Fix and enforce checkstyle (#3380)

* Checkstyle improvements.

* Checkstyle improvements.

* Checkstyle improvements.

* Finish checkstyle cleanup. Turn failOnError on.

* Fix incorrect final class
This commit is contained in:
Olga Maciaszek-Sharma
2019-02-07 22:16:44 +01:00
committed by GitHub
parent b0335afd69
commit 805818941c
405 changed files with 11308 additions and 8510 deletions
+16
View File
@@ -0,0 +1,16 @@
root=true
[*.java]
indent_style = tab
indent_size = 4
continuation_indent_size = 8
[*.groovy]
indent_style = tab
indent_size = 4
continuation_indent_size = 8
[*.xml]
indent_style = tab
indent_size = 4
continuation_indent_size = 8
-3
View File
@@ -17,9 +17,6 @@ specific language governing permissions and limitations
under the License.
*/
import java.net.*;
import java.io.*;
import java.nio.channels.*;
import java.util.Properties;
public class MavenWrapperDownloader {
+20
View File
@@ -32,6 +32,10 @@
<sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
<sonar.jacoco.reportPath>${project.basedir}/../target/jacoco.exec</sonar.jacoco.reportPath>
<sonar.language>java</sonar.language>
<maven-checkstyle-plugin.includeTestSourceDirectory>true
</maven-checkstyle-plugin.includeTestSourceDirectory>
<maven-checkstyle-plugin.failOnViolation>true
</maven-checkstyle-plugin.failOnViolation>
</properties>
<build>
<plugins>
@@ -61,6 +65,14 @@
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>io.spring.javaformat</groupId>
<artifactId>spring-javaformat-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencyManagement>
@@ -132,6 +144,14 @@
<!-- end archaius deps -->
</dependencies>
</dependencyManagement>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-checkstyle-plugin</artifactId>
</plugin>
</plugins>
</reporting>
<modules>
<module>spring-cloud-netflix-dependencies</module>
<module>spring-cloud-netflix-archaius</module>
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,6 +24,13 @@ import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.PreDestroy;
import com.netflix.config.AggregatedConfiguration;
import com.netflix.config.ConcurrentCompositeConfiguration;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DeploymentContext;
import com.netflix.config.DynamicProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicURLConfiguration;
import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.ConfigurationBuilder;
import org.apache.commons.configuration.EnvironmentConfiguration;
@@ -32,6 +39,7 @@ import org.apache.commons.configuration.event.ConfigurationEvent;
import org.apache.commons.configuration.event.ConfigurationListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.health.Health;
@@ -48,14 +56,6 @@ import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.util.ReflectionUtils;
import com.netflix.config.AggregatedConfiguration;
import com.netflix.config.ConcurrentCompositeConfiguration;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DeploymentContext;
import com.netflix.config.DynamicProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicURLConfiguration;
import static com.netflix.config.ConfigurationManager.APPLICATION_PROPERTIES;
import static com.netflix.config.ConfigurationManager.DISABLE_DEFAULT_ENV_CONFIG;
import static com.netflix.config.ConfigurationManager.DISABLE_DEFAULT_SYS_CONFIG;
@@ -98,52 +98,21 @@ public class ArchaiusAutoConfiguration {
}
@Bean
public static ConfigurableEnvironmentConfiguration configurableEnvironmentConfiguration(ConfigurableEnvironment env,
ApplicationContext context) {
Map<String, AbstractConfiguration> abstractConfigurationMap = context.getBeansOfType(AbstractConfiguration.class);
List<AbstractConfiguration> externalConfigurations = new ArrayList<>(abstractConfigurationMap.values());
ConfigurableEnvironmentConfiguration envConfig = new ConfigurableEnvironmentConfiguration(env);
public static ConfigurableEnvironmentConfiguration configurableEnvironmentConfiguration(
ConfigurableEnvironment env, ApplicationContext context) {
Map<String, AbstractConfiguration> abstractConfigurationMap = context
.getBeansOfType(AbstractConfiguration.class);
List<AbstractConfiguration> externalConfigurations = new ArrayList<>(
abstractConfigurationMap.values());
ConfigurableEnvironmentConfiguration envConfig = new ConfigurableEnvironmentConfiguration(
env);
configureArchaius(envConfig, env, externalConfigurations);
return envConfig;
}
@Configuration
@ConditionalOnClass(Health.class)
protected static class ArchaiusEndpointConfiguration {
@Bean
@ConditionalOnEnabledEndpoint
protected ArchaiusEndpoint archaiusEndpoint() {
return new ArchaiusEndpoint();
}
}
@Configuration
@ConditionalOnProperty(value = "archaius.propagate.environmentChangedEvent", matchIfMissing = true)
@ConditionalOnClass(EnvironmentChangeEvent.class)
protected static class PropagateEventsConfiguration
implements ApplicationListener<EnvironmentChangeEvent> {
@Autowired
private Environment env;
@Override
public void onApplicationEvent(EnvironmentChangeEvent event) {
AbstractConfiguration manager = ConfigurationManager.getConfigInstance();
for (String key : event.getKeys()) {
for (ConfigurationListener listener : manager
.getConfigurationListeners()) {
Object source = event.getSource();
// TODO: Handle add vs set vs delete?
int type = AbstractConfiguration.EVENT_SET_PROPERTY;
String value = this.env.getProperty(key);
boolean beforeUpdate = false;
listener.configurationChanged(new ConfigurationEvent(source, type,
key, value, beforeUpdate));
}
}
}
}
protected static void configureArchaius(ConfigurableEnvironmentConfiguration envConfig, ConfigurableEnvironment env, List<AbstractConfiguration> externalConfigurations) {
protected static void configureArchaius(
ConfigurableEnvironmentConfiguration envConfig, ConfigurableEnvironment env,
List<AbstractConfiguration> externalConfigurations) {
if (initialized.compareAndSet(false, true)) {
String appName = env.getProperty("spring.application.name");
if (appName == null) {
@@ -196,7 +165,8 @@ public class ArchaiusAutoConfiguration {
}
}
private static void addArchaiusConfiguration(ConcurrentCompositeConfiguration config) {
private static void addArchaiusConfiguration(
ConcurrentCompositeConfiguration config) {
if (ConfigurationManager.isConfigurationInstalled()) {
AbstractConfiguration installedConfiguration = ConfigurationManager
.getConfigInstance();
@@ -224,4 +194,44 @@ public class ArchaiusAutoConfiguration {
ReflectionUtils.setField(field, null, value);
}
@Configuration
@ConditionalOnClass(Health.class)
protected static class ArchaiusEndpointConfiguration {
@Bean
@ConditionalOnEnabledEndpoint
protected ArchaiusEndpoint archaiusEndpoint() {
return new ArchaiusEndpoint();
}
}
@Configuration
@ConditionalOnProperty(value = "archaius.propagate.environmentChangedEvent", matchIfMissing = true)
@ConditionalOnClass(EnvironmentChangeEvent.class)
protected static class PropagateEventsConfiguration
implements ApplicationListener<EnvironmentChangeEvent> {
@Autowired
private Environment env;
@Override
public void onApplicationEvent(EnvironmentChangeEvent event) {
AbstractConfiguration manager = ConfigurationManager.getConfigInstance();
for (String key : event.getKeys()) {
for (ConfigurationListener listener : manager
.getConfigurationListeners()) {
Object source = event.getSource();
// TODO: Handle add vs set vs delete?
int type = AbstractConfiguration.EVENT_SET_PROPERTY;
String value = this.env.getProperty(key);
boolean beforeUpdate = false;
listener.configurationChanged(new ConfigurationEvent(source, type,
key, value, beforeUpdate));
}
}
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,24 +16,30 @@
package org.springframework.cloud.netflix.archaius;
import com.netflix.config.ConfigurationManager;
import org.apache.commons.configuration.AbstractConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import com.netflix.config.ConfigurationManager;
/**
* @author Dave Syer
*/
public class ArchaiusDelegatingProxyUtils {
public final class ArchaiusDelegatingProxyUtils {
private ArchaiusDelegatingProxyUtils() {
}
/**
* {@code ApplicationContext} class name.
*/
public static String APPLICATION_CONTEXT = ApplicationContext.class.getName();
public static <T> T getNamedInstance(Class<T> type, String name) {
ApplicationContext context = (ApplicationContext) ConfigurationManager
.getConfigInstance().getProperty(APPLICATION_CONTEXT);
return context != null && context.containsBean(name) ? context
.getBean(name, type) : null;
return context != null && context.containsBean(name) ? context.getBean(name, type)
: null;
}
public static <T> T getInstanceWithPrefix(Class<T> type, String prefix) {
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,17 +20,19 @@ import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import com.netflix.config.ConcurrentCompositeConfiguration;
import com.netflix.config.ConfigurationManager;
import org.apache.commons.configuration.AbstractConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.EnvironmentConfiguration;
import org.apache.commons.configuration.SystemConfiguration;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import com.netflix.config.ConcurrentCompositeConfiguration;
import com.netflix.config.ConfigurationManager;
/**
* An actuator endpoint that returns Archaius configuration.
*
* @author Dave Syer
*/
@Endpoint(id = "archaius")
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +23,7 @@ import java.util.List;
import java.util.Map;
import org.apache.commons.configuration.AbstractConfiguration;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
@@ -31,6 +32,8 @@ import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;
/**
* EnvironmentConfiguration wrapper class providing further configuration possibilities.
*
* @author Spencer Gibb
*/
public class ConfigurableEnvironmentConfiguration extends AbstractConfiguration {
@@ -64,7 +67,8 @@ public class ConfigurableEnvironmentConfiguration extends AbstractConfiguration
@Override
public Iterator<String> getKeys() {
List<String> result = new ArrayList<>();
for (Map.Entry<String, PropertySource<?>> entry : getPropertySources().entrySet()) {
for (Map.Entry<String, PropertySource<?>> entry : getPropertySources()
.entrySet()) {
PropertySource<?> source = entry.getValue();
if (source instanceof EnumerablePropertySource) {
EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) source;
@@ -78,8 +82,9 @@ public class ConfigurableEnvironmentConfiguration extends AbstractConfiguration
private Map<String, PropertySource<?>> getPropertySources() {
Map<String, PropertySource<?>> map = new LinkedHashMap<>();
MutablePropertySources sources = (this.environment != null ? this.environment
.getPropertySources() : new StandardEnvironment().getPropertySources());
MutablePropertySources sources = (this.environment != null
? this.environment.getPropertySources()
: new StandardEnvironment().getPropertySources());
for (PropertySource<?> source : sources) {
extract("", map, source);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,27 +12,24 @@
* 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 org.springframework.cloud.netflix.archaius;
import java.util.Collections;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import org.apache.commons.configuration.AbstractConfiguration;
import org.junit.After;
import org.junit.Test;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.config.DynamicStringProperty;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Dave Syer
@@ -40,6 +37,7 @@ import static org.junit.Assert.assertNull;
public class ArchaiusAutoConfigurationTests {
private AnnotationConfigApplicationContext context;
private Object propertyValue;
@After
@@ -55,24 +53,23 @@ public class ArchaiusAutoConfigurationTests {
ArchaiusAutoConfiguration.class);
AbstractConfiguration config = this.context
.getBean(ConfigurableEnvironmentConfiguration.class);
assertNotNull(config.getString("java.io.tmpdir"));
assertThat(config.getString("java.io.tmpdir")).isNotNull();
}
@Test
public void environmentChangeEventPropagated() {
this.context = new AnnotationConfigApplicationContext(
ArchaiusAutoConfiguration.class);
ConfigurationManager.getConfigInstance().addConfigurationListener(
event -> {
ConfigurationManager.getConfigInstance().addConfigurationListener(event -> {
if (event.getPropertyName().equals("my.prop")) {
ArchaiusAutoConfigurationTests.this.propertyValue = event
.getPropertyValue();
}
});
TestPropertyValues.of("my.prop=my.newval").applyTo(this.context);
this.context.publishEvent(new EnvironmentChangeEvent(Collections
.singleton("my.prop")));
assertEquals("my.newval", this.propertyValue);
this.context.publishEvent(
new EnvironmentChangeEvent(Collections.singleton("my.prop")));
assertThat(this.propertyValue).isEqualTo("my.newval");
}
@Test
@@ -84,9 +81,9 @@ public class ArchaiusAutoConfigurationTests {
DynamicStringProperty staticProperty = DynamicPropertyFactory.getInstance()
.getStringProperty("archaius.file.property", null);
assertNull(dbProperty.getValue());
assertNotNull(staticProperty.getValue());
assertEquals("Static config file property", staticProperty.getValue());
assertThat(dbProperty.getValue()).isNull();
assertThat(staticProperty.getValue()).isNotNull();
assertThat(staticProperty.getValue()).isEqualTo("Static config file property");
}
@Test
@@ -100,12 +97,12 @@ public class ArchaiusAutoConfigurationTests {
DynamicStringProperty staticProperty = DynamicPropertyFactory.getInstance()
.getStringProperty("archaius.file.property", null);
assertNotNull(dbProperty.getValue());
assertNotNull(secondDbProperty.getValue());
assertNotNull(staticProperty.getValue());
assertEquals("this is a db property", dbProperty.getValue());
assertEquals("this is another db property", secondDbProperty.getValue());
assertEquals("Static config file property", staticProperty.getValue());
assertThat(dbProperty.getValue()).isNotNull();
assertThat(secondDbProperty.getValue()).isNotNull();
assertThat(staticProperty.getValue()).isNotNull();
assertThat(dbProperty.getValue()).isEqualTo("this is a db property");
assertThat(secondDbProperty.getValue()).isEqualTo("this is another db property");
assertThat(staticProperty.getValue()).isEqualTo("Static config file property");
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,14 +18,13 @@ package org.springframework.cloud.netflix.archaius;
import java.util.Map;
import org.junit.Test;
import org.springframework.core.env.StandardEnvironment;
import com.netflix.config.ConcurrentCompositeConfiguration;
import com.netflix.config.ConfigurationManager;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.springframework.core.env.StandardEnvironment;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Dave Syer
@@ -37,7 +36,7 @@ public class ArchaiusEndpointTests {
@Test
public void detectsPropertiesWhenSet() {
ConfigurationManager.getConfigInstance().setProperty("foo", "bar");
assertTrue(this.endpoint.invoke().containsKey("foo"));
assertThat(this.endpoint.invoke().containsKey("foo")).isTrue();
}
@Test
@@ -46,12 +45,12 @@ public class ArchaiusEndpointTests {
ConfigurationManager.getConfigInstance());
ConfigurableEnvironmentConfiguration config = new ConfigurableEnvironmentConfiguration(
new StandardEnvironment());
assertTrue(config.containsKey("user.dir"));
assertThat(config.containsKey("user.dir")).isTrue();
composite.addConfiguration(config);
ConfigurationManager.getConfigInstance().setProperty("foo", "bar");
Map<String, Object> map = this.endpoint.invoke();
assertTrue(map.containsKey("foo"));
assertFalse(map.containsKey("user.dir"));
assertThat(map.containsKey("foo")).isTrue();
assertThat(map.containsKey("user.dir")).isFalse();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,13 +16,13 @@
package org.springframework.cloud.netflix.archaius;
import com.netflix.config.ConcurrentMapConfiguration;
import org.apache.commons.configuration.AbstractConfiguration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.config.ConcurrentMapConfiguration;
/**
* @author Alexandru-George Burghelea
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.concurrency.limits.micrometer;
@@ -24,9 +23,15 @@ import io.micrometer.core.instrument.DistributionSummary;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tags;
/**
* A Micrometer-specific {@link MetricRegistry} implementation.
*
* @author Spencer Gibb
*/
public class MicrometerMetricRegistry implements MetricRegistry {
private final MeterRegistry meterRegistry;
// TODO: baseId?
public MicrometerMetricRegistry(MeterRegistry meterRegistry) {
@@ -40,7 +45,9 @@ public class MicrometerMetricRegistry implements MetricRegistry {
}
@Override
public void registerGauge(String id, Supplier<Number> supplier, String... tagNameValuePairs) {
public void registerGauge(String id, Supplier<Number> supplier,
String... tagNameValuePairs) {
this.meterRegistry.gauge(id, Tags.of(tagNameValuePairs), supplier.get());
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.concurrency.limits.reactive;
@@ -25,6 +24,12 @@ import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
/**
* A {@link WebFilter} implementation providing the possibility to use Netflix
* {@link Limiter} to handle requests.
*
* @author Spencer Gibb
*/
public class ConcurrencyLimitsWebFilter implements WebFilter {
private final Limiter<ServerWebExchange> limiter;
@@ -45,4 +50,5 @@ public class ConcurrencyLimitsWebFilter implements WebFilter {
return exchange.getResponse().setComplete();
});
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,25 +12,30 @@
* 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 org.springframework.cloud.netflix.concurrency.limits.reactive;
import com.netflix.concurrency.limits.Limiter;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.WebFilter;
import java.util.function.Consumer;
import com.netflix.concurrency.limits.Limiter;
import reactor.core.publisher.Mono;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
/**
* Reactive autoconfiguration class for registering Netflix {@link Limiter} bean.
*
* @author Spencer Gibb
*/
@Configuration
@ConditionalOnWebApplication(type = Type.REACTIVE)
@ConditionalOnClass({ WebFilter.class, Mono.class })
@@ -38,7 +43,8 @@ public class ReactiveConcurrencyLimitsAutoConfiguration {
private final ObjectProvider<Consumer<ServerWebExchangeLimiterBuilder>> configurerProvider;
public ReactiveConcurrencyLimitsAutoConfiguration(ObjectProvider<Consumer<ServerWebExchangeLimiterBuilder>> configurerProvider) {
public ReactiveConcurrencyLimitsAutoConfiguration(
ObjectProvider<Consumer<ServerWebExchangeLimiterBuilder>> configurerProvider) {
this.configurerProvider = configurerProvider;
}
@@ -53,7 +59,9 @@ public class ReactiveConcurrencyLimitsAutoConfiguration {
}
@Bean
public ConcurrencyLimitsWebFilter concurrencyLimitsWebFilter(Limiter<ServerWebExchange> limiter) {
public ConcurrencyLimitsWebFilter concurrencyLimitsWebFilter(
Limiter<ServerWebExchange> limiter) {
return new ConcurrencyLimitsWebFilter(limiter);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,12 +12,10 @@
* 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 org.springframework.cloud.netflix.concurrency.limits.reactive;
import java.security.Principal;
import java.util.Optional;
import java.util.function.Function;
@@ -25,31 +23,44 @@ import com.netflix.concurrency.limits.limiter.AbstractPartitionedLimiter;
import org.springframework.web.server.ServerWebExchange;
public class ServerWebExchangeLimiterBuilder extends AbstractPartitionedLimiter.Builder<ServerWebExchangeLimiterBuilder, ServerWebExchange> {
/**
* Partition the limit by header
* Builder for ServerWebExchange Limiter.
*
* @author Spencer Gibb
*/
public class ServerWebExchangeLimiterBuilder extends
AbstractPartitionedLimiter.Builder<ServerWebExchangeLimiterBuilder, ServerWebExchange> {
/**
* Partition the limit by header.
* @param name header name
* @return Chainable builder
*/
public ServerWebExchangeLimiterBuilder partitionByHeader(String name) {
return partitionResolver(exchange -> exchange.getRequest().getHeaders().getFirst(name));
return partitionResolver(
exchange -> exchange.getRequest().getHeaders().getFirst(name));
}
/**
* Partition the limit by {@link Principal}. Percentages of the limit are partitioned to named
* groups. Group membership is derived from the provided mapping function.
* Partition the limit by {@link Principal}. Percentages of the limit are partitioned
* to named groups. Group membership is derived from the provided mapping function.
* @param principalToGroup Mapping function from {@link Principal} to a named group.
* @param configurer Configuration function though which group percentages may be specified
* Unspecified group values may only use excess capacity.
* @param configurer Configuration function though which group percentages may be
* specified Unspecified group values may only use excess capacity.
* @return Chainable builder
*/
/*public ServerWebExchangeLimiterBuilder partitionByUserPrincipal(Function<Principal, String> principalToGroup, Consumer<LookupPartitionStrategy.Builder<ServerWebExchange>> configurer) {
return partitionResolver(
exchange -> Optional.ofNullable(request.getUserPrincipal()).map(principalToGroup).orElse(null),
configurer);
}*/
/*
* public ServerWebExchangeLimiterBuilder partitionByUserPrincipal(Function<Principal,
* String> principalToGroup,
* Consumer<LookupPartitionStrategy.Builder<ServerWebExchange>> configurer) { return
* partitionResolver( exchange ->
* Optional.ofNullable(request.getUserPrincipal()).map(principalToGroup).orElse(null),
* configurer); }
*/
/**
* Partition the limit by request attribute
* Partition the limit by request attribute.
* @param name attribute name
* @return Chainable builder
*/
public ServerWebExchangeLimiterBuilder partitionByAttribute(String name) {
@@ -57,22 +68,24 @@ public class ServerWebExchangeLimiterBuilder extends AbstractPartitionedLimiter.
}
/**
* Partition the limit by request parameter
* Partition the limit by request parameter.
* @param name parameter name
* @return Chainable builder
*/
public ServerWebExchangeLimiterBuilder partitionByParameter(String name) {
return partitionResolver(exchange -> exchange.getRequest().getQueryParams().getFirst(name));
return partitionResolver(
exchange -> exchange.getRequest().getQueryParams().getFirst(name));
}
/**
* Partition the limit by the full path. Percentages of the limit are partitioned to named
* groups. Group membership is derived from the provided mapping function.
* Partition the limit by the full path. Percentages of the limit are partitioned to
* named groups. Group membership is derived from the provided mapping function.
* @param pathToGroup Mapping function from full path to a named group.
* @return Chainable builder
*/
public ServerWebExchangeLimiterBuilder partitionByPathInfo(Function<String, String> pathToGroup) {
return partitionResolver(
exchange -> {
public ServerWebExchangeLimiterBuilder partitionByPathInfo(
Function<String, String> pathToGroup) {
return partitionResolver(exchange -> {
// TODO: pathWithinApplication?
String path = exchange.getRequest().getPath().contextPath().value();
return Optional.ofNullable(path).map(pathToGroup).orElse(null);
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.concurrency.limits.web;
@@ -30,6 +29,12 @@ import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* A {@link HandlerInterceptor} implementation providing the possibility to use Netflix
* {@link Limiter} to handle requests.
*
* @author Spencer Gibb
*/
public class ConcurrencyLimitsHandlerInterceptor implements HandlerInterceptor {
private final Limiter<HttpServletRequest> limiter;
@@ -39,7 +44,8 @@ public class ConcurrencyLimitsHandlerInterceptor implements HandlerInterceptor {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
Optional<Listener> listener = limiter.acquire(request);
if (listener.isPresent()) {
request.setAttribute("concurrency_limiter_listener", listener.get());
@@ -48,28 +54,35 @@ public class ConcurrencyLimitsHandlerInterceptor implements HandlerInterceptor {
try {
// TODO: headers with information?
/*response.sendError(HttpStatus.TOO_MANY_REQUESTS.value());
response.getWriter().print("Concurrency limit exceeded");*/
/*
* response.sendError(HttpStatus.TOO_MANY_REQUESTS.value());
* response.getWriter().print("Concurrency limit exceeded");
*/
response.sendError(HttpStatus.TOO_MANY_REQUESTS.value(),
"Concurrency limit exceeded");
} catch (IOException e) {
}
catch (IOException e) {
// ignore
}
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
Listener listener = (Listener) request.getAttribute("concurrency_limiter_listener");
public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
Object handler, Exception ex) throws Exception {
Listener listener = (Listener) request
.getAttribute("concurrency_limiter_listener");
if (listener != null) {
if (ex != null) {
listener.onIgnore();
} else {
}
else {
listener.onSuccess();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,8 +12,8 @@
* 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 org.springframework.cloud.netflix.concurrency.limits.web;
import java.util.function.Consumer;
@@ -35,6 +35,11 @@ import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* MVC autoconfiguration class for registering Netflix {@link Limiter} bean.
*
* @author Spencer Gibb
*/
@Configuration
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ HttpServletRequest.class, HandlerInterceptor.class })
@@ -42,7 +47,8 @@ public class MvcConcurrencyLimitsAutoConfiguration implements WebMvcConfigurer {
private final ObjectProvider<Consumer<ServletLimiterBuilder>> configurerProvider;
public MvcConcurrencyLimitsAutoConfiguration(ObjectProvider<Consumer<ServletLimiterBuilder>> configurerProvider) {
public MvcConcurrencyLimitsAutoConfiguration(
ObjectProvider<Consumer<ServletLimiterBuilder>> configurerProvider) {
this.configurerProvider = configurerProvider;
}
@@ -62,10 +68,11 @@ public class MvcConcurrencyLimitsAutoConfiguration implements WebMvcConfigurer {
@Autowired
private Limiter<HttpServletRequest> limiter;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ConcurrencyLimitsHandlerInterceptor(limiter));
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.concurrency.limits.micrometer;
@@ -26,6 +25,7 @@ import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class MicrometerMetricRegistryTests {
@Test
public void testGuage() {
MeterRegistry registry = new SimpleMeterRegistry();
@@ -52,5 +52,5 @@ public class MicrometerMetricRegistryTests {
assertThat(bar.value()).isEqualTo(20.0);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.concurrency.limits.reactive;
@@ -53,7 +52,8 @@ public class ConcurrencyLimitsWebFilterTests extends AbstractConcurrencyLimitsTe
public void webFilterWorks() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder()
.properties("server.port="+port, "spring.main.web-application-type=reactive")
.properties("server.port=" + port,
"spring.main.web-application-type=reactive")
.sources(TestConfig.class).run()) {
assertLimiter(client);
@@ -67,9 +67,9 @@ public class ConcurrencyLimitsWebFilterTests extends AbstractConcurrencyLimitsTe
@Bean
public Consumer<ServerWebExchangeLimiterBuilder> limiterBuilderConfigurer() {
return limiterBuilder -> limiterBuilder
.limit(FixedLimit.of(1));
return limiterBuilder -> limiterBuilder.limit(FixedLimit.of(1));
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.concurrency.limits.test;
@@ -39,23 +38,23 @@ public class AbstractConcurrencyLimitsTests {
Flux<Tuple2<String, HttpStatus>> flux = Flux.range(1, 100)
.flatMap(integer -> client.get().uri("/").exchange(), 4)
// .log("reqs", Level.INFO)
.flatMap(response -> response.bodyToMono(String.class)
.defaultIfEmpty("")
.flatMap(response -> response.bodyToMono(String.class).defaultIfEmpty("")
/* .log("body2mono", Level.INFO) */
.zipWith(Mono.just(response.statusCode())));
Responses responses = new Responses();
StepVerifier.create(flux)
.thenConsumeWhile(response -> true, response -> {
StepVerifier.create(flux).thenConsumeWhile(response -> true, response -> {
HttpStatus status = response.getT2();
if (status.equals(HttpStatus.OK)) {
responses.success.incrementAndGet();
} else if (status.equals(HttpStatus.TOO_MANY_REQUESTS)) {
}
else if (status.equals(HttpStatus.TOO_MANY_REQUESTS)) {
responses.tooManyReqs.incrementAndGet();
String body = response.getT1();
// TODO: body from handler isn't coming thru
// assertThat(body).isEqualTo("Concurrency limit exceeded");
} else {
}
else {
responses.other.incrementAndGet();
}
}).verifyComplete();
@@ -75,5 +74,7 @@ public class AbstractConcurrencyLimitsTests {
public String get() {
return "Hello";
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,26 +12,26 @@
* 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 org.springframework.cloud.netflix.concurrency.limits.test;
import org.springframework.core.style.ToStringCreator;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.core.style.ToStringCreator;
public class Responses {
public AtomicInteger success = new AtomicInteger(0);
public AtomicInteger tooManyReqs = new AtomicInteger(0);
public AtomicInteger other = new AtomicInteger(0);
@Override
public String toString() {
return new ToStringCreator(this)
.append("success", success)
.append("tooManyReqs", tooManyReqs)
.append("other", other)
.toString();
return new ToStringCreator(this).append("success", success)
.append("tooManyReqs", tooManyReqs).append("other", other).toString();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.concurrency.limits.web;
@@ -39,7 +38,8 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "logging.level.reactor.netty=DEBUG", webEnvironment = RANDOM_PORT)
public class ConcurrencyLimitsHandlerInterceptorTests extends AbstractConcurrencyLimitsTests {
public class ConcurrencyLimitsHandlerInterceptorTests
extends AbstractConcurrencyLimitsTests {
@LocalServerPort
public int port;
@@ -61,9 +61,9 @@ public class ConcurrencyLimitsHandlerInterceptorTests extends AbstractConcurrenc
@Bean
public Consumer<ServletLimiterBuilder> limiterBuilderConfigurer() {
return servletLimiterBuilder -> servletLimiterBuilder
.limit(FixedLimit.of(1));
return servletLimiterBuilder -> servletLimiterBuilder.limit(FixedLimit.of(1));
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2018 the original author or authors.
* Copyright 2018-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,12 +18,14 @@ package org.springframework.cloud.netflix.core;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.annotation.Configuration;
/**
* @author Olga Maciaszek-Sharma
* @since 2.1.0
* @deprecated Module spring-cloud-netflix-core is deprecated as of 2.1.0, use spring-cloud-netflix-hystrix instead.
* @deprecated Module spring-cloud-netflix-core is deprecated as of 2.1.0, use
* spring-cloud-netflix-hystrix instead.
*/
@Configuration
@Deprecated
@@ -32,7 +34,9 @@ public class CoreAutoConfiguration {
private static final Log LOG = LogFactory.getLog(CoreAutoConfiguration.class);
public CoreAutoConfiguration() {
LOG.warn("This module is deprecated. It will be removed in the next major release. " +
"Please use spring-cloud-netflix-hystrix instead.");
LOG.warn(
"This module is deprecated. It will be removed in the next major release. "
+ "Please use spring-cloud-netflix-hystrix instead.");
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,13 +20,6 @@ import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.util.ReflectionUtils;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
@@ -35,20 +28,32 @@ import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;
import org.springframework.util.ReflectionUtils;
/**
* Subclass of {@link DiscoveryClient} that sends a {@link HeartbeatEvent} when
* {@link CloudEurekaClient#onCacheRefreshed()} is called.
*
* @author Spencer Gibb
*/
public class CloudEurekaClient extends DiscoveryClient {
private static final Log log = LogFactory.getLog(CloudEurekaClient.class);
private final AtomicLong cacheRefreshedCount = new AtomicLong(0);
private ApplicationEventPublisher publisher;
private Field eurekaTransportField;
private ApplicationInfoManager applicationInfoManager;
private AtomicReference<EurekaHttpClient> eurekaHttpClient = new AtomicReference<>();
public CloudEurekaClient(ApplicationInfoManager applicationInfoManager,
@@ -57,13 +62,13 @@ public class CloudEurekaClient extends DiscoveryClient {
}
public CloudEurekaClient(ApplicationInfoManager applicationInfoManager,
EurekaClientConfig config,
AbstractDiscoveryClientOptionalArgs<?> args,
EurekaClientConfig config, AbstractDiscoveryClientOptionalArgs<?> args,
ApplicationEventPublisher publisher) {
super(applicationInfoManager, config, args);
this.applicationInfoManager = applicationInfoManager;
this.publisher = publisher;
this.eurekaTransportField = ReflectionUtils.findField(DiscoveryClient.class, "eurekaTransport");
this.eurekaTransportField = ReflectionUtils.findField(DiscoveryClient.class,
"eurekaTransport");
ReflectionUtils.makeAccessible(this.eurekaTransportField);
}
@@ -76,7 +81,8 @@ public class CloudEurekaClient extends DiscoveryClient {
}
public InstanceInfo getInstanceInfo(String appname, String instanceId) {
EurekaHttpResponse<InstanceInfo> response = getEurekaHttpClient().getInstance(appname, instanceId);
EurekaHttpResponse<InstanceInfo> response = getEurekaHttpClient()
.getInstance(appname, instanceId);
HttpStatus httpStatus = HttpStatus.valueOf(response.getStatusCode());
if (httpStatus.is2xxSuccessful() && response.getEntity() != null) {
return response.getEntity();
@@ -88,10 +94,13 @@ public class CloudEurekaClient extends DiscoveryClient {
if (this.eurekaHttpClient.get() == null) {
try {
Object eurekaTransport = this.eurekaTransportField.get(this);
Field registrationClientField = ReflectionUtils.findField(eurekaTransport.getClass(), "registrationClient");
Field registrationClientField = ReflectionUtils
.findField(eurekaTransport.getClass(), "registrationClient");
ReflectionUtils.makeAccessible(registrationClientField);
this.eurekaHttpClient.compareAndSet(null, (EurekaHttpClient) registrationClientField.get(eurekaTransport));
} catch (IllegalAccessException e) {
this.eurekaHttpClient.compareAndSet(null,
(EurekaHttpClient) registrationClientField.get(eurekaTransport));
}
catch (IllegalAccessException e) {
log.error("error getting EurekaHttpClient", e);
}
}
@@ -99,17 +108,20 @@ public class CloudEurekaClient extends DiscoveryClient {
}
public void setStatus(InstanceStatus newStatus, InstanceInfo info) {
getEurekaHttpClient().statusUpdate(info.getAppName(), info.getId(), newStatus, info);
getEurekaHttpClient().statusUpdate(info.getAppName(), info.getId(), newStatus,
info);
}
@Override
protected void onCacheRefreshed() {
super.onCacheRefreshed();
if (this.cacheRefreshedCount != null) { //might be called during construction and will be null
if (this.cacheRefreshedCount != null) { // might be called during construction and
// will be null
long newCount = this.cacheRefreshedCount.incrementAndGet();
log.trace("onCacheRefreshed called with count: " + newCount);
this.publisher.publishEvent(new HeartbeatEvent(this, newCount));
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,11 @@ import com.netflix.appinfo.InstanceInfo;
* @author Spencer Gibb
*/
public interface CloudEurekaInstanceConfig extends EurekaInstanceConfig {
void setNonSecurePort(int port);
void setSecurePort(int securePort);
InstanceInfo.InstanceStatus getInitialStatus();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,10 @@
package org.springframework.cloud.netflix.eureka;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
import java.util.Objects;
import com.netflix.discovery.shared.transport.EurekaTransportConfig;
/**
* @author Spencer Gibb
* @author Gregor Zurowski
@@ -162,21 +162,27 @@ public class CloudEurekaTransportConfig implements EurekaTransportConfig {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CloudEurekaTransportConfig that = (CloudEurekaTransportConfig) o;
return sessionedClientReconnectIntervalSeconds == that.sessionedClientReconnectIntervalSeconds &&
Double.compare(retryableClientQuarantineRefreshPercentage, that.retryableClientQuarantineRefreshPercentage) == 0 &&
bootstrapResolverRefreshIntervalSeconds == that.bootstrapResolverRefreshIntervalSeconds &&
applicationsResolverDataStalenessThresholdSeconds == that.applicationsResolverDataStalenessThresholdSeconds &&
asyncResolverRefreshIntervalMs == that.asyncResolverRefreshIntervalMs &&
asyncResolverWarmUpTimeoutMs == that.asyncResolverWarmUpTimeoutMs &&
asyncExecutorThreadPoolSize == that.asyncExecutorThreadPoolSize &&
Objects.equals(readClusterVip, that.readClusterVip) &&
Objects.equals(writeClusterVip, that.writeClusterVip) &&
bootstrapResolverForQuery == that.bootstrapResolverForQuery &&
Objects.equals(bootstrapResolverStrategy, that.bootstrapResolverStrategy) &&
applicationsResolverUseIp == that.applicationsResolverUseIp;
return sessionedClientReconnectIntervalSeconds == that.sessionedClientReconnectIntervalSeconds
&& Double.compare(retryableClientQuarantineRefreshPercentage,
that.retryableClientQuarantineRefreshPercentage) == 0
&& bootstrapResolverRefreshIntervalSeconds == that.bootstrapResolverRefreshIntervalSeconds
&& applicationsResolverDataStalenessThresholdSeconds == that.applicationsResolverDataStalenessThresholdSeconds
&& asyncResolverRefreshIntervalMs == that.asyncResolverRefreshIntervalMs
&& asyncResolverWarmUpTimeoutMs == that.asyncResolverWarmUpTimeoutMs
&& asyncExecutorThreadPoolSize == that.asyncExecutorThreadPoolSize
&& Objects.equals(readClusterVip, that.readClusterVip)
&& Objects.equals(writeClusterVip, that.writeClusterVip)
&& bootstrapResolverForQuery == that.bootstrapResolverForQuery
&& Objects.equals(bootstrapResolverStrategy,
that.bootstrapResolverStrategy)
&& applicationsResolverUseIp == that.applicationsResolverUseIp;
}
@Override
@@ -194,18 +200,27 @@ public class CloudEurekaTransportConfig implements EurekaTransportConfig {
@Override
public String toString() {
return new StringBuilder("CloudEurekaTransportConfig{")
.append("sessionedClientReconnectIntervalSeconds=").append(sessionedClientReconnectIntervalSeconds).append(", ")
.append("retryableClientQuarantineRefreshPercentage=").append(retryableClientQuarantineRefreshPercentage).append(", ")
.append("bootstrapResolverRefreshIntervalSeconds=").append(bootstrapResolverRefreshIntervalSeconds).append(", ")
.append("applicationsResolverDataStalenessThresholdSeconds=").append(applicationsResolverDataStalenessThresholdSeconds).append(", ")
.append("asyncResolverRefreshIntervalMs=").append(asyncResolverRefreshIntervalMs).append(", ")
.append("asyncResolverWarmUpTimeoutMs=").append(asyncResolverWarmUpTimeoutMs).append(", ")
.append("asyncExecutorThreadPoolSize=").append(asyncExecutorThreadPoolSize).append(", ")
.append("sessionedClientReconnectIntervalSeconds=")
.append(sessionedClientReconnectIntervalSeconds).append(", ")
.append("retryableClientQuarantineRefreshPercentage=")
.append(retryableClientQuarantineRefreshPercentage).append(", ")
.append("bootstrapResolverRefreshIntervalSeconds=")
.append(bootstrapResolverRefreshIntervalSeconds).append(", ")
.append("applicationsResolverDataStalenessThresholdSeconds=")
.append(applicationsResolverDataStalenessThresholdSeconds).append(", ")
.append("asyncResolverRefreshIntervalMs=")
.append(asyncResolverRefreshIntervalMs).append(", ")
.append("asyncResolverWarmUpTimeoutMs=")
.append(asyncResolverWarmUpTimeoutMs).append(", ")
.append("asyncExecutorThreadPoolSize=")
.append(asyncExecutorThreadPoolSize).append(", ")
.append("readClusterVip='").append(readClusterVip).append("', ")
.append("writeClusterVip='").append(writeClusterVip).append("', ")
.append("bootstrapResolverForQuery=").append(bootstrapResolverForQuery).append(", ")
.append("bootstrapResolverStrategy='").append(bootstrapResolverStrategy).append("', ")
.append("applicationsResolverUseIp=").append(applicationsResolverUseIp).append(", ").append("}")
.toString();
.append("bootstrapResolverForQuery=").append(bootstrapResolverForQuery)
.append(", ").append("bootstrapResolverStrategy='")
.append(bootstrapResolverStrategy).append("', ")
.append("applicationsResolverUseIp=").append(applicationsResolverUseIp)
.append(", ").append("}").toString();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +23,14 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
@@ -64,14 +72,6 @@ import org.springframework.context.annotation.Lazy;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.StringUtils;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import static org.springframework.cloud.commons.util.IdUtils.getDefaultInstanceId;
/**
@@ -90,7 +90,8 @@ import static org.springframework.cloud.commons.util.IdUtils.getDefaultInstanceI
@ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true)
@AutoConfigureBefore({ NoopDiscoveryClientAutoConfiguration.class,
CommonsClientAutoConfiguration.class, ServiceRegistryAutoConfiguration.class })
@AutoConfigureAfter(name = {"org.springframework.cloud.autoconfigure.RefreshAutoConfiguration",
@AutoConfigureAfter(name = {
"org.springframework.cloud.autoconfigure.RefreshAutoConfiguration",
"org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration",
"org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration" })
public class EurekaClientAutoConfiguration {
@@ -133,16 +134,29 @@ public class EurekaClientAutoConfiguration {
public EurekaInstanceConfigBean eurekaInstanceConfigBean(InetUtils inetUtils,
ManagementMetadataProvider managementMetadataProvider) {
String hostname = getProperty("eureka.instance.hostname");
boolean preferIpAddress = Boolean.parseBoolean(getProperty("eureka.instance.prefer-ip-address"));
boolean preferIpAddress = Boolean
.parseBoolean(getProperty("eureka.instance.prefer-ip-address"));
String ipAddress = getProperty("eureka.instance.ip-address");
boolean isSecurePortEnabled = Boolean.parseBoolean(getProperty("eureka.instance.secure-port-enabled"));
boolean isSecurePortEnabled = Boolean
.parseBoolean(getProperty("eureka.instance.secure-port-enabled"));
String serverContextPath = env.getProperty("server.context-path", "/");
int serverPort = Integer.valueOf(env.getProperty("server.port", env.getProperty("port", "8080")));
int serverPort = Integer
.valueOf(env.getProperty("server.port", env.getProperty("port", "8080")));
Integer managementPort = env.getProperty("management.server.port", Integer.class);// nullable. should be wrapped into optional
String managementContextPath = env.getProperty("management.server.servlet.context-path");// nullable. should be wrapped into optional
Integer jmxPort = env.getProperty("com.sun.management.jmxremote.port", Integer.class);//nullable
Integer managementPort = env.getProperty("management.server.port", Integer.class); // nullable.
// should
// be
// wrapped
// into
// optional
String managementContextPath = env
.getProperty("management.server.servlet.context-path"); // nullable.
// should
// be wrapped into
// optional
Integer jmxPort = env.getProperty("com.sun.management.jmxremote.port",
Integer.class); // nullable
EurekaInstanceConfigBean instance = new EurekaInstanceConfigBean(inetUtils);
instance.setNonSecurePort(serverPort);
@@ -180,16 +194,18 @@ public class EurekaClientAutoConfiguration {
instance.setSecureHealthCheckUrl(metadata.getSecureHealthCheckUrl());
}
Map<String, String> metadataMap = instance.getMetadataMap();
if (metadataMap.get("management.port") == null) {
metadataMap.put("management.port", String.valueOf(metadata.getManagementPort()));
metadataMap.computeIfAbsent("management.port",
k -> String.valueOf(metadata.getManagementPort()));
}
} else {
else {
// without the metadata the status and health check URLs will not be set
// and the status page and health check url paths will not include the
// context path so set them here
if (StringUtils.hasText(managementContextPath)) {
instance.setHealthCheckUrlPath(managementContextPath + instance.getHealthCheckUrlPath());
instance.setStatusPageUrlPath(managementContextPath + instance.getStatusPageUrlPath());
instance.setHealthCheckUrlPath(
managementContextPath + instance.getHealthCheckUrlPath());
instance.setStatusPageUrlPath(
managementContextPath + instance.getStatusPageUrlPath());
}
}
@@ -205,7 +221,8 @@ public class EurekaClientAutoConfiguration {
}
@Bean
public DiscoveryClient discoveryClient(EurekaClient client, EurekaClientConfig clientConfig) {
public DiscoveryClient discoveryClient(EurekaClient client,
EurekaClientConfig clientConfig) {
return new EurekaDiscoveryClient(client, clientConfig);
}
@@ -216,8 +233,11 @@ public class EurekaClientAutoConfiguration {
// @Bean
// @ConditionalOnBean(AutoServiceRegistrationProperties.class)
// @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
// public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient, CloudEurekaInstanceConfig instanceConfig, ApplicationInfoManager applicationInfoManager, ObjectProvider<HealthCheckHandler> healthCheckHandler) {
// @ConditionalOnProperty(value =
// "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
// public EurekaRegistration eurekaRegistration(EurekaClient eurekaClient,
// CloudEurekaInstanceConfig instanceConfig, ApplicationInfoManager
// applicationInfoManager, ObjectProvider<HealthCheckHandler> healthCheckHandler) {
// return EurekaRegistration.builder(instanceConfig)
// .with(applicationInfoManager)
// .with(eurekaClient)
@@ -228,7 +248,8 @@ public class EurekaClientAutoConfiguration {
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true)
public EurekaAutoServiceRegistration eurekaAutoServiceRegistration(ApplicationContext context, EurekaServiceRegistry registry,
public EurekaAutoServiceRegistration eurekaAutoServiceRegistration(
ApplicationContext context, EurekaServiceRegistry registry,
EurekaRegistration registration) {
return new EurekaAutoServiceRegistration(context, registry, registration);
}
@@ -245,7 +266,8 @@ public class EurekaClientAutoConfiguration {
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT)
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config) {
public EurekaClient eurekaClient(ApplicationInfoManager manager,
EurekaClientConfig config) {
return new CloudEurekaClient(manager, config, this.optionalArgs,
this.context);
}
@@ -265,12 +287,10 @@ public class EurekaClientAutoConfiguration {
CloudEurekaInstanceConfig instanceConfig,
ApplicationInfoManager applicationInfoManager,
@Autowired(required = false) ObjectProvider<HealthCheckHandler> healthCheckHandler) {
return EurekaRegistration.builder(instanceConfig)
.with(applicationInfoManager)
.with(eurekaClient)
.with(healthCheckHandler)
.build();
return EurekaRegistration.builder(instanceConfig).with(applicationInfoManager)
.with(eurekaClient).with(healthCheckHandler).build();
}
}
@Configuration
@@ -287,20 +307,25 @@ public class EurekaClientAutoConfiguration {
@ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT)
@org.springframework.cloud.context.config.annotation.RefreshScope
@Lazy
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config, EurekaInstanceConfig instance,
public EurekaClient eurekaClient(ApplicationInfoManager manager,
EurekaClientConfig config, EurekaInstanceConfig instance,
@Autowired(required = false) HealthCheckHandler healthCheckHandler) {
//If we use the proxy of the ApplicationInfoManager we could run into a problem
//when shutdown is called on the CloudEurekaClient where the ApplicationInfoManager bean is
//requested but wont be allowed because we are shutting down. To avoid this we use the
// If we use the proxy of the ApplicationInfoManager we could run into a
// problem
// when shutdown is called on the CloudEurekaClient where the
// ApplicationInfoManager bean is
// requested but wont be allowed because we are shutting down. To avoid this
// we use the
// object directly.
ApplicationInfoManager appManager;
if (AopUtils.isAopProxy(manager)) {
appManager = ProxyUtils.getTargetObject(manager);
} else {
}
else {
appManager = manager;
}
CloudEurekaClient cloudEurekaClient = new CloudEurekaClient(appManager, config, this.optionalArgs,
this.context);
CloudEurekaClient cloudEurekaClient = new CloudEurekaClient(appManager,
config, this.optionalArgs, this.context);
cloudEurekaClient.registerHealthCheck(healthCheckHandler);
return cloudEurekaClient;
}
@@ -309,7 +334,8 @@ public class EurekaClientAutoConfiguration {
@ConditionalOnMissingBean(value = ApplicationInfoManager.class, search = SearchStrategy.CURRENT)
@org.springframework.cloud.context.config.annotation.RefreshScope
@Lazy
public ApplicationInfoManager eurekaApplicationInfoManager(EurekaInstanceConfig config) {
public ApplicationInfoManager eurekaApplicationInfoManager(
EurekaInstanceConfig config) {
InstanceInfo instanceInfo = new InstanceInfoFactory().create(config);
return new ApplicationInfoManager(config, instanceInfo);
}
@@ -322,11 +348,8 @@ public class EurekaClientAutoConfiguration {
CloudEurekaInstanceConfig instanceConfig,
ApplicationInfoManager applicationInfoManager,
@Autowired(required = false) ObjectProvider<HealthCheckHandler> healthCheckHandler) {
return EurekaRegistration.builder(instanceConfig)
.with(applicationInfoManager)
.with(eurekaClient)
.with(healthCheckHandler)
.build();
return EurekaRegistration.builder(instanceConfig).with(applicationInfoManager)
.with(eurekaClient).with(healthCheckHandler).build();
}
}
@@ -350,16 +373,18 @@ public class EurekaClientAutoConfiguration {
private static class OnMissingRefreshScopeCondition extends AnyNestedCondition {
public OnMissingRefreshScopeCondition() {
OnMissingRefreshScopeCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnMissingClass("org.springframework.cloud.context.scope.refresh.RefreshScope")
static class MissingClass {
}
@ConditionalOnMissingBean(RefreshAutoConfiguration.class)
static class MissingScope {
}
}
@@ -367,6 +392,7 @@ public class EurekaClientAutoConfiguration {
@Configuration
@ConditionalOnClass(Health.class)
protected static class EurekaHealthIndicatorConfiguration {
@Bean
@ConditionalOnMissingBean
@ConditionalOnEnabledHealthIndicator("eureka")
@@ -374,5 +400,7 @@ public class EurekaClientAutoConfiguration {
EurekaInstanceConfig instanceConfig, EurekaClientConfig clientConfig) {
return new EurekaHealthIndicator(eurekaClient, instanceConfig, clientConfig);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,17 +36,28 @@ import org.springframework.util.StringUtils;
import static org.springframework.cloud.netflix.eureka.EurekaConstants.DEFAULT_PREFIX;
/**
* Eureka client configuration bean.
*
* @author Dave Syer
* @author Gregor Zurowski
*/
@ConfigurationProperties(EurekaClientConfigBean.PREFIX)
public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
/**
* Default prefix for Eureka client config properties.
*/
public static final String PREFIX = "eureka.client";
/**
* Default Eureka URL.
*/
public static final String DEFAULT_URL = "http://localhost:8761" + DEFAULT_PREFIX
+ "/";
/**
* Default availability zone if none is resolved based on region.
*/
public static final String DEFAULT_ZONE = "defaultZone";
private static final int MINUTES = 60;
@@ -76,7 +87,7 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
/**
* Indicates how long initially (in seconds) to replicate instance info to the eureka
* server
* server.
*/
private int initialInstanceInfoReplicationIntervalSeconds = 40;
@@ -191,7 +202,7 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
*
* In the AWS environment, it is recommended that the values is 30 seconds or less,
* since the firewall cleans up the connection information after a few mins leaving
* the connection hanging in limbo
* the connection hanging in limbo.
*/
private int eurekaConnectionIdleTimeoutSeconds = 30;
@@ -202,7 +213,7 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
private String registryRefreshSingleVipAddress;
/**
* The thread pool size for the heartbeatExecutor to initialise with
* The thread pool size for the heartbeatExecutor to initialise with.
*/
private int heartbeatExecutorThreadPoolSize = 2;
@@ -213,7 +224,7 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
private int heartbeatExecutorExponentialBackOffBound = 10;
/**
* The thread pool size for the cacheRefreshExecutor to initialise with
* The thread pool size for the cacheRefreshExecutor to initialise with.
*/
private int cacheRefreshExecutorThreadPoolSize = 2;
@@ -349,8 +360,8 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
private String dollarReplacement = "_-";
/**
* Get a replacement string for underscore sign <code>_</code> during
* serializing/deserializing information in eureka server.
* Get a replacement string for underscore sign <code>_</code> during serializing/
* deserializing information in eureka server.
*/
private String escapeCharReplacement = "__";
@@ -363,40 +374,42 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
/**
* If set to true, local status updates via ApplicationInfoManager will trigger
* on-demand (but rate limited) register/updates to remote eureka servers
* on-demand (but rate limited) register/updates to remote eureka servers.
*/
private boolean onDemandUpdateStatusChange = true;
/**
* This is a transient config and once the latest codecs are stable, can be removed
* (as there will only be one)
* (as there will only be one).
*/
private String encoderName;
/**
* This is a transient config and once the latest codecs are stable, can be removed
* (as there will only be one)
* (as there will only be one).
*/
private String decoderName;
/**
* EurekaAccept name for client data accept
* EurekaAccept name for client data accept.
*/
private String clientDataAccept = EurekaAccept.full.name();
/**
* Indicates whether the client should explicitly unregister itself from the remote server
* on client shutdown.
* Indicates whether the client should explicitly unregister itself from the remote
* server on client shutdown.
*/
private boolean shouldUnregisterOnShutdown = true;
/**
* Indicates whether the client should enforce registration during initialization. Defaults to false.
* Indicates whether the client should enforce registration during initialization.
* Defaults to false.
*/
private boolean shouldEnforceRegistrationAtInit = false;
/**
* Order of the discovery client used by `CompositeDiscoveryClient` for sorting available clients.
* Order of the discovery client used by `CompositeDiscoveryClient` for sorting
* available clients.
*/
private int order = 0;
@@ -461,7 +474,8 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
serviceUrls = this.serviceUrl.get(DEFAULT_ZONE);
}
if (!StringUtils.isEmpty(serviceUrls)) {
final String[] serviceUrlsSplit = StringUtils.commaDelimitedListToStringArray(serviceUrls);
final String[] serviceUrlsSplit = StringUtils
.commaDelimitedListToStringArray(serviceUrls);
List<String> eurekaServiceUrls = new ArrayList<>(serviceUrlsSplit.length);
for (String eurekaServiceUrl : serviceUrlsSplit) {
if (!endsWithSlash(eurekaServiceUrl)) {
@@ -915,7 +929,8 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
return shouldEnforceRegistrationAtInit;
}
public void setShouldEnforceRegistrationAtInit(boolean shouldEnforceRegistrationAtInit) {
public void setShouldEnforceRegistrationAtInit(
boolean shouldEnforceRegistrationAtInit) {
this.shouldEnforceRegistrationAtInit = shouldEnforceRegistrationAtInit;
}
@@ -930,56 +945,60 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EurekaClientConfigBean that = (EurekaClientConfigBean) o;
return Objects.equals(propertyResolver, that.propertyResolver) &&
enabled == that.enabled &&
Objects.equals(transport, that.transport) &&
registryFetchIntervalSeconds == that.registryFetchIntervalSeconds &&
instanceInfoReplicationIntervalSeconds == that.instanceInfoReplicationIntervalSeconds &&
initialInstanceInfoReplicationIntervalSeconds == that.initialInstanceInfoReplicationIntervalSeconds &&
eurekaServiceUrlPollIntervalSeconds == that.eurekaServiceUrlPollIntervalSeconds &&
eurekaServerReadTimeoutSeconds == that.eurekaServerReadTimeoutSeconds &&
eurekaServerConnectTimeoutSeconds == that.eurekaServerConnectTimeoutSeconds &&
eurekaServerTotalConnections == that.eurekaServerTotalConnections &&
eurekaServerTotalConnectionsPerHost == that.eurekaServerTotalConnectionsPerHost &&
eurekaConnectionIdleTimeoutSeconds == that.eurekaConnectionIdleTimeoutSeconds &&
heartbeatExecutorThreadPoolSize == that.heartbeatExecutorThreadPoolSize &&
heartbeatExecutorExponentialBackOffBound == that.heartbeatExecutorExponentialBackOffBound &&
cacheRefreshExecutorThreadPoolSize == that.cacheRefreshExecutorThreadPoolSize &&
cacheRefreshExecutorExponentialBackOffBound == that.cacheRefreshExecutorExponentialBackOffBound &&
gZipContent == that.gZipContent &&
useDnsForFetchingServiceUrls == that.useDnsForFetchingServiceUrls &&
registerWithEureka == that.registerWithEureka &&
preferSameZoneEureka == that.preferSameZoneEureka &&
logDeltaDiff == that.logDeltaDiff &&
disableDelta == that.disableDelta &&
filterOnlyUpInstances == that.filterOnlyUpInstances &&
fetchRegistry == that.fetchRegistry &&
allowRedirects == that.allowRedirects &&
onDemandUpdateStatusChange == that.onDemandUpdateStatusChange &&
shouldUnregisterOnShutdown == that.shouldUnregisterOnShutdown &&
shouldEnforceRegistrationAtInit == that.shouldEnforceRegistrationAtInit &&
Objects.equals(proxyPort, that.proxyPort) &&
Objects.equals(proxyHost, that.proxyHost) &&
Objects.equals(proxyUserName, that.proxyUserName) &&
Objects.equals(proxyPassword, that.proxyPassword) &&
Objects.equals(backupRegistryImpl, that.backupRegistryImpl) &&
Objects.equals(eurekaServerURLContext, that.eurekaServerURLContext) &&
Objects.equals(eurekaServerPort, that.eurekaServerPort) &&
Objects.equals(eurekaServerDNSName, that.eurekaServerDNSName) &&
Objects.equals(region, that.region) &&
Objects.equals(registryRefreshSingleVipAddress, that.registryRefreshSingleVipAddress) &&
Objects.equals(serviceUrl, that.serviceUrl) &&
Objects.equals(fetchRemoteRegionsRegistry, that.fetchRemoteRegionsRegistry) &&
Objects.equals(availabilityZones, that.availabilityZones) &&
Objects.equals(dollarReplacement, that.dollarReplacement) &&
Objects.equals(escapeCharReplacement, that.escapeCharReplacement) &&
Objects.equals(encoderName, that.encoderName) &&
Objects.equals(decoderName, that.decoderName) &&
Objects.equals(clientDataAccept, that.clientDataAccept) &&
Objects.equals(order, that.order);
return Objects.equals(propertyResolver, that.propertyResolver)
&& enabled == that.enabled && Objects.equals(transport, that.transport)
&& registryFetchIntervalSeconds == that.registryFetchIntervalSeconds
&& instanceInfoReplicationIntervalSeconds == that.instanceInfoReplicationIntervalSeconds
&& initialInstanceInfoReplicationIntervalSeconds == that.initialInstanceInfoReplicationIntervalSeconds
&& eurekaServiceUrlPollIntervalSeconds == that.eurekaServiceUrlPollIntervalSeconds
&& eurekaServerReadTimeoutSeconds == that.eurekaServerReadTimeoutSeconds
&& eurekaServerConnectTimeoutSeconds == that.eurekaServerConnectTimeoutSeconds
&& eurekaServerTotalConnections == that.eurekaServerTotalConnections
&& eurekaServerTotalConnectionsPerHost == that.eurekaServerTotalConnectionsPerHost
&& eurekaConnectionIdleTimeoutSeconds == that.eurekaConnectionIdleTimeoutSeconds
&& heartbeatExecutorThreadPoolSize == that.heartbeatExecutorThreadPoolSize
&& heartbeatExecutorExponentialBackOffBound == that.heartbeatExecutorExponentialBackOffBound
&& cacheRefreshExecutorThreadPoolSize == that.cacheRefreshExecutorThreadPoolSize
&& cacheRefreshExecutorExponentialBackOffBound == that.cacheRefreshExecutorExponentialBackOffBound
&& gZipContent == that.gZipContent
&& useDnsForFetchingServiceUrls == that.useDnsForFetchingServiceUrls
&& registerWithEureka == that.registerWithEureka
&& preferSameZoneEureka == that.preferSameZoneEureka
&& logDeltaDiff == that.logDeltaDiff && disableDelta == that.disableDelta
&& filterOnlyUpInstances == that.filterOnlyUpInstances
&& fetchRegistry == that.fetchRegistry
&& allowRedirects == that.allowRedirects
&& onDemandUpdateStatusChange == that.onDemandUpdateStatusChange
&& shouldUnregisterOnShutdown == that.shouldUnregisterOnShutdown
&& shouldEnforceRegistrationAtInit == that.shouldEnforceRegistrationAtInit
&& Objects.equals(proxyPort, that.proxyPort)
&& Objects.equals(proxyHost, that.proxyHost)
&& Objects.equals(proxyUserName, that.proxyUserName)
&& Objects.equals(proxyPassword, that.proxyPassword)
&& Objects.equals(backupRegistryImpl, that.backupRegistryImpl)
&& Objects.equals(eurekaServerURLContext, that.eurekaServerURLContext)
&& Objects.equals(eurekaServerPort, that.eurekaServerPort)
&& Objects.equals(eurekaServerDNSName, that.eurekaServerDNSName)
&& Objects.equals(region, that.region)
&& Objects.equals(registryRefreshSingleVipAddress,
that.registryRefreshSingleVipAddress)
&& Objects.equals(serviceUrl, that.serviceUrl)
&& Objects.equals(fetchRemoteRegionsRegistry,
that.fetchRemoteRegionsRegistry)
&& Objects.equals(availabilityZones, that.availabilityZones)
&& Objects.equals(dollarReplacement, that.dollarReplacement)
&& Objects.equals(escapeCharReplacement, that.escapeCharReplacement)
&& Objects.equals(encoderName, that.encoderName)
&& Objects.equals(decoderName, that.decoderName)
&& Objects.equals(clientDataAccept, that.clientDataAccept)
&& Objects.equals(order, that.order);
}
@Override
@@ -1006,54 +1025,70 @@ public class EurekaClientConfigBean implements EurekaClientConfig, Ordered {
@Override
public String toString() {
return new StringBuilder("EurekaClientConfigBean{")
.append("propertyResolver=").append(propertyResolver).append(", ")
.append("enabled=").append(enabled).append(", ")
.append("transport=").append(transport).append(", ")
.append("registryFetchIntervalSeconds=").append(registryFetchIntervalSeconds).append(", ")
.append("instanceInfoReplicationIntervalSeconds=").append(instanceInfoReplicationIntervalSeconds).append(", ")
.append("initialInstanceInfoReplicationIntervalSeconds=").append(initialInstanceInfoReplicationIntervalSeconds).append(", ")
.append("eurekaServiceUrlPollIntervalSeconds=").append(eurekaServiceUrlPollIntervalSeconds).append(", ")
return new StringBuilder("EurekaClientConfigBean{").append("propertyResolver=")
.append(propertyResolver).append(", ").append("enabled=").append(enabled)
.append(", ").append("transport=").append(transport).append(", ")
.append("registryFetchIntervalSeconds=")
.append(registryFetchIntervalSeconds).append(", ")
.append("instanceInfoReplicationIntervalSeconds=")
.append(instanceInfoReplicationIntervalSeconds).append(", ")
.append("initialInstanceInfoReplicationIntervalSeconds=")
.append(initialInstanceInfoReplicationIntervalSeconds).append(", ")
.append("eurekaServiceUrlPollIntervalSeconds=")
.append(eurekaServiceUrlPollIntervalSeconds).append(", ")
.append("proxyPort='").append(proxyPort).append("', ")
.append("proxyHost='").append(proxyHost).append("', ")
.append("proxyUserName='").append(proxyUserName).append("', ")
.append("proxyPassword='").append(proxyPassword).append("', ")
.append("eurekaServerReadTimeoutSeconds=").append(eurekaServerReadTimeoutSeconds).append(", ")
.append("eurekaServerConnectTimeoutSeconds=").append(eurekaServerConnectTimeoutSeconds).append(", ")
.append("eurekaServerReadTimeoutSeconds=")
.append(eurekaServerReadTimeoutSeconds).append(", ")
.append("eurekaServerConnectTimeoutSeconds=")
.append(eurekaServerConnectTimeoutSeconds).append(", ")
.append("backupRegistryImpl='").append(backupRegistryImpl).append("', ")
.append("eurekaServerTotalConnections=").append(eurekaServerTotalConnections).append(", ")
.append("eurekaServerTotalConnectionsPerHost=").append(eurekaServerTotalConnectionsPerHost).append(", ")
.append("eurekaServerURLContext='").append(eurekaServerURLContext).append("', ")
.append("eurekaServerPort='").append(eurekaServerPort).append("', ")
.append("eurekaServerDNSName='").append(eurekaServerDNSName).append("', ")
.append("region='").append(region).append("', ")
.append("eurekaConnectionIdleTimeoutSeconds=").append(eurekaConnectionIdleTimeoutSeconds).append(", ")
.append("registryRefreshSingleVipAddress='").append(registryRefreshSingleVipAddress).append("', ")
.append("heartbeatExecutorThreadPoolSize=").append(heartbeatExecutorThreadPoolSize).append(", ")
.append("heartbeatExecutorExponentialBackOffBound=").append(heartbeatExecutorExponentialBackOffBound).append(", ")
.append("cacheRefreshExecutorThreadPoolSize=").append(cacheRefreshExecutorThreadPoolSize).append(", ")
.append("cacheRefreshExecutorExponentialBackOffBound=").append(cacheRefreshExecutorExponentialBackOffBound).append(", ")
.append("eurekaServerTotalConnections=")
.append(eurekaServerTotalConnections).append(", ")
.append("eurekaServerTotalConnectionsPerHost=")
.append(eurekaServerTotalConnectionsPerHost).append(", ")
.append("eurekaServerURLContext='").append(eurekaServerURLContext)
.append("', ").append("eurekaServerPort='").append(eurekaServerPort)
.append("', ").append("eurekaServerDNSName='").append(eurekaServerDNSName)
.append("', ").append("region='").append(region).append("', ")
.append("eurekaConnectionIdleTimeoutSeconds=")
.append(eurekaConnectionIdleTimeoutSeconds).append(", ")
.append("registryRefreshSingleVipAddress='")
.append(registryRefreshSingleVipAddress).append("', ")
.append("heartbeatExecutorThreadPoolSize=")
.append(heartbeatExecutorThreadPoolSize).append(", ")
.append("heartbeatExecutorExponentialBackOffBound=")
.append(heartbeatExecutorExponentialBackOffBound).append(", ")
.append("cacheRefreshExecutorThreadPoolSize=")
.append(cacheRefreshExecutorThreadPoolSize).append(", ")
.append("cacheRefreshExecutorExponentialBackOffBound=")
.append(cacheRefreshExecutorExponentialBackOffBound).append(", ")
.append("serviceUrl=").append(serviceUrl).append(", ")
.append("gZipContent=").append(gZipContent).append(", ")
.append("useDnsForFetchingServiceUrls=").append(useDnsForFetchingServiceUrls).append(", ")
.append("useDnsForFetchingServiceUrls=")
.append(useDnsForFetchingServiceUrls).append(", ")
.append("registerWithEureka=").append(registerWithEureka).append(", ")
.append("preferSameZoneEureka=").append(preferSameZoneEureka).append(", ")
.append("logDeltaDiff=").append(logDeltaDiff).append(", ")
.append("disableDelta=").append(disableDelta).append(", ")
.append("fetchRemoteRegionsRegistry='").append(fetchRemoteRegionsRegistry).append("', ")
.append("availabilityZones=").append(availabilityZones).append(", ")
.append("filterOnlyUpInstances=").append(filterOnlyUpInstances).append(", ")
.append("fetchRegistry=").append(fetchRegistry).append(", ")
.append("dollarReplacement='").append(dollarReplacement).append("', ")
.append("escapeCharReplacement='").append(escapeCharReplacement).append("', ")
.append("allowRedirects=").append(allowRedirects).append(", ")
.append("onDemandUpdateStatusChange=").append(onDemandUpdateStatusChange).append(", ")
.append("encoderName='").append(encoderName).append("', ")
.append("decoderName='").append(decoderName).append("', ")
.append("clientDataAccept='").append(clientDataAccept).append("', ")
.append("shouldUnregisterOnShutdown='").append(shouldUnregisterOnShutdown).append("', ")
.append("shouldEnforceRegistrationAtInit='").append(shouldEnforceRegistrationAtInit).append("', ")
.append("order='").append(order).append("'}")
.toString();
.append("fetchRemoteRegionsRegistry='").append(fetchRemoteRegionsRegistry)
.append("', ").append("availabilityZones=").append(availabilityZones)
.append(", ").append("filterOnlyUpInstances=")
.append(filterOnlyUpInstances).append(", ").append("fetchRegistry=")
.append(fetchRegistry).append(", ").append("dollarReplacement='")
.append(dollarReplacement).append("', ").append("escapeCharReplacement='")
.append(escapeCharReplacement).append("', ").append("allowRedirects=")
.append(allowRedirects).append(", ").append("onDemandUpdateStatusChange=")
.append(onDemandUpdateStatusChange).append(", ").append("encoderName='")
.append(encoderName).append("', ").append("decoderName='")
.append(decoderName).append("', ").append("clientDataAccept='")
.append(clientDataAccept).append("', ")
.append("shouldUnregisterOnShutdown='").append(shouldUnregisterOnShutdown)
.append("', ").append("shouldEnforceRegistrationAtInit='")
.append(shouldEnforceRegistrationAtInit).append("', ").append("order='")
.append(order).append("'}").toString();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,10 +17,15 @@
package org.springframework.cloud.netflix.eureka;
/**
* Class containing Eureka-specific constants.
*
* @author Spencer Gibb
*/
public class EurekaConstants {
public final class EurekaConstants {
/**
* Default Eureka prefix.
*/
public static final String DEFAULT_PREFIX = "/eureka";
private EurekaConstants() {
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -38,14 +38,20 @@ import org.springframework.util.Assert;
import static com.netflix.appinfo.InstanceInfo.PortType.SECURE;
/**
* A {@link DiscoveryClient} implementation for Eureka.
*
* @author Spencer Gibb
* @author Tim Ysewyn
*/
public class EurekaDiscoveryClient implements DiscoveryClient {
/**
* Client description {@link String}.
*/
public static final String DESCRIPTION = "Spring Cloud Eureka Discovery Client";
private final EurekaClient eurekaClient;
private final EurekaClientConfig clientConfig;
@Deprecated
@@ -53,7 +59,8 @@ public class EurekaDiscoveryClient implements DiscoveryClient {
this(eurekaClient, eurekaClient.getEurekaClientConfig());
}
public EurekaDiscoveryClient(EurekaClient eurekaClient, EurekaClientConfig clientConfig) {
public EurekaDiscoveryClient(EurekaClient eurekaClient,
EurekaClientConfig clientConfig) {
this.clientConfig = clientConfig;
this.eurekaClient = eurekaClient;
}
@@ -74,7 +81,35 @@ public class EurekaDiscoveryClient implements DiscoveryClient {
return instances;
}
@Override
public List<String> getServices() {
Applications applications = this.eurekaClient.getApplications();
if (applications == null) {
return Collections.emptyList();
}
List<Application> registered = applications.getRegisteredApplications();
List<String> names = new ArrayList<>();
for (Application app : registered) {
if (app.getInstances().isEmpty()) {
continue;
}
names.add(app.getName().toLowerCase());
}
return names;
}
@Override
public int getOrder() {
return clientConfig instanceof Ordered ? ((Ordered) clientConfig).getOrder()
: DiscoveryClient.DEFAULT_ORDER;
}
/**
* An Eureka-specific {@link ServiceInstance} implementation.
*/
public static class EurekaServiceInstance implements ServiceInstance {
private InstanceInfo instance;
public EurekaServiceInstance(InstanceInfo instance) {
@@ -124,28 +159,7 @@ public class EurekaDiscoveryClient implements DiscoveryClient {
public Map<String, String> getMetadata() {
return this.instance.getMetadata();
}
}
@Override
public List<String> getServices() {
Applications applications = this.eurekaClient.getApplications();
if (applications == null) {
return Collections.emptyList();
}
List<Application> registered = applications.getRegisteredApplications();
List<String> names = new ArrayList<>();
for (Application app : registered) {
if (app.getInstances().isEmpty()) {
continue;
}
names.add(app.getName().toLowerCase());
}
return names;
}
@Override
public int getOrder() {
return clientConfig instanceof Ordered ? ((Ordered) clientConfig).getOrder() : DiscoveryClient.DEFAULT_ORDER;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.eureka;
@@ -46,16 +45,34 @@ import org.springframework.context.annotation.Configuration;
@ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true)
public class EurekaDiscoveryClientConfiguration {
class Marker {}
@Bean
public Marker eurekaDiscoverClientMarker() {
return new Marker();
}
@Configuration
@ConditionalOnProperty(value = "eureka.client.healthcheck.enabled", matchIfMissing = false)
protected static class EurekaHealthCheckHandlerConfiguration {
@Autowired(required = false)
private HealthAggregator healthAggregator = new OrderedHealthAggregator();
@Bean
@ConditionalOnMissingBean(HealthCheckHandler.class)
public EurekaHealthCheckHandler eurekaHealthCheckHandler() {
return new EurekaHealthCheckHandler(this.healthAggregator);
}
}
class Marker {
}
@Configuration
@ConditionalOnClass(RefreshScopeRefreshedEvent.class)
protected static class EurekaClientConfigurationRefresher implements ApplicationListener<RefreshScopeRefreshedEvent> {
protected static class EurekaClientConfigurationRefresher
implements ApplicationListener<RefreshScopeRefreshedEvent> {
@Autowired(required = false)
private EurekaClient eurekaClient;
@@ -75,20 +92,7 @@ public class EurekaDiscoveryClientConfiguration {
this.autoRegistration.start();
}
}
}
@Configuration
@ConditionalOnProperty(value = "eureka.client.healthcheck.enabled", matchIfMissing = false)
protected static class EurekaHealthCheckHandlerConfiguration {
@Autowired(required = false)
private HealthAggregator healthAggregator = new OrderedHealthAggregator();
@Bean
@ConditionalOnMissingBean(HealthCheckHandler.class)
public EurekaHealthCheckHandler eurekaHealthCheckHandler() {
return new EurekaHealthCheckHandler(this.healthAggregator);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -36,26 +36,28 @@ import org.springframework.util.Assert;
import static com.netflix.appinfo.InstanceInfo.InstanceStatus;
/**
* A Eureka health checker, maps the application status into {@link InstanceStatus}
* that will be propagated to Eureka registry.
* A Eureka health checker, maps the application status into {@link InstanceStatus} that
* will be propagated to Eureka registry.
*
* On each heartbeat Eureka performs the health check invoking registered {@link HealthCheckHandler}. By default this
* implementation will perform aggregation of all registered {@link HealthIndicator}
* through registered {@link HealthAggregator}.
* On each heartbeat Eureka performs the health check invoking registered
* {@link HealthCheckHandler}. By default this implementation will perform aggregation of
* all registered {@link HealthIndicator} through registered {@link HealthAggregator}.
*
* @author Jakub Narloch
* @see HealthCheckHandler
* @see HealthAggregator
*/
public class EurekaHealthCheckHandler implements HealthCheckHandler, ApplicationContextAware, InitializingBean {
public class EurekaHealthCheckHandler
implements HealthCheckHandler, ApplicationContextAware, InitializingBean {
private static final Map<Status, InstanceInfo.InstanceStatus> STATUS_MAPPING =
new HashMap<Status, InstanceInfo.InstanceStatus>() {{
private static final Map<Status, InstanceInfo.InstanceStatus> STATUS_MAPPING = new HashMap<Status, InstanceInfo.InstanceStatus>() {
{
put(Status.UNKNOWN, InstanceStatus.UNKNOWN);
put(Status.OUT_OF_SERVICE, InstanceStatus.OUT_OF_SERVICE);
put(Status.DOWN, InstanceStatus.DOWN);
put(Status.UP, InstanceStatus.UP);
}};
}
};
private final CompositeHealthIndicator healthIndicator;
@@ -67,23 +69,28 @@ public class EurekaHealthCheckHandler implements HealthCheckHandler, Application
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() throws Exception {
final Map<String, HealthIndicator> healthIndicators = applicationContext.getBeansOfType(HealthIndicator.class);
final Map<String, HealthIndicator> healthIndicators = applicationContext
.getBeansOfType(HealthIndicator.class);
for (Map.Entry<String, HealthIndicator> entry : healthIndicators.entrySet()) {
// ignore EurekaHealthIndicator and flatten the rest of the composite
// otherwise there is a never ending cycle of down. See gh-643
if (entry.getValue() instanceof DiscoveryCompositeHealthIndicator) {
DiscoveryCompositeHealthIndicator indicator = (DiscoveryCompositeHealthIndicator) entry.getValue();
for (DiscoveryCompositeHealthIndicator.Holder holder : indicator.getHealthIndicators()) {
DiscoveryCompositeHealthIndicator indicator = (DiscoveryCompositeHealthIndicator) entry
.getValue();
for (DiscoveryCompositeHealthIndicator.Holder holder : indicator
.getHealthIndicators()) {
if (!(holder.getDelegate() instanceof EurekaHealthIndicator)) {
healthIndicator.addHealthIndicator(holder.getDelegate().getName(), holder);
healthIndicator.addHealthIndicator(holder.getDelegate().getName(),
holder);
}
}
@@ -114,4 +121,5 @@ public class EurekaHealthCheckHandler implements HealthCheckHandler, Application
protected CompositeHealthIndicator getHealthIndicator() {
return healthIndicator;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,13 +20,6 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Health.Builder;
import org.springframework.boot.actuate.health.Status;
import org.springframework.cloud.client.discovery.health.DiscoveryHealthIndicator;
import org.springframework.cloud.util.ProxyUtils;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.discovery.DiscoveryClient;
import com.netflix.discovery.EurekaClient;
@@ -34,6 +27,13 @@ import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import org.springframework.aop.support.AopUtils;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.Health.Builder;
import org.springframework.boot.actuate.health.Status;
import org.springframework.cloud.client.discovery.health.DiscoveryHealthIndicator;
import org.springframework.cloud.util.ProxyUtils;
/**
* @author Dave Syer
*/
@@ -67,8 +67,7 @@ public class EurekaHealthIndicator implements DiscoveryHealthIndicator {
}
private Status getStatus(Builder builder) {
Status status = new Status(
this.eurekaClient.getInstanceRemoteStatus().toString(),
Status status = new Status(this.eurekaClient.getInstanceRemoteStatus().toString(),
"Remote status from Eureka server");
DiscoveryClient discoveryClient = getDiscoveryClient();
if (discoveryClient != null && clientConfig.shouldFetchRegistry()) {
@@ -95,7 +94,8 @@ public class EurekaHealthIndicator implements DiscoveryHealthIndicator {
DiscoveryClient discoveryClient = null;
if (AopUtils.isAopProxy(eurekaClient)) {
discoveryClient = ProxyUtils.getTargetObject(eurekaClient);
} else if(DiscoveryClient.class.isInstance(eurekaClient)) {
}
else if (DiscoveryClient.class.isInstance(eurekaClient)) {
discoveryClient = (DiscoveryClient) eurekaClient;
}
return discoveryClient;
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,10 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.appinfo.MyDataCenterInfo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtils.HostInfo;
@@ -28,10 +32,6 @@ import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import com.netflix.appinfo.DataCenterInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.appinfo.MyDataCenterInfo;
/**
* @author Dave Syer
* @author Spencer Gibb
@@ -39,7 +39,8 @@ import com.netflix.appinfo.MyDataCenterInfo;
* @author Gregor Zurowski
*/
@ConfigurationProperties("eureka.instance")
public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, EnvironmentAware {
public class EurekaInstanceConfigBean
implements CloudEurekaInstanceConfig, EnvironmentAware {
private static final String UNKNOWN = "unknown";
@@ -48,7 +49,7 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi
private InetUtils inetUtils;
/**
* Default prefix for actuator endpoints
* Default prefix for actuator endpoints.
*/
private String actuatorPrefix = "/actuator";
@@ -275,6 +276,7 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi
private InstanceStatus initialStatus = InstanceStatus.UP;
private String[] defaultAddressResolutionOrder = new String[0];
private Environment environment;
public String getHostname() {
@@ -327,8 +329,10 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi
@Override
public void setEnvironment(Environment environment) {
this.environment = environment;
// set some defaults from the environment, but allow the defaults to use relaxed binding
String springAppName = this.environment.getProperty("spring.application.name", "");
// set some defaults from the environment, but allow the defaults to use relaxed
// binding
String springAppName = this.environment.getProperty("spring.application.name",
"");
if (StringUtils.hasText(springAppName)) {
setAppname(springAppName);
setVirtualHostName(springAppName);
@@ -567,40 +571,44 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EurekaInstanceConfigBean that = (EurekaInstanceConfigBean) o;
return Objects.equals(hostInfo, that.hostInfo) &&
Objects.equals(inetUtils, that.inetUtils) &&
Objects.equals(appname, that.appname) &&
Objects.equals(appGroupName, that.appGroupName) &&
instanceEnabledOnit == that.instanceEnabledOnit &&
nonSecurePort == that.nonSecurePort &&
securePort == that.securePort &&
nonSecurePortEnabled == that.nonSecurePortEnabled &&
securePortEnabled == that.securePortEnabled &&
leaseRenewalIntervalInSeconds == that.leaseRenewalIntervalInSeconds &&
leaseExpirationDurationInSeconds == that.leaseExpirationDurationInSeconds &&
Objects.equals(virtualHostName, that.virtualHostName) &&
Objects.equals(instanceId, that.instanceId) &&
Objects.equals(secureVirtualHostName, that.secureVirtualHostName) &&
Objects.equals(aSGName, that.aSGName) &&
Objects.equals(metadataMap, that.metadataMap) &&
Objects.equals(dataCenterInfo, that.dataCenterInfo) &&
Objects.equals(ipAddress, that.ipAddress) &&
Objects.equals(statusPageUrlPath, that.statusPageUrlPath) &&
Objects.equals(statusPageUrl, that.statusPageUrl) &&
Objects.equals(homePageUrlPath, that.homePageUrlPath) &&
Objects.equals(homePageUrl, that.homePageUrl) &&
Objects.equals(healthCheckUrlPath, that.healthCheckUrlPath) &&
Objects.equals(healthCheckUrl, that.healthCheckUrl) &&
Objects.equals(secureHealthCheckUrl, that.secureHealthCheckUrl) &&
Objects.equals(namespace, that.namespace) &&
Objects.equals(hostname, that.hostname) &&
preferIpAddress == that.preferIpAddress &&
Objects.equals(initialStatus, that.initialStatus) &&
Arrays.equals(defaultAddressResolutionOrder, that.defaultAddressResolutionOrder) &&
Objects.equals(environment, that.environment);
return Objects.equals(hostInfo, that.hostInfo)
&& Objects.equals(inetUtils, that.inetUtils)
&& Objects.equals(appname, that.appname)
&& Objects.equals(appGroupName, that.appGroupName)
&& instanceEnabledOnit == that.instanceEnabledOnit
&& nonSecurePort == that.nonSecurePort && securePort == that.securePort
&& nonSecurePortEnabled == that.nonSecurePortEnabled
&& securePortEnabled == that.securePortEnabled
&& leaseRenewalIntervalInSeconds == that.leaseRenewalIntervalInSeconds
&& leaseExpirationDurationInSeconds == that.leaseExpirationDurationInSeconds
&& Objects.equals(virtualHostName, that.virtualHostName)
&& Objects.equals(instanceId, that.instanceId)
&& Objects.equals(secureVirtualHostName, that.secureVirtualHostName)
&& Objects.equals(aSGName, that.aSGName)
&& Objects.equals(metadataMap, that.metadataMap)
&& Objects.equals(dataCenterInfo, that.dataCenterInfo)
&& Objects.equals(ipAddress, that.ipAddress)
&& Objects.equals(statusPageUrlPath, that.statusPageUrlPath)
&& Objects.equals(statusPageUrl, that.statusPageUrl)
&& Objects.equals(homePageUrlPath, that.homePageUrlPath)
&& Objects.equals(homePageUrl, that.homePageUrl)
&& Objects.equals(healthCheckUrlPath, that.healthCheckUrlPath)
&& Objects.equals(healthCheckUrl, that.healthCheckUrl)
&& Objects.equals(secureHealthCheckUrl, that.secureHealthCheckUrl)
&& Objects.equals(namespace, that.namespace)
&& Objects.equals(hostname, that.hostname)
&& preferIpAddress == that.preferIpAddress
&& Objects.equals(initialStatus, that.initialStatus)
&& Arrays.equals(defaultAddressResolutionOrder,
that.defaultAddressResolutionOrder)
&& Objects.equals(environment, that.environment);
}
@Override
@@ -612,27 +620,29 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi
secureVirtualHostName, aSGName, metadataMap, dataCenterInfo, ipAddress,
statusPageUrlPath, statusPageUrl, homePageUrlPath, homePageUrl,
healthCheckUrlPath, healthCheckUrl, secureHealthCheckUrl, namespace,
hostname, preferIpAddress, initialStatus, defaultAddressResolutionOrder, environment);
hostname, preferIpAddress, initialStatus, defaultAddressResolutionOrder,
environment);
}
@Override
public String toString() {
return new StringBuilder("EurekaInstanceConfigBean{")
.append("hostInfo=").append(hostInfo).append(", ")
.append("inetUtils=").append(inetUtils).append(", ")
.append("appname='").append(appname).append("', ")
return new StringBuilder("EurekaInstanceConfigBean{").append("hostInfo=")
.append(hostInfo).append(", ").append("inetUtils=").append(inetUtils)
.append(", ").append("appname='").append(appname).append("', ")
.append("appGroupName='").append(appGroupName).append("', ")
.append("instanceEnabledOnit=").append(instanceEnabledOnit).append(", ")
.append("nonSecurePort=").append(nonSecurePort).append(", ")
.append("securePort=").append(securePort).append(", ")
.append("nonSecurePortEnabled=").append(nonSecurePortEnabled).append(", ")
.append("securePortEnabled=").append(securePortEnabled).append(", ")
.append("leaseRenewalIntervalInSeconds=").append(leaseRenewalIntervalInSeconds).append(", ")
.append("leaseExpirationDurationInSeconds=").append(leaseExpirationDurationInSeconds).append(", ")
.append("leaseRenewalIntervalInSeconds=")
.append(leaseRenewalIntervalInSeconds).append(", ")
.append("leaseExpirationDurationInSeconds=")
.append(leaseExpirationDurationInSeconds).append(", ")
.append("virtualHostName='").append(virtualHostName).append("', ")
.append("instanceId='").append(instanceId).append("', ")
.append("secureVirtualHostName='").append(secureVirtualHostName).append("', ")
.append("aSGName='").append(aSGName).append("', ")
.append("secureVirtualHostName='").append(secureVirtualHostName)
.append("', ").append("aSGName='").append(aSGName).append("', ")
.append("metadataMap=").append(metadataMap).append(", ")
.append("dataCenterInfo=").append(dataCenterInfo).append(", ")
.append("ipAddress='").append(ipAddress).append("', ")
@@ -642,13 +652,15 @@ public class EurekaInstanceConfigBean implements CloudEurekaInstanceConfig, Envi
.append("homePageUrl='").append(homePageUrl).append("', ")
.append("healthCheckUrlPath='").append(healthCheckUrlPath).append("', ")
.append("healthCheckUrl='").append(healthCheckUrl).append("', ")
.append("secureHealthCheckUrl='").append(secureHealthCheckUrl).append("', ")
.append("namespace='").append(namespace).append("', ")
.append("secureHealthCheckUrl='").append(secureHealthCheckUrl)
.append("', ").append("namespace='").append(namespace).append("', ")
.append("hostname='").append(hostname).append("', ")
.append("preferIpAddress=").append(preferIpAddress).append(", ")
.append("initialStatus=").append(initialStatus).append(", ")
.append("defaultAddressResolutionOrder=").append(Arrays.toString(defaultAddressResolutionOrder)).append(", ")
.append("defaultAddressResolutionOrder=")
.append(Arrays.toString(defaultAddressResolutionOrder)).append(", ")
.append("environment=").append(environment).append(", ").append("}")
.toString();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,7 +25,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* See com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider
* See com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider.
*
* @author Spencer Gibb
*/
public class InstanceInfoFactory {
@@ -95,4 +96,5 @@ public class InstanceInfoFactory {
instanceInfo.setLeaseInfo(leaseInfoBuilder.build());
return instanceInfo;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,8 @@
package org.springframework.cloud.netflix.eureka.config;
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
@@ -25,13 +27,12 @@ import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClient
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
/**
* @author Daniel Lavoie
*/
@Configuration
public class DiscoveryClientOptionalArgsConfiguration {
@Bean
@ConditionalOnMissingClass("com.sun.jersey.api.client.filter.ClientFilter")
@ConditionalOnMissingBean(value = AbstractDiscoveryClientOptionalArgs.class, search = SearchStrategy.CURRENT)
@@ -45,4 +46,5 @@ public class DiscoveryClientOptionalArgsConfiguration {
public MutableDiscoveryClientOptionalArgs discoveryClientOptionalArgs() {
return new MutableDiscoveryClientOptionalArgs();
}
}
@@ -18,6 +18,9 @@ package org.springframework.cloud.netflix.eureka.config;
import javax.annotation.PostConstruct;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@@ -26,9 +29,6 @@ import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.discovery.EurekaClient;
/**
* Extra configuration for config server if it happens to be a Eureka instance.
*
@@ -52,7 +52,8 @@ public class EurekaClientConfigServerAutoConfiguration {
return;
}
String prefix = this.server.getPrefix();
if (StringUtils.hasText(prefix) && !StringUtils.hasText(this.instance.getMetadataMap().get("configPath"))) {
if (StringUtils.hasText(prefix) && !StringUtils
.hasText(this.instance.getMetadataMap().get("configPath"))) {
this.instance.getMetadataMap().put("configPath", prefix);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,14 +18,14 @@ package org.springframework.cloud.netflix.eureka.config;
import javax.annotation.PostConstruct;
import com.netflix.discovery.EurekaClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClientConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import com.netflix.discovery.EurekaClient;
/**
* Bootstrap configuration for a config client that wants to lookup the config server via
* discovery.
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,7 +33,11 @@ import org.springframework.context.annotation.Import;
@ConditionalOnClass(ConfigServicePropertySourceLocator.class)
@ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", matchIfMissing = false)
@Configuration
@Import({ EurekaDiscoveryClientConfiguration.class, // this emulates @EnableDiscoveryClient, the import selector doesn't run before the bootstrap phase
@Import({ EurekaDiscoveryClientConfiguration.class, // this emulates
// @EnableDiscoveryClient, the import
// selector doesn't run before the
// bootstrap phase
EurekaClientAutoConfiguration.class })
public class EurekaDiscoveryClientConfigServiceBootstrapConfiguration {
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -37,4 +37,5 @@ public class EurekaApplications extends com.netflix.discovery.shared.Application
@JsonProperty("application") List<Application> registeredApplications) {
super(appsHashCode, versionDelta, registeredApplications);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,7 +23,9 @@ import com.netflix.discovery.AbstractDiscoveryClientOptionalArgs;
*/
public class RestTemplateDiscoveryClientOptionalArgs
extends AbstractDiscoveryClientOptionalArgs<Void> {
public RestTemplateDiscoveryClientOptionalArgs() {
setTransportClientFactories(new RestTemplateTransportClientFactories());
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,24 +16,12 @@
package org.springframework.cloud.netflix.eureka.http;
import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.discovery.shared.Application;
@@ -42,6 +30,18 @@ import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.EurekaHttpResponse;
import com.netflix.discovery.shared.transport.EurekaHttpResponse.EurekaHttpResponseBuilder;
import com.netflix.discovery.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import static com.netflix.discovery.shared.transport.EurekaHttpResponse.anEurekaHttpResponse;
/**
* @author Daniel Lavoie
@@ -51,6 +51,7 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
protected final Log logger = LogFactory.getLog(getClass());
private RestTemplate restTemplate;
private String serviceUrl;
public RestTemplateEurekaHttpClient(RestTemplate restTemplate, String serviceUrl) {
@@ -102,8 +103,9 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
response.getStatusCodeValue(), InstanceInfo.class)
.headers(headersOf(response));
if (response.hasBody())
if (response.hasBody()) {
eurekaResponseBuilder.entity(response.getBody());
}
return eurekaResponseBuilder.build();
}
@@ -228,4 +230,5 @@ public class RestTemplateEurekaHttpClient implements EurekaHttpClient {
}
return headers;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,15 +19,15 @@ package org.springframework.cloud.netflix.eureka.http;
import java.util.Collection;
import java.util.Optional;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.transport.TransportClientFactory;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient;
import com.netflix.discovery.shared.transport.jersey.TransportClientFactories;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
/**
* @author Daniel Lavoie
*/
@@ -48,11 +48,12 @@ public class RestTemplateTransportClientFactories
}
@Override
public TransportClientFactory newTransportClientFactory(final EurekaClientConfig clientConfig,
final Collection<Void> additionalFilters,
final InstanceInfo myInstanceInfo,
public TransportClientFactory newTransportClientFactory(
final EurekaClientConfig clientConfig,
final Collection<Void> additionalFilters, final InstanceInfo myInstanceInfo,
final Optional<SSLContext> sslContext,
final Optional<HostnameVerifier> hostnameVerifier) {
return new RestTemplateTransportClientFactory();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,12 +19,6 @@ package org.springframework.cloud.netflix.eureka.http;
import java.net.URI;
import java.net.URISyntaxException;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.support.BasicAuthorizationInterceptor;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
@@ -44,6 +38,12 @@ import com.netflix.discovery.shared.resolver.EurekaEndpoint;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import com.netflix.discovery.shared.transport.TransportClientFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.support.BasicAuthorizationInterceptor;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
/**
* Provides the custom {@link RestTemplate} required by the
* {@link RestTemplateEurekaHttpClient}. Relies on Jackson for serialization and
@@ -85,13 +85,11 @@ public class RestTemplateTransportClientFactory implements TransportClientFactor
* Provides the serialization configurations required by the Eureka Server. JSON
* content exchanged with eureka requires a root node matching the entity being
* serialized or deserialized. Achived with
* {@link SerializationFeature.WRAP_ROOT_VALUE} and
* {@link DeserializationFeature.UNWRAP_ROOT_VALUE}.
* {@link SerializationFeature#WRAP_ROOT_VALUE} and
* {@link DeserializationFeature#UNWRAP_ROOT_VALUE}.
* {@link PropertyNamingStrategy.SnakeCaseStrategy} is applied to the underlying
* {@link ObjectMapper}.
*
*
* @return
* @return a {@link MappingJackson2HttpMessageConverter} object
*/
public MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
@@ -99,34 +97,49 @@ public class RestTemplateTransportClientFactory implements TransportClientFactor
.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE));
SimpleModule jsonModule = new SimpleModule();
jsonModule.setSerializerModifier(createJsonSerializerModifier());//keyFormatter, compact));
jsonModule.setSerializerModifier(createJsonSerializerModifier()); // keyFormatter,
// compact));
converter.getObjectMapper().registerModule(jsonModule);
converter.getObjectMapper().configure(SerializationFeature.WRAP_ROOT_VALUE, true);
converter.getObjectMapper().configure(DeserializationFeature.UNWRAP_ROOT_VALUE,
true);
converter.getObjectMapper().addMixIn(Applications.class, ApplicationsJsonMixIn.class);
converter.getObjectMapper().addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class);
// converter.getObjectMapper().addMixIn(DataCenterInfo.class, DataCenterInfoXmlMixIn.class);
// converter.getObjectMapper().addMixIn(InstanceInfo.PortWrapper.class, PortWrapperXmlMixIn.class);
// converter.getObjectMapper().addMixIn(Application.class, ApplicationXmlMixIn.class);
// converter.getObjectMapper().addMixIn(Applications.class, ApplicationsXmlMixIn.class);
converter.getObjectMapper().addMixIn(Applications.class,
ApplicationsJsonMixIn.class);
converter.getObjectMapper().addMixIn(InstanceInfo.class,
InstanceInfoJsonMixIn.class);
// converter.getObjectMapper().addMixIn(DataCenterInfo.class,
// DataCenterInfoXmlMixIn.class);
// converter.getObjectMapper().addMixIn(InstanceInfo.PortWrapper.class,
// PortWrapperXmlMixIn.class);
// converter.getObjectMapper().addMixIn(Application.class,
// ApplicationXmlMixIn.class);
// converter.getObjectMapper().addMixIn(Applications.class,
// ApplicationsXmlMixIn.class);
return converter;
}
public static BeanSerializerModifier createJsonSerializerModifier() {//final KeyFormatter keyFormatter, final boolean compactMode) {
public static BeanSerializerModifier createJsonSerializerModifier() { // final
// KeyFormatter
// keyFormatter,
// final
// boolean
// compactMode)
// {
return new BeanSerializerModifier() {
@Override
public JsonSerializer<?> modifySerializer(SerializationConfig config,
BeanDescription beanDesc, JsonSerializer<?> serializer) {
/*if (beanDesc.getBeanClass().isAssignableFrom(Applications.class)) {
return new ApplicationsJsonBeanSerializer((BeanSerializerBase) serializer, keyFormatter);
}*/
/*
* if (beanDesc.getBeanClass().isAssignableFrom(Applications.class)) {
* return new ApplicationsJsonBeanSerializer((BeanSerializerBase)
* serializer, keyFormatter); }
*/
if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) {
return new InstanceInfoJsonBeanSerializer((BeanSerializerBase) serializer, false);
return new InstanceInfoJsonBeanSerializer(
(BeanSerializerBase) serializer, false);
}
return serializer;
}
@@ -138,19 +151,21 @@ public class RestTemplateTransportClientFactory implements TransportClientFactor
}
class ErrorHanlder extends DefaultResponseErrorHandler {
@Override
protected boolean hasError(HttpStatus statusCode) {
/**
* When the Eureka server restarts and a client tries to sent a heartbeat the server
* will respond with a 404. By default RestTemplate will throw an exception in this case.
* What we want is to return the 404 to the upstream code so it will send another registration
* request to the server.
* When the Eureka server restarts and a client tries to sent a heartbeat the
* server will respond with a 404. By default RestTemplate will throw an
* exception in this case. What we want is to return the 404 to the upstream
* code so it will send another registration request to the server.
*/
if (statusCode.is4xxClientError()) {
return false;
}
return super.hasError(statusCode);
}
}
}
@@ -1,17 +1,41 @@
package org.springframework.cloud.netflix.eureka.metadata;
/*
* Copyright 2017-2019 the original author or authors.
*
* 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.
*/
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
import org.springframework.util.StringUtils;
package org.springframework.cloud.netflix.eureka.metadata;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
import org.springframework.util.StringUtils;
/**
* Default implementation of {@link DefaultManagementMetadataProvider}.
*
* @author Anastasiia Smirnova
*/
public class DefaultManagementMetadataProvider implements ManagementMetadataProvider {
private static final int RANDOM_PORT = 0;
private static final Log log = LogFactory.getLog(DefaultManagementMetadataProvider.class);
private static final Log log = LogFactory
.getLog(DefaultManagementMetadataProvider.class);
@Override
public ManagementMetadata get(EurekaInstanceConfigBean instance, int serverPort,
@@ -28,10 +52,11 @@ public class DefaultManagementMetadataProvider implements ManagementMetadataProv
String statusPageUrl = getStatusPageUrl(instance, serverPort, serverContextPath,
managementContextPath, managementPort);
ManagementMetadata metadata = new ManagementMetadata(healthCheckUrl, statusPageUrl, managementPort == null ? serverPort : managementPort);
ManagementMetadata metadata = new ManagementMetadata(healthCheckUrl,
statusPageUrl, managementPort == null ? serverPort : managementPort);
if (instance.isSecurePortEnabled()) {
metadata.setSecureHealthCheckUrl(getHealthCheckUrl(instance, serverPort, serverContextPath,
managementContextPath, managementPort, true));
metadata.setSecureHealthCheckUrl(getHealthCheckUrl(instance, serverPort,
serverContextPath, managementContextPath, managementPort, true));
}
return metadata;
}
@@ -40,20 +65,22 @@ public class DefaultManagementMetadataProvider implements ManagementMetadataProv
return port != null && port == RANDOM_PORT;
}
protected String getHealthCheckUrl(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath,
String managementContextPath, Integer managementPort, boolean isSecure) {
protected String getHealthCheckUrl(EurekaInstanceConfigBean instance, int serverPort,
String serverContextPath, String managementContextPath,
Integer managementPort, boolean isSecure) {
String healthCheckUrlPath = instance.getHealthCheckUrlPath();
String healthCheckUrl = getUrl(instance, serverPort, serverContextPath, managementContextPath,
managementPort, healthCheckUrlPath, isSecure);
String healthCheckUrl = getUrl(instance, serverPort, serverContextPath,
managementContextPath, managementPort, healthCheckUrlPath, isSecure);
log.debug("Constructed eureka meta-data healthcheckUrl: " + healthCheckUrl);
return healthCheckUrl;
}
public String getStatusPageUrl(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath,
String managementContextPath, Integer managementPort) {
public String getStatusPageUrl(EurekaInstanceConfigBean instance, int serverPort,
String serverContextPath, String managementContextPath,
Integer managementPort) {
String statusPageUrlPath = instance.getStatusPageUrlPath();
String statusPageUrl = getUrl(instance, serverPort, serverContextPath, managementContextPath,
managementPort, statusPageUrlPath, false);
String statusPageUrl = getUrl(instance, serverPort, serverContextPath,
managementContextPath, managementPort, statusPageUrlPath, false);
log.debug("Constructed eureka meta-data statusPageUrl: " + statusPageUrl);
return statusPageUrl;
}
@@ -61,17 +88,20 @@ public class DefaultManagementMetadataProvider implements ManagementMetadataProv
private String getUrl(EurekaInstanceConfigBean instance, int serverPort,
String serverContextPath, String managementContextPath,
Integer managementPort, String urlPath, boolean isSecure) {
managementContextPath = refineManagementContextPath(serverContextPath, managementContextPath, managementPort);
managementContextPath = refineManagementContextPath(serverContextPath,
managementContextPath, managementPort);
if (managementPort == null) {
managementPort = serverPort;
}
String scheme = isSecure ? "https" : "http";
return constructValidUrl(scheme, instance.getHostname(), managementPort, managementContextPath, urlPath);
return constructValidUrl(scheme, instance.getHostname(), managementPort,
managementContextPath, urlPath);
}
private String refineManagementContextPath(String serverContextPath, String managementContextPath,
Integer managementPort) {
// management context path is relative to server context path when no management port is set
private String refineManagementContextPath(String serverContextPath,
String managementContextPath, Integer managementPort) {
// management context path is relative to server context path when no management
// port is set
if (managementContextPath != null && managementPort == null) {
return serverContextPath + managementContextPath;
}
@@ -90,18 +120,24 @@ public class DefaultManagementMetadataProvider implements ManagementMetadataProv
if (!contextPath.endsWith("/")) {
contextPath = contextPath + "/";
}
String refinedContextPath = '/' + StringUtils.trimLeadingCharacter(contextPath, '/') ;
String refinedContextPath = '/'
+ StringUtils.trimLeadingCharacter(contextPath, '/');
URL base = new URL(scheme, hostname, port, refinedContextPath);
String refinedStatusPath = StringUtils.trimLeadingCharacter(statusPath, '/');
return new URL(base, refinedStatusPath).toString();
} catch (MalformedURLException e) {
String message = getErrorMessage(scheme, hostname, port, contextPath, statusPath);
}
catch (MalformedURLException e) {
String message = getErrorMessage(scheme, hostname, port, contextPath,
statusPath);
throw new IllegalStateException(message, e);
}
}
private String getErrorMessage(String scheme, String hostname, int port, String contextPath, String statusPath) {
return String.format("Failed to construct url for scheme: %s, hostName: %s port: %s contextPath: %s statusPath: %s",
private String getErrorMessage(String scheme, String hostname, int port,
String contextPath, String statusPath) {
return String.format(
"Failed to construct url for scheme: %s, hostName: %s port: %s contextPath: %s statusPath: %s",
scheme, hostname, port, contextPath, statusPath);
}
}
@@ -1,15 +1,41 @@
/*
* Copyright 2017-2019 the original author or authors.
*
* 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 org.springframework.cloud.netflix.eureka.metadata;
import java.util.Objects;
/**
* Stores management metadata for Eureka.
*
* @author Anastasiia Smirnova
* @author Ryan Baxter
*/
public class ManagementMetadata {
private final String healthCheckUrl;
private final String statusPageUrl;
private final Integer managementPort;
private String secureHealthCheckUrl;
public ManagementMetadata(String healthCheckUrl, String statusPageUrl, Integer managementPort) {
public ManagementMetadata(String healthCheckUrl, String statusPageUrl,
Integer managementPort) {
this.healthCheckUrl = healthCheckUrl;
this.statusPageUrl = statusPageUrl;
this.managementPort = managementPort;
@@ -38,12 +64,16 @@ public class ManagementMetadata {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ManagementMetadata that = (ManagementMetadata) o;
return Objects.equals(healthCheckUrl, that.healthCheckUrl) &&
Objects.equals(statusPageUrl, that.statusPageUrl) &&
Objects.equals(managementPort, that.managementPort);
return Objects.equals(healthCheckUrl, that.healthCheckUrl)
&& Objects.equals(statusPageUrl, that.statusPageUrl)
&& Objects.equals(managementPort, that.managementPort);
}
@Override
@@ -60,4 +90,5 @@ public class ManagementMetadata {
sb.append('}');
return sb.toString();
}
}
@@ -1,10 +1,32 @@
/*
* Copyright 2017-2019 the original author or authors.
*
* 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 org.springframework.cloud.netflix.eureka.metadata;
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
/**
* Provider for Eureka-specific management metadata.
*
* @author Anastasiia Smirnova
*/
public interface ManagementMetadataProvider {
ManagementMetadata get(EurekaInstanceConfigBean instance, int serverPort,
String serverContextPath, String managementContextPath, Integer managementPort);
String serverContextPath, String managementContextPath,
Integer managementPort);
}
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.eureka.serviceregistry;
@@ -38,9 +37,10 @@ import org.springframework.core.Ordered;
* @author Spencer Gibb
* @author Jon Schneider
* @author Jakub Narloch
* @author raiyan
* @author Raiyan Raiyan
*/
public class EurekaAutoServiceRegistration implements AutoServiceRegistration, SmartLifecycle, Ordered, SmartApplicationListener {
public class EurekaAutoServiceRegistration implements AutoServiceRegistration,
SmartLifecycle, Ordered, SmartApplicationListener {
private static final Log log = LogFactory.getLog(EurekaAutoServiceRegistration.class);
@@ -56,7 +56,8 @@ public class EurekaAutoServiceRegistration implements AutoServiceRegistration, S
private EurekaRegistration registration;
public EurekaAutoServiceRegistration(ApplicationContext context, EurekaServiceRegistry serviceRegistry, EurekaRegistration registration) {
public EurekaAutoServiceRegistration(ApplicationContext context,
EurekaServiceRegistry serviceRegistry, EurekaRegistration registration) {
this.context = context;
this.serviceRegistry = serviceRegistry;
this.registration = registration;
@@ -81,11 +82,12 @@ public class EurekaAutoServiceRegistration implements AutoServiceRegistration, S
this.serviceRegistry.register(this.registration);
this.context.publishEvent(
new InstanceRegisteredEvent<>(this, this.registration.getInstanceConfig()));
this.context.publishEvent(new InstanceRegisteredEvent<>(this,
this.registration.getInstanceConfig()));
this.running.set(true);
}
}
@Override
public void stop() {
this.serviceRegistry.deregister(this.registration);
@@ -118,7 +120,6 @@ public class EurekaAutoServiceRegistration implements AutoServiceRegistration, S
return this.order;
}
@Override
public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
return WebServerInitializedEvent.class.isAssignableFrom(eventType)
@@ -129,7 +130,8 @@ public class EurekaAutoServiceRegistration implements AutoServiceRegistration, S
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof WebServerInitializedEvent) {
onApplicationEvent((WebServerInitializedEvent) event);
} else if (event instanceof ContextClosedEvent) {
}
else if (event instanceof ContextClosedEvent) {
onApplicationEvent((ContextClosedEvent) event);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.eureka.serviceregistry;
@@ -21,8 +20,14 @@ import java.net.URI;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.ObjectProvider;
@@ -34,26 +39,29 @@ import org.springframework.cloud.netflix.eureka.InstanceInfoFactory;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.util.Assert;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
/**
* Eureka-specific implementation of service instance {@link Registration}.
*
* @author Spencer Gibb
* @author Tim Ysewyn
*/
public class EurekaRegistration implements Registration {
private static final Log log = LogFactory.getLog(EurekaRegistration.class);
private final EurekaClient eurekaClient;
private final AtomicReference<CloudEurekaClient> cloudEurekaClient = new AtomicReference<>();
private final CloudEurekaInstanceConfig instanceConfig;
private final ApplicationInfoManager applicationInfoManager;
private ObjectProvider<HealthCheckHandler> healthCheckHandler;
private EurekaRegistration(CloudEurekaInstanceConfig instanceConfig, EurekaClient eurekaClient, ApplicationInfoManager applicationInfoManager, ObjectProvider<HealthCheckHandler> healthCheckHandler) {
private EurekaRegistration(CloudEurekaInstanceConfig instanceConfig,
EurekaClient eurekaClient, ApplicationInfoManager applicationInfoManager,
ObjectProvider<HealthCheckHandler> healthCheckHandler) {
this.eurekaClient = eurekaClient;
this.instanceConfig = instanceConfig;
this.applicationInfoManager = applicationInfoManager;
@@ -64,58 +72,6 @@ public class EurekaRegistration implements Registration {
return new Builder(instanceConfig);
}
public static class Builder {
private final CloudEurekaInstanceConfig instanceConfig;
private ApplicationInfoManager applicationInfoManager;
private EurekaClient eurekaClient;
private ObjectProvider<HealthCheckHandler> healthCheckHandler;
private EurekaClientConfig clientConfig;
private ApplicationEventPublisher publisher;
Builder(CloudEurekaInstanceConfig instanceConfig) {
this.instanceConfig = instanceConfig;
}
public Builder with(ApplicationInfoManager applicationInfoManager) {
this.applicationInfoManager = applicationInfoManager;
return this;
}
public Builder with(EurekaClient eurekaClient) {
this.eurekaClient = eurekaClient;
return this;
}
public Builder with(ObjectProvider<HealthCheckHandler> healthCheckHandler) {
this.healthCheckHandler = healthCheckHandler;
return this;
}
public Builder with(EurekaClientConfig clientConfig, ApplicationEventPublisher publisher) {
this.clientConfig = clientConfig;
this.publisher = publisher;
return this;
}
public EurekaRegistration build() {
Assert.notNull(instanceConfig, "instanceConfig may not be null");
if (this.applicationInfoManager == null) {
InstanceInfo instanceInfo = new InstanceInfoFactory().create(this.instanceConfig);
this.applicationInfoManager = new ApplicationInfoManager(this.instanceConfig, instanceInfo);
}
if (this.eurekaClient == null) {
Assert.notNull(this.clientConfig, "if eurekaClient is null, EurekaClientConfig may not be null");
Assert.notNull(this.publisher, "if eurekaClient is null, ApplicationEventPublisher may not be null");
this.eurekaClient = new CloudEurekaClient(this.applicationInfoManager, this.clientConfig, this.publisher);
}
return new EurekaRegistration(instanceConfig, eurekaClient, applicationInfoManager, healthCheckHandler);
}
}
@Override
public String getInstanceId() {
return this.instanceConfig.getInstanceId();
@@ -157,8 +113,10 @@ public class EurekaRegistration implements Registration {
public CloudEurekaClient getEurekaClient() {
if (this.cloudEurekaClient.get() == null) {
try {
this.cloudEurekaClient.compareAndSet(null, getTargetObject(eurekaClient, CloudEurekaClient.class));
} catch (Exception e) {
this.cloudEurekaClient.compareAndSet(null,
getTargetObject(eurekaClient, CloudEurekaClient.class));
}
catch (Exception e) {
log.error("error getting CloudEurekaClient", e);
}
}
@@ -169,8 +127,10 @@ public class EurekaRegistration implements Registration {
protected <T> T getTargetObject(Object proxy, Class<T> targetClass) throws Exception {
if (AopUtils.isJdkDynamicProxy(proxy)) {
return (T) ((Advised) proxy).getTargetSource().getTarget();
} else {
return (T) proxy; // expected to be cglib proxy then, which is simply a specialized class
}
else {
return (T) proxy; // expected to be cglib proxy then, which is simply a
// specialized class
}
}
@@ -186,7 +146,8 @@ public class EurekaRegistration implements Registration {
return healthCheckHandler;
}
public void setHealthCheckHandler(ObjectProvider<HealthCheckHandler> healthCheckHandler) {
public void setHealthCheckHandler(
ObjectProvider<HealthCheckHandler> healthCheckHandler) {
this.healthCheckHandler = healthCheckHandler;
}
@@ -206,4 +167,71 @@ public class EurekaRegistration implements Registration {
return this.instanceConfig.getSecurePort();
}
/**
* A builder for {@link EurekaRegistration} objects.
*/
public static class Builder {
private final CloudEurekaInstanceConfig instanceConfig;
private ApplicationInfoManager applicationInfoManager;
private EurekaClient eurekaClient;
private ObjectProvider<HealthCheckHandler> healthCheckHandler;
private EurekaClientConfig clientConfig;
private ApplicationEventPublisher publisher;
Builder(CloudEurekaInstanceConfig instanceConfig) {
this.instanceConfig = instanceConfig;
}
public Builder with(ApplicationInfoManager applicationInfoManager) {
this.applicationInfoManager = applicationInfoManager;
return this;
}
public Builder with(EurekaClient eurekaClient) {
this.eurekaClient = eurekaClient;
return this;
}
public Builder with(ObjectProvider<HealthCheckHandler> healthCheckHandler) {
this.healthCheckHandler = healthCheckHandler;
return this;
}
public Builder with(EurekaClientConfig clientConfig,
ApplicationEventPublisher publisher) {
this.clientConfig = clientConfig;
this.publisher = publisher;
return this;
}
public EurekaRegistration build() {
Assert.notNull(instanceConfig, "instanceConfig may not be null");
if (this.applicationInfoManager == null) {
InstanceInfo instanceInfo = new InstanceInfoFactory()
.create(this.instanceConfig);
this.applicationInfoManager = new ApplicationInfoManager(
this.instanceConfig, instanceInfo);
}
if (this.eurekaClient == null) {
Assert.notNull(this.clientConfig,
"if eurekaClient is null, EurekaClientConfig may not be null");
Assert.notNull(this.publisher,
"if eurekaClient is null, ApplicationEventPublisher may not be null");
this.eurekaClient = new CloudEurekaClient(this.applicationInfoManager,
this.clientConfig, this.publisher);
}
return new EurekaRegistration(instanceConfig, eurekaClient,
applicationInfoManager, healthCheckHandler);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,18 +12,17 @@
* 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 org.springframework.cloud.netflix.eureka.serviceregistry;
import java.util.HashMap;
import com.netflix.appinfo.InstanceInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import com.netflix.appinfo.InstanceInfo;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import static com.netflix.appinfo.InstanceInfo.InstanceStatus.UNKNOWN;
@@ -39,7 +38,8 @@ public class EurekaServiceRegistry implements ServiceRegistry<EurekaRegistration
maybeInitializeClient(reg);
if (log.isInfoEnabled()) {
log.info("Registering application " + reg.getApplicationInfoManager().getInfo().getAppName()
log.info("Registering application "
+ reg.getApplicationInfoManager().getInfo().getAppName()
+ " with eureka with status "
+ reg.getInstanceConfig().getInitialStatus());
}
@@ -47,8 +47,8 @@ public class EurekaServiceRegistry implements ServiceRegistry<EurekaRegistration
reg.getApplicationInfoManager()
.setInstanceStatus(reg.getInstanceConfig().getInitialStatus());
reg.getHealthCheckHandler().ifAvailable(healthCheckHandler ->
reg.getEurekaClient().registerHealthCheck(healthCheckHandler));
reg.getHealthCheckHandler().ifAvailable(healthCheckHandler -> reg
.getEurekaClient().registerHealthCheck(healthCheckHandler));
}
private void maybeInitializeClient(EurekaRegistration reg) {
@@ -62,11 +62,13 @@ public class EurekaServiceRegistry implements ServiceRegistry<EurekaRegistration
if (reg.getApplicationInfoManager().getInfo() != null) {
if (log.isInfoEnabled()) {
log.info("Unregistering application " + reg.getApplicationInfoManager().getInfo().getAppName()
log.info("Unregistering application "
+ reg.getApplicationInfoManager().getInfo().getAppName()
+ " with eureka with status DOWN");
}
reg.getApplicationInfoManager().setInstanceStatus(InstanceInfo.InstanceStatus.DOWN);
reg.getApplicationInfoManager()
.setInstanceStatus(InstanceInfo.InstanceStatus.DOWN);
// shutdown of eureka client should happen with EurekaRegistration.close()
// auto registration will create a bean which will be properly disposed
@@ -85,7 +87,8 @@ public class EurekaServiceRegistry implements ServiceRegistry<EurekaRegistration
}
// TODO: howto deal with status types across discovery systems?
InstanceInfo.InstanceStatus newStatus = InstanceInfo.InstanceStatus.toEnum(status);
InstanceInfo.InstanceStatus newStatus = InstanceInfo.InstanceStatus
.toEnum(status);
registration.getEurekaClient().setStatus(newStatus, info);
}
@@ -93,13 +96,15 @@ public class EurekaServiceRegistry implements ServiceRegistry<EurekaRegistration
public Object getStatus(EurekaRegistration registration) {
String appname = registration.getApplicationInfoManager().getInfo().getAppName();
String instanceId = registration.getApplicationInfoManager().getInfo().getId();
InstanceInfo info = registration.getEurekaClient().getInstanceInfo(appname, instanceId);
InstanceInfo info = registration.getEurekaClient().getInstanceInfo(appname,
instanceId);
HashMap<String, Object> status = new HashMap<>();
if (info != null) {
status.put("status", info.getStatus().toString());
status.put("overriddenStatus", info.getOverriddenStatus().toString());
} else {
}
else {
status.put("status", UNKNOWN.toString());
}
@@ -1,3 +1,19 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* 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 org.springframework.cloud.netflix.ribbon.eureka;
import java.lang.annotation.Documented;
@@ -6,6 +22,9 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import com.netflix.discovery.EurekaClient;
import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList;
import org.springframework.boot.autoconfigure.condition.AllNestedConditions;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@@ -13,9 +32,11 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import org.springframework.context.annotation.Conditional;
import com.netflix.discovery.EurekaClient;
import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList;
/**
* Conditional that requires both Ribbon and Eureka to be enabled.
* @author Ihor Kryvenko
* @author Spencer Gibb
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@@ -24,19 +45,27 @@ public @interface ConditionalOnRibbonAndEurekaEnabled {
class OnRibbonAndEurekaEnabledCondition extends AllNestedConditions {
public OnRibbonAndEurekaEnabledCondition() {
OnRibbonAndEurekaEnabledCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnClass(DiscoveryEnabledNIWSServerList.class)
@ConditionalOnBean(SpringClientFactory.class)
@ConditionalOnProperty(value = "ribbon.eureka.enabled", matchIfMissing = true)
static class Defaults {}
static class Defaults {
}
@ConditionalOnBean(EurekaClient.class)
static class EurekaBeans {}
static class EurekaBeans {
}
@ConditionalOnProperty(value = "eureka.client.enabled", matchIfMissing = true)
static class OnEurekaClientEnabled {}
static class OnEurekaClientEnabled {
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,20 +19,21 @@ package org.springframework.cloud.netflix.ribbon.eureka;
import java.util.ArrayList;
import java.util.List;
import org.springframework.cloud.netflix.ribbon.RibbonProperties;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;
import org.springframework.cloud.netflix.ribbon.RibbonProperties;
/**
* @author Dave Syer
*/
public class DomainExtractingServerList implements ServerList<DiscoveryEnabledServer> {
private ServerList<DiscoveryEnabledServer> list;
private final RibbonProperties ribbon;
private boolean approximateZoneFromHostname;
@@ -46,15 +47,15 @@ public class DomainExtractingServerList implements ServerList<DiscoveryEnabledSe
@Override
public List<DiscoveryEnabledServer> getInitialListOfServers() {
List<DiscoveryEnabledServer> servers = setZones(this.list
.getInitialListOfServers());
List<DiscoveryEnabledServer> servers = setZones(
this.list.getInitialListOfServers());
return servers;
}
@Override
public List<DiscoveryEnabledServer> getUpdatedListOfServers() {
List<DiscoveryEnabledServer> servers = setZones(this.list
.getUpdatedListOfServers());
List<DiscoveryEnabledServer> servers = setZones(
this.list.getUpdatedListOfServers());
return servers;
}
@@ -85,7 +86,7 @@ class DomainExtractingServer extends DiscoveryEnabledServer {
this.id = id;
}
public DomainExtractingServer(DiscoveryEnabledServer server, boolean useSecurePort,
DomainExtractingServer(DiscoveryEnabledServer server, boolean useSecurePort,
boolean useIpAddr, boolean approximateZoneFromHostname) {
// host and port are set in super()
super(server.getInstanceInfo(), useSecurePort, useIpAddr);
@@ -108,9 +109,11 @@ class DomainExtractingServer extends DiscoveryEnabledServer {
DiscoveryEnabledServer enabled = (DiscoveryEnabledServer) server;
InstanceInfo instance = enabled.getInstanceInfo();
if (instance.getMetadata().containsKey("instanceId")) {
return instance.getHostName()+":"+instance.getMetadata().get("instanceId");
return instance.getHostName() + ":"
+ instance.getMetadata().get("instanceId");
}
}
return super.getId();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,9 +19,19 @@ package org.springframework.cloud.netflix.ribbon.eureka;
import javax.annotation.PostConstruct;
import javax.inject.Provider;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.client.config.IClientConfig;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DeploymentContext.ContextKey;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.ServerList;
import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList;
import com.netflix.niws.loadbalancer.NIWSDiscoveryPing;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
@@ -33,16 +43,6 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import com.netflix.appinfo.EurekaInstanceConfig;
import com.netflix.client.config.IClientConfig;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DeploymentContext.ContextKey;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.loadbalancer.IPing;
import com.netflix.loadbalancer.ServerList;
import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList;
import com.netflix.niws.loadbalancer.NIWSDiscoveryPing;
/**
* Preprocessor that configures defaults for eureka-discovered ribbon clients. Such as:
* <code>@zone</code>, NIWSServerListClassName, DeploymentContextBasedVipAddresses,
@@ -55,7 +55,8 @@ import com.netflix.niws.loadbalancer.NIWSDiscoveryPing;
@Configuration
public class EurekaRibbonClientConfiguration {
private static final Log log = LogFactory.getLog(EurekaRibbonClientConfiguration.class);
private static final Log log = LogFactory
.getLog(EurekaRibbonClientConfiguration.class);
@Value("${ribbon.eureka.approximateZoneFromHostname:false}")
private boolean approximateZoneFromHostname = false;
@@ -97,7 +98,8 @@ public class EurekaRibbonClientConfiguration {
@Bean
@ConditionalOnMissingBean
public ServerList<?> ribbonServerList(IClientConfig config, Provider<EurekaClient> eurekaClientProvider) {
public ServerList<?> ribbonServerList(IClientConfig config,
Provider<EurekaClient> eurekaClientProvider) {
if (this.propertiesFactory.isSet(ServerList.class, serviceId)) {
return this.propertiesFactory.get(ServerList.class, config, serviceId);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,12 +18,12 @@ package org.springframework.cloud.netflix.ribbon.eureka;
import java.util.Map;
import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.loadbalancer.Server;
import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;
import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector;
/**
* @author Spencer Gibb
*/
@@ -33,7 +33,8 @@ public class EurekaServerIntrospector extends DefaultServerIntrospector {
public boolean isSecure(Server server) {
if (server instanceof DiscoveryEnabledServer) {
DiscoveryEnabledServer discoveryServer = (DiscoveryEnabledServer) server;
return discoveryServer.getInstanceInfo().isPortEnabled(InstanceInfo.PortType.SECURE);
return discoveryServer.getInstanceInfo()
.isPortEnabled(InstanceInfo.PortType.SECURE);
}
return super.isSecure(server);
}
@@ -46,4 +47,5 @@ public class EurekaServerIntrospector extends DefaultServerIntrospector {
}
return super.getMetadata(server);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,8 +23,8 @@ import org.springframework.cloud.netflix.ribbon.RibbonClients;
import org.springframework.context.annotation.Configuration;
/**
* Spring configuration for configuring Ribbon defaults to be Eureka based
* if Eureka client is enabled
* Spring configuration for configuring Ribbon defaults to be Eureka based if Eureka
* client is enabled.
*
* @author Dave Syer
* @author Biju Kunjummen
@@ -36,5 +36,4 @@ import org.springframework.context.annotation.Configuration;
@RibbonClients(defaultConfiguration = EurekaRibbonClientConfiguration.class)
public class RibbonEurekaAutoConfiguration {
}
@@ -1,4 +1,5 @@
/* Copyright 2013-2015 the original author or authors.
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,16 +13,22 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.netflix.ribbon.eureka;
import org.springframework.util.StringUtils;
/**
* Utility class for dealing with zones.
*
* @author Ryan Baxter
*
*/
public class ZoneUtils {
public final class ZoneUtils {
private ZoneUtils() {
throw new AssertionError("Must not instantiate utility class.");
}
/**
* Approximates Eureka zones from a host name. This method approximates the zone to be
@@ -1,5 +1,5 @@
/*
* Copyright 2015 the original author or authors.
* Copyright 2015-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
package org.springframework.cloud.netflix.eureka;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
@@ -52,11 +53,13 @@ public class ConditionalOnRefreshScopeTests {
@Configuration
protected static class Beans {
@Bean
@ConditionalOnRefreshScope
public String foo() {
return "foo";
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.eureka;
@@ -52,4 +51,5 @@ public class EurekaClientAutoConfigurationRandomPortTests {
public static class TestConfig {
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.eureka;
@@ -21,9 +20,17 @@ import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import org.junit.After;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.aop.framework.Advised;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.SearchStrategy;
@@ -45,22 +52,15 @@ import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.SystemEnvironmentPropertySource;
import org.springframework.test.util.ReflectionTestUtils;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.transport.jersey.EurekaJerseyClient;
import com.sun.jersey.client.apache4.ApacheHttpClient4;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Spencer Gibb
* @author Matt Jenkins
*/
public class EurekaClientAutoConfigurationTests {
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
@After
@@ -72,7 +72,8 @@ public class EurekaClientAutoConfigurationTests {
private void setupContext(Class<?>... config) {
ConfigurationPropertySources.attach(this.context.getEnvironment());
this.context.register(PropertyPlaceholderAutoConfiguration.class, EurekaDiscoveryClientConfiguration.class);
this.context.register(PropertyPlaceholderAutoConfiguration.class,
EurekaDiscoveryClientConfiguration.class);
for (Class<?> value : config) {
this.context.register(value);
}
@@ -81,26 +82,28 @@ public class EurekaClientAutoConfigurationTests {
}
@Test
public void shouldSetManagementPortInMetadataMapIfEqualToServerPort() throws Exception {
public void shouldSetManagementPortInMetadataMapIfEqualToServerPort()
throws Exception {
TestPropertyValues.of("server.port=8989").applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertEquals("8989", instance.getMetadataMap().get("management.port"));
assertThat(instance.getMetadataMap().get("management.port")).isEqualTo("8989");
}
@Test
public void shouldNotSetManagementAndJmxPortsInMetadataMap() throws Exception {
TestPropertyValues.of("server.port=8989", "management.server.port=0").applyTo(this.context);
TestPropertyValues.of("server.port=8989", "management.server.port=0")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertEquals(null, instance.getMetadataMap().get("management.port"));
assertEquals(null, instance.getMetadataMap().get("jmx.port"));
assertThat(instance.getMetadataMap().get("management.port")).isEqualTo(null);
assertThat(instance.getMetadataMap().get("jmx.port")).isEqualTo(null);
}
@Test
@@ -111,21 +114,23 @@ public class EurekaClientAutoConfigurationTests {
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertEquals("9999", instance.getMetadataMap().get("management.port"));
assertEquals("6789", instance.getMetadataMap().get("jmx.port"));
assertThat(instance.getMetadataMap().get("management.port")).isEqualTo("9999");
assertThat(instance.getMetadataMap().get("jmx.port")).isEqualTo("6789");
}
@Test
public void shouldNotResetManagementAndJmxPortsInMetadataMap() throws Exception {
TestPropertyValues.of("management.server.port=9999",
TestPropertyValues
.of("management.server.port=9999",
"eureka.instance.metadata-map.jmx.port=9898",
"eureka.instance.metadata-map.management.port=7878").applyTo(this.context);
"eureka.instance.metadata-map.management.port=7878")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertEquals("7878", instance.getMetadataMap().get("management.port"));
assertEquals("9898", instance.getMetadataMap().get("jmx.port"));
assertThat(instance.getMetadataMap().get("management.port")).isEqualTo("7878");
assertThat(instance.getMetadataMap().get("jmx.port")).isEqualTo("9898");
}
@Test
@@ -141,8 +146,8 @@ public class EurekaClientAutoConfigurationTests {
@Test
public void nonSecurePort() {
testNonSecurePortSystemProp("PORT");
assertEquals("eurekaClient",
this.context.getBeanDefinition("eurekaClient").getFactoryMethodName());
assertThat(this.context.getBeanDefinition("eurekaClient").getFactoryMethodName())
.isEqualTo("eurekaClient");
}
@Test
@@ -152,176 +157,196 @@ public class EurekaClientAutoConfigurationTests {
@Test
public void securePortUnderscores() {
TestPropertyValues.of("eureka.instance.secure-port-enabled=true").applyTo(this.context);
TestPropertyValues.of("eureka.instance.secure-port-enabled=true")
.applyTo(this.context);
addSystemEnvironment(this.context.getEnvironment(), "SERVER_PORT:8443");
setupContext();
assertEquals(8443, getInstanceConfig().getSecurePort());
assertThat(getInstanceConfig().getSecurePort()).isEqualTo(8443);
}
@Test
public void securePort() {
testSecurePort("PORT");
assertEquals("eurekaClient",
this.context.getBeanDefinition("eurekaClient").getFactoryMethodName());
assertThat(this.context.getBeanDefinition("eurekaClient").getFactoryMethodName())
.isEqualTo("eurekaClient");
}
@Test
public void managementPort() {
TestPropertyValues.of("server.port=8989",
"management.server.port=9999").applyTo(this.context);
TestPropertyValues.of("server.port=8989", "management.server.port=9999")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong status page: " + instance.getStatusPageUrl(),
instance.getStatusPageUrl().contains("9999"));
assertThat(instance.getStatusPageUrl().contains("9999"))
.as("Wrong status page: " + instance.getStatusPageUrl()).isTrue();
}
@Test
public void statusPageUrlPathAndManagementPort() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999",
"eureka.instance.statusPageUrlPath=/myStatusPage").applyTo(this.context);
TestPropertyValues
.of("server.port=8989", "management.server.port=9999",
"eureka.instance.statusPageUrlPath=/myStatusPage")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong status page: " + instance.getStatusPageUrl(),
instance.getStatusPageUrl().contains("/myStatusPage"));
assertThat(instance.getStatusPageUrl().contains("/myStatusPage"))
.as("Wrong status page: " + instance.getStatusPageUrl()).isTrue();
}
@Test
public void healthCheckUrlPathAndManagementPort() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999",
"eureka.instance.healthCheckUrlPath=/myHealthCheck").applyTo(this.context);
TestPropertyValues
.of("server.port=8989", "management.server.port=9999",
"eureka.instance.healthCheckUrlPath=/myHealthCheck")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong health check: " + instance.getHealthCheckUrl(),
instance.getHealthCheckUrl().contains("/myHealthCheck"));
assertThat(instance.getHealthCheckUrl().contains("/myHealthCheck"))
.as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue();
}
@Test
public void statusPageUrl_and_healthCheckUrl_do_not_contain_server_context_path() throws Exception {
TestPropertyValues.of("server.port=8989",
"management.server.port=9999", "server.contextPath=/service").applyTo(this.context);
public void statusPageUrl_and_healthCheckUrl_do_not_contain_server_context_path()
throws Exception {
TestPropertyValues.of("server.port=8989", "management.server.port=9999",
"server.contextPath=/service").applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong status page: " + instance.getStatusPageUrl(),
instance.getStatusPageUrl().endsWith(":9999/actuator/info"));
assertTrue("Wrong health check: " + instance.getHealthCheckUrl(),
instance.getHealthCheckUrl().endsWith(":9999/actuator/health"));
assertThat(instance.getStatusPageUrl().endsWith(":9999/actuator/info"))
.as("Wrong status page: " + instance.getStatusPageUrl()).isTrue();
assertThat(instance.getHealthCheckUrl().endsWith(":9999/actuator/health"))
.as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue();
}
@Test
public void statusPageUrl_and_healthCheckUrl_contain_management_context_path() throws Exception {
TestPropertyValues.of(
"server.port=8989", "management.server.servlet.context-path=/management").applyTo(this.context);
public void statusPageUrl_and_healthCheckUrl_contain_management_context_path()
throws Exception {
TestPropertyValues
.of("server.port=8989",
"management.server.servlet.context-path=/management")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong status page: " + instance.getStatusPageUrl(),
instance.getStatusPageUrl().endsWith(":8989/management/actuator/info"));
assertTrue("Wrong health check: " + instance.getHealthCheckUrl(),
instance.getHealthCheckUrl().endsWith(":8989/management/actuator/health"));
assertThat(instance.getStatusPageUrl().endsWith(":8989/management/actuator/info"))
.as("Wrong status page: " + instance.getStatusPageUrl()).isTrue();
assertThat(
instance.getHealthCheckUrl().endsWith(":8989/management/actuator/health"))
.as("Wrong health check: " + instance.getHealthCheckUrl())
.isTrue();
}
@Test
public void statusPageUrl_and_healthCheckUrl_contain_management_context_path_random_port() throws Exception {
TestPropertyValues.of(
"server.port=0", "management.server.servlet.context-path=/management").applyTo(this.context);
public void statusPageUrl_and_healthCheckUrl_contain_management_context_path_random_port()
throws Exception {
TestPropertyValues
.of("server.port=0", "management.server.servlet.context-path=/management")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong status page: " + instance.getStatusPageUrlPath(),
instance.getStatusPageUrlPath().equals("/management/actuator/info"));
assertTrue("Wrong health check: " + instance.getHealthCheckUrlPath(),
instance.getHealthCheckUrlPath().equals("/management/actuator/health"));
assertThat(instance.getStatusPageUrlPath().equals("/management/actuator/info"))
.as("Wrong status page: " + instance.getStatusPageUrlPath()).isTrue();
assertThat(instance.getHealthCheckUrlPath().equals("/management/actuator/health"))
.as("Wrong health check: " + instance.getHealthCheckUrlPath()).isTrue();
}
@Test
public void statusPageUrlPathAndManagementPortAndContextPath() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999", "management.server.servlet.context-path=/manage",
"eureka.instance.status-page-url-path=/myStatusPage").applyTo(this.context);
TestPropertyValues
.of("server.port=8989", "management.server.port=9999",
"management.server.servlet.context-path=/manage",
"eureka.instance.status-page-url-path=/myStatusPage")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong status page: " + instance.getStatusPageUrl(),
instance.getStatusPageUrl().endsWith(":9999/manage/myStatusPage"));
assertThat(instance.getStatusPageUrl().endsWith(":9999/manage/myStatusPage"))
.as("Wrong status page: " + instance.getStatusPageUrl()).isTrue();
}
@Test
public void healthCheckUrlPathAndManagementPortAndContextPath() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999", "management.server.servlet.context-path=/manage",
"eureka.instance.health-check-url-path=/myHealthCheck").applyTo(this.context);
TestPropertyValues
.of("server.port=8989", "management.server.port=9999",
"management.server.servlet.context-path=/manage",
"eureka.instance.health-check-url-path=/myHealthCheck")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong health check: " + instance.getHealthCheckUrl(),
instance.getHealthCheckUrl().endsWith(":9999/manage/myHealthCheck"));
assertThat(instance.getHealthCheckUrl().endsWith(":9999/manage/myHealthCheck"))
.as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue();
}
@Test
public void statusPageUrlPathAndManagementPortAndContextPathKebobCase() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999", "management.server.servlet.context-path=/manage",
"eureka.instance.status-page-url-path=/myStatusPage").applyTo(this.context);
TestPropertyValues
.of("server.port=8989", "management.server.port=9999",
"management.server.servlet.context-path=/manage",
"eureka.instance.status-page-url-path=/myStatusPage")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong status page: " + instance.getStatusPageUrl(),
instance.getStatusPageUrl().endsWith(":9999/manage/myStatusPage"));
assertThat(instance.getStatusPageUrl().endsWith(":9999/manage/myStatusPage"))
.as("Wrong status page: " + instance.getStatusPageUrl()).isTrue();
}
@Test
public void healthCheckUrlPathAndManagementPortAndContextPathKebobCase() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999", "management.server.servlet.context-path=/manage",
"eureka.instance.health-check-url-path=/myHealthCheck").applyTo(this.context);
TestPropertyValues
.of("server.port=8989", "management.server.port=9999",
"management.server.servlet.context-path=/manage",
"eureka.instance.health-check-url-path=/myHealthCheck")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong health check: " + instance.getHealthCheckUrl(),
instance.getHealthCheckUrl().endsWith(":9999/manage/myHealthCheck"));
assertThat(instance.getHealthCheckUrl().endsWith(":9999/manage/myHealthCheck"))
.as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue();
}
@Test
public void statusPageUrlPathAndManagementPortKabobCase() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999",
"eureka.instance.status-page-url-path=/myStatusPage").applyTo(this.context);
TestPropertyValues
.of("server.port=8989", "management.server.port=9999",
"eureka.instance.status-page-url-path=/myStatusPage")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong status page: " + instance.getStatusPageUrl(),
instance.getStatusPageUrl().contains("/myStatusPage"));
assertThat(instance.getStatusPageUrl().contains("/myStatusPage"))
.as("Wrong status page: " + instance.getStatusPageUrl()).isTrue();
}
@Test
public void statusPageUrlAndPreferIpAddress() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999", "eureka.instance.hostname=foo",
"eureka.instance.prefer-ip-address:true").applyTo(this.context);
TestPropertyValues.of("server.port=8989", "management.server.port=9999",
"eureka.instance.hostname=foo", "eureka.instance.prefer-ip-address:true")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertEquals("statusPageUrl is wrong", "http://" + instance.getIpAddress() + ":9999/actuator/info",
instance.getStatusPageUrl());
assertEquals("healthCheckUrl is wrong", "http://" + instance.getIpAddress() + ":9999/actuator/health",
instance.getHealthCheckUrl());
assertThat(instance.getStatusPageUrl()).as("statusPageUrl is wrong")
.isEqualTo("http://" + instance.getIpAddress() + ":9999/actuator/info");
assertThat(instance.getHealthCheckUrl()).as("healthCheckUrl is wrong")
.isEqualTo("http://" + instance.getIpAddress() + ":9999/actuator/health");
}
@Test
public void statusPageAndHealthCheckUrlsShouldSetUserDefinedIpAddress() {
TestPropertyValues.of("server.port=8989",
"management.server.port=9999", "eureka.instance.hostname=foo",
TestPropertyValues.of("server.port=8989", "management.server.port=9999",
"eureka.instance.hostname=foo",
"eureka.instance.ip-address:192.168.13.90",
"eureka.instance.prefer-ip-address:true").applyTo(this.context);
@@ -329,85 +354,95 @@ public class EurekaClientAutoConfigurationTests {
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertEquals("statusPageUrl is wrong", "http://192.168.13.90:9999/actuator/info",
instance.getStatusPageUrl());
assertEquals("healthCheckUrl is wrong", "http://192.168.13.90:9999/actuator/health",
instance.getHealthCheckUrl());
assertThat(instance.getStatusPageUrl()).as("statusPageUrl is wrong")
.isEqualTo("http://192.168.13.90:9999/actuator/info");
assertThat(instance.getHealthCheckUrl()).as("healthCheckUrl is wrong")
.isEqualTo("http://192.168.13.90:9999/actuator/health");
}
@Test
public void healthCheckUrlPathAndManagementPortKabobCase() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999",
"eureka.instance.health-check-url-path=/myHealthCheck").applyTo(this.context);
TestPropertyValues
.of("server.port=8989", "management.server.port=9999",
"eureka.instance.health-check-url-path=/myHealthCheck")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong health check: " + instance.getHealthCheckUrl(),
instance.getHealthCheckUrl().contains("/myHealthCheck"));
assertThat(instance.getHealthCheckUrl().contains("/myHealthCheck"))
.as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue();
}
@Test
public void statusPageUrlPathAndManagementPortUpperCase() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999").applyTo(this.context);
addSystemEnvironment(this.context.getEnvironment(), "EUREKA_INSTANCE_STATUS_PAGE_URL_PATH=/myStatusPage");
TestPropertyValues.of("server.port=8989", "management.server.port=9999")
.applyTo(this.context);
addSystemEnvironment(this.context.getEnvironment(),
"EUREKA_INSTANCE_STATUS_PAGE_URL_PATH=/myStatusPage");
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong status page: " + instance.getStatusPageUrl(),
instance.getStatusPageUrl().contains("/myStatusPage"));
assertThat(instance.getStatusPageUrl().contains("/myStatusPage"))
.as("Wrong status page: " + instance.getStatusPageUrl()).isTrue();
}
@Test
public void healthCheckUrlPathAndManagementPortUpperCase() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999").applyTo(this.context);
addSystemEnvironment(this.context.getEnvironment(), "EUREKA_INSTANCE_HEALTH_CHECK_URL_PATH=/myHealthCheck");
TestPropertyValues.of("server.port=8989", "management.server.port=9999")
.applyTo(this.context);
addSystemEnvironment(this.context.getEnvironment(),
"EUREKA_INSTANCE_HEALTH_CHECK_URL_PATH=/myHealthCheck");
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong health check: " + instance.getHealthCheckUrl(),
instance.getHealthCheckUrl().contains("/myHealthCheck"));
assertThat(instance.getHealthCheckUrl().contains("/myHealthCheck"))
.as("Wrong health check: " + instance.getHealthCheckUrl()).isTrue();
}
@Test
public void hostname() {
TestPropertyValues.of( "server.port=8989",
"management.server.port=9999", "eureka.instance.hostname=foo").applyTo(this.context);
TestPropertyValues.of("server.port=8989", "management.server.port=9999",
"eureka.instance.hostname=foo").applyTo(this.context);
setupContext(RefreshAutoConfiguration.class);
EurekaInstanceConfigBean instance = this.context
.getBean(EurekaInstanceConfigBean.class);
assertTrue("Wrong status page: " + instance.getStatusPageUrl(),
instance.getStatusPageUrl().contains("foo"));
assertThat(instance.getStatusPageUrl().contains("foo"))
.as("Wrong status page: " + instance.getStatusPageUrl()).isTrue();
}
@Test
public void refreshScopedBeans() {
setupContext(RefreshAutoConfiguration.class);
assertThat(this.context.getBeanDefinition("eurekaClient").getBeanClassName())
.startsWith(GenericScope.class.getName()+"$LockedScopedProxyFactoryBean");
assertThat(this.context.getBeanDefinition("eurekaApplicationInfoManager").getBeanClassName())
.startsWith(GenericScope.class.getName()+"$LockedScopedProxyFactoryBean");
.startsWith(
GenericScope.class.getName() + "$LockedScopedProxyFactoryBean");
assertThat(this.context.getBeanDefinition("eurekaApplicationInfoManager")
.getBeanClassName()).startsWith(
GenericScope.class.getName() + "$LockedScopedProxyFactoryBean");
}
@Test
public void shouldReregisterHealthCheckHandlerAfterRefresh() throws Exception {
TestPropertyValues.of("eureka.client.healthcheck.enabled=true").applyTo(this.context);
setupContext(RefreshAutoConfiguration.class, AutoServiceRegistrationConfiguration.class);
TestPropertyValues.of("eureka.client.healthcheck.enabled=true")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class,
AutoServiceRegistrationConfiguration.class);
EurekaClient oldEurekaClient = getLazyInitEurekaClient();
HealthCheckHandler healthCheckHandler = this.context.getBean("eurekaHealthCheckHandler", HealthCheckHandler.class);
HealthCheckHandler healthCheckHandler = this.context
.getBean("eurekaHealthCheckHandler", HealthCheckHandler.class);
assertThat(healthCheckHandler).isInstanceOf(EurekaHealthCheckHandler.class);
assertThat(oldEurekaClient.getHealthCheckHandler()).isSameAs(healthCheckHandler);
ContextRefresher refresher = this.context.getBean("contextRefresher", ContextRefresher.class);
ContextRefresher refresher = this.context.getBean("contextRefresher",
ContextRefresher.class);
refresher.refresh();
EurekaClient newEurekaClient = getLazyInitEurekaClient();
HealthCheckHandler newHealthCheckHandler = this.context.getBean("eurekaHealthCheckHandler", HealthCheckHandler.class);
HealthCheckHandler newHealthCheckHandler = this.context
.getBean("eurekaHealthCheckHandler", HealthCheckHandler.class);
assertThat(healthCheckHandler).isSameAs(newHealthCheckHandler);
assertThat(oldEurekaClient).isNotSameAs(newEurekaClient);
@@ -416,10 +451,13 @@ public class EurekaClientAutoConfigurationTests {
@Test
public void shouldCloseDiscoveryClient() throws Exception {
TestPropertyValues.of("eureka.client.healthcheck.enabled=true").applyTo(this.context);
setupContext(RefreshAutoConfiguration.class, AutoServiceRegistrationConfiguration.class);
TestPropertyValues.of("eureka.client.healthcheck.enabled=true")
.applyTo(this.context);
setupContext(RefreshAutoConfiguration.class,
AutoServiceRegistrationConfiguration.class);
AtomicBoolean isShutdown = (AtomicBoolean) ReflectionTestUtils.getField(getLazyInitEurekaClient(), "isShutdown");
AtomicBoolean isShutdown = (AtomicBoolean) ReflectionTestUtils
.getField(getLazyInitEurekaClient(), "isShutdown");
assertThat(isShutdown.get()).isFalse();
@@ -431,7 +469,8 @@ public class EurekaClientAutoConfigurationTests {
@Test
public void basicAuth() {
TestPropertyValues.of("server.port=8989",
"eureka.client.serviceUrl.defaultZone=http://user:foo@example.com:80/eureka").applyTo(this.context);
"eureka.client.serviceUrl.defaultZone=http://user:foo@example.com:80/eureka")
.applyTo(this.context);
setupContext(MockClientConfiguration.class);
// ApacheHttpClient4 http = this.context.getBean(ApacheHttpClient4.class);
// Mockito.verify(http).addFilter(Matchers.any(HTTPBasicAuthFilter.class));
@@ -440,30 +479,33 @@ public class EurekaClientAutoConfigurationTests {
@Test
public void testDefaultAppName() throws Exception {
setupContext();
assertEquals("unknown", getInstanceConfig().getAppname());
assertEquals("unknown", getInstanceConfig().getVirtualHostName());
assertEquals("unknown", getInstanceConfig().getSecureVirtualHostName());
assertThat(getInstanceConfig().getAppname()).isEqualTo("unknown");
assertThat(getInstanceConfig().getVirtualHostName()).isEqualTo("unknown");
assertThat(getInstanceConfig().getSecureVirtualHostName()).isEqualTo("unknown");
}
@Test
public void testAppName() throws Exception {
TestPropertyValues.of("spring.application.name=mytest").applyTo(this.context);
setupContext();
assertEquals("mytest", getInstanceConfig().getAppname());
assertEquals("mytest", getInstanceConfig().getVirtualHostName());
assertEquals("mytest", getInstanceConfig().getSecureVirtualHostName());
assertThat(getInstanceConfig().getAppname()).isEqualTo("mytest");
assertThat(getInstanceConfig().getVirtualHostName()).isEqualTo("mytest");
assertThat(getInstanceConfig().getSecureVirtualHostName()).isEqualTo("mytest");
}
@Test
public void testAppNameUpper() throws Exception {
addSystemEnvironment(this.context.getEnvironment(), "SPRING_APPLICATION_NAME=mytestupper");
addSystemEnvironment(this.context.getEnvironment(),
"SPRING_APPLICATION_NAME=mytestupper");
setupContext();
assertEquals("mytestupper", getInstanceConfig().getAppname());
assertEquals("mytestupper", getInstanceConfig().getVirtualHostName());
assertEquals("mytestupper", getInstanceConfig().getSecureVirtualHostName());
assertThat(getInstanceConfig().getAppname()).isEqualTo("mytestupper");
assertThat(getInstanceConfig().getVirtualHostName()).isEqualTo("mytestupper");
assertThat(getInstanceConfig().getSecureVirtualHostName())
.isEqualTo("mytestupper");
}
private void addSystemEnvironment(ConfigurableEnvironment environment, String... pairs) {
private void addSystemEnvironment(ConfigurableEnvironment environment,
String... pairs) {
MutablePropertySources sources = environment.getPropertySources();
Map<String, Object> map = getOrAdd(sources, "testsysenv");
for (String pair : pairs) {
@@ -499,10 +541,12 @@ public class EurekaClientAutoConfigurationTests {
@Test
public void testInstanceNamePreferred() throws Exception {
addSystemEnvironment(this.context.getEnvironment(), "SPRING_APPLICATION_NAME=mytestspringappname");
TestPropertyValues.of( "eureka.instance.appname=mytesteurekaappname").applyTo(this.context);
addSystemEnvironment(this.context.getEnvironment(),
"SPRING_APPLICATION_NAME=mytestspringappname");
TestPropertyValues.of("eureka.instance.appname=mytesteurekaappname")
.applyTo(this.context);
setupContext();
assertEquals("mytesteurekaappname", getInstanceConfig().getAppname());
assertThat(getInstanceConfig().getAppname()).isEqualTo("mytesteurekaappname");
}
@Test
@@ -524,19 +568,21 @@ public class EurekaClientAutoConfigurationTests {
private void testNonSecurePortSystemProp(String propName) {
addSystemEnvironment(this.context.getEnvironment(), propName + ":8888");
setupContext();
assertEquals(8888, getInstanceConfig().getNonSecurePort());
assertThat(getInstanceConfig().getNonSecurePort()).isEqualTo(8888);
}
private void testNonSecurePort(String propName) {
TestPropertyValues.of(propName + ":8888").applyTo(this.context);
setupContext();
assertEquals(8888, getInstanceConfig().getNonSecurePort());
assertThat(getInstanceConfig().getNonSecurePort()).isEqualTo(8888);
}
private void testSecurePort(String propName) {
TestPropertyValues.of("eureka.instance.secure-port-enabled=true", propName+":8443").applyTo(this.context);
TestPropertyValues
.of("eureka.instance.secure-port-enabled=true", propName + ":8443")
.applyTo(this.context);
setupContext();
assertEquals(8443, getInstanceConfig().getSecurePort());
assertThat(getInstanceConfig().getSecurePort()).isEqualTo(8443);
}
private EurekaInstanceConfigBean getInstanceConfig() {
@@ -544,13 +590,16 @@ public class EurekaClientAutoConfigurationTests {
}
private EurekaClient getLazyInitEurekaClient() throws Exception {
return (EurekaClient)((Advised) this.context.getBean("eurekaClient", EurekaClient.class)).getTargetSource().getTarget();
return (EurekaClient) ((Advised) this.context.getBean("eurekaClient",
EurekaClient.class)).getTargetSource().getTarget();
}
@Configuration
@EnableConfigurationProperties
@Import({ UtilAutoConfiguration.class, EurekaClientAutoConfiguration.class })
protected static class TestConfiguration { }
protected static class TestConfiguration {
}
@Configuration
protected static class TestEurekaClientConfiguration {
@@ -562,7 +611,8 @@ public class EurekaClientAutoConfigurationTests {
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingBean(value = EurekaClient.class, search = SearchStrategy.CURRENT)
public EurekaClient eurekaClient(ApplicationInfoManager manager, EurekaClientConfig config, ApplicationContext context) {
public EurekaClient eurekaClient(ApplicationInfoManager manager,
EurekaClientConfig config, ApplicationContext context) {
return new CloudEurekaClient(manager, config, null, context) {
@Override
public synchronized void shutdown() {
@@ -574,6 +624,7 @@ public class EurekaClientAutoConfigurationTests {
}
};
}
}
@Configuration
@@ -597,6 +648,7 @@ public class EurekaClientAutoConfigurationTests {
public ApacheHttpClient4 apacheClient() {
return Mockito.mock(ApacheHttpClient4.class);
}
}
@Configuration
@@ -604,4 +656,5 @@ public class EurekaClientAutoConfigurationTests {
public static class AutoServiceRegistrationConfiguration {
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.eureka;
@@ -21,6 +20,7 @@ import java.util.Collections;
import org.junit.After;
import org.junit.Test;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.util.TestPropertyValues;
@@ -29,7 +29,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.MapPropertySource;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Dave Syer
@@ -52,8 +52,8 @@ public class EurekaClientConfigBeanTests {
this.context.register(PropertyPlaceholderAutoConfiguration.class,
TestConfiguration.class);
this.context.refresh();
assertEquals("example.com", this.context.getBean(EurekaClientConfigBean.class)
.getProxyHost());
assertThat(this.context.getBean(EurekaClientConfigBean.class).getProxyHost())
.isEqualTo("example.com");
}
@Test
@@ -63,27 +63,28 @@ public class EurekaClientConfigBeanTests {
this.context.register(PropertyPlaceholderAutoConfiguration.class,
TestConfiguration.class);
this.context.refresh();
assertEquals("{defaultZone=http://example.com}",
this.context.getBean(EurekaClientConfigBean.class).getServiceUrl()
.toString());
assertEquals("[http://example.com/]", getEurekaServiceUrlsForDefaultZone());
assertThat(this.context.getBean(EurekaClientConfigBean.class).getServiceUrl()
.toString()).isEqualTo("{defaultZone=http://example.com}");
assertThat(getEurekaServiceUrlsForDefaultZone())
.isEqualTo("[http://example.com/]");
}
@Test
public void serviceUrlWithCompositePropertySource() {
CompositePropertySource source = new CompositePropertySource("composite");
this.context.getEnvironment().getPropertySources().addFirst(source);
source.addPropertySource(new MapPropertySource("config", Collections
.<String, Object> singletonMap("eureka.client.serviceUrl.defaultZone",
source.addPropertySource(new MapPropertySource("config",
Collections.<String, Object>singletonMap(
"eureka.client.serviceUrl.defaultZone",
"http://example.com,http://example2.com, http://example3.com")));
this.context.register(PropertyPlaceholderAutoConfiguration.class,
TestConfiguration.class);
this.context.refresh();
assertEquals("{defaultZone=http://example.com,http://example2.com, http://example3.com}",
this.context.getBean(EurekaClientConfigBean.class).getServiceUrl()
.toString());
assertEquals("[http://example.com/, http://example2.com/, http://example3.com/]",
getEurekaServiceUrlsForDefaultZone());
assertThat(this.context.getBean(EurekaClientConfigBean.class).getServiceUrl()
.toString()).isEqualTo(
"{defaultZone=http://example.com,http://example2.com, http://example3.com}");
assertThat(getEurekaServiceUrlsForDefaultZone()).isEqualTo(
"[http://example.com/, http://example2.com/, http://example3.com/]");
}
@Test
@@ -93,17 +94,20 @@ public class EurekaClientConfigBeanTests {
this.context.register(PropertyPlaceholderAutoConfiguration.class,
TestConfiguration.class);
this.context.refresh();
assertEquals("[http://example.com/]", getEurekaServiceUrlsForDefaultZone());
assertThat(getEurekaServiceUrlsForDefaultZone())
.isEqualTo("[http://example.com/]");
}
@Test
public void serviceUrlWithCustomZone() {
TestPropertyValues.of("eureka.client.serviceUrl.customZone:http://custom-example.com")
TestPropertyValues
.of("eureka.client.serviceUrl.customZone:http://custom-example.com")
.applyTo(this.context);
this.context.register(PropertyPlaceholderAutoConfiguration.class,
TestConfiguration.class);
this.context.refresh();
assertEquals("[http://custom-example.com/]", getEurekaServiceUrls("customZone"));
assertThat(getEurekaServiceUrls("customZone"))
.isEqualTo("[http://custom-example.com/]");
}
@Test
@@ -113,7 +117,7 @@ public class EurekaClientConfigBeanTests {
this.context.register(PropertyPlaceholderAutoConfiguration.class,
TestConfiguration.class);
this.context.refresh();
assertEquals("[]", getEurekaServiceUrlsForDefaultZone());
assertThat(getEurekaServiceUrlsForDefaultZone()).isEqualTo("[]");
}
private String getEurekaServiceUrlsForDefaultZone() {
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,9 +19,9 @@ package org.springframework.cloud.netflix.eureka;
import java.util.List;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import org.junit.Before;
import org.junit.Test;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
@@ -33,7 +33,7 @@ import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests the {@link EurekaHealthCheckHandler} with different health indicator registered.
@@ -54,7 +54,7 @@ public class EurekaHealthCheckHandlerTests {
public void testNoHealthCheckRegistered() throws Exception {
InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN);
assertEquals(InstanceStatus.UNKNOWN, status);
assertThat(status).isEqualTo(InstanceStatus.UNKNOWN);
}
@Test
@@ -63,7 +63,7 @@ public class EurekaHealthCheckHandlerTests {
initialize(UpHealthConfiguration.class);
InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN);
assertEquals(InstanceStatus.UP, status);
assertThat(status).isEqualTo(InstanceStatus.UP);
}
@Test
@@ -72,7 +72,7 @@ public class EurekaHealthCheckHandlerTests {
initialize(UpHealthConfiguration.class, DownHealthConfiguration.class);
InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN);
assertEquals(InstanceStatus.DOWN, status);
assertThat(status).isEqualTo(InstanceStatus.DOWN);
}
@Test
@@ -81,7 +81,7 @@ public class EurekaHealthCheckHandlerTests {
initialize(FatalHealthConfiguration.class);
InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UNKNOWN);
assertEquals(InstanceStatus.UNKNOWN, status);
assertThat(status).isEqualTo(InstanceStatus.UNKNOWN);
}
@Test
@@ -90,11 +90,12 @@ public class EurekaHealthCheckHandlerTests {
initialize(EurekaDownHealthConfiguration.class);
InstanceStatus status = healthCheckHandler.getStatus(InstanceStatus.UP);
assertEquals(InstanceStatus.UP, status);
assertThat(status).isEqualTo(InstanceStatus.UP);
}
private void initialize(Class<?>... configurations) throws Exception {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(configurations);
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(
configurations);
healthCheckHandler.setApplicationContext(applicationContext);
healthCheckHandler.afterPropertiesSet();
}
@@ -110,6 +111,7 @@ public class EurekaHealthCheckHandlerTests {
}
};
}
}
public static class DownHealthConfiguration {
@@ -123,6 +125,7 @@ public class EurekaHealthCheckHandlerTests {
}
};
}
}
public static class FatalHealthConfiguration {
@@ -136,10 +139,11 @@ public class EurekaHealthCheckHandlerTests {
}
};
}
}
public static class EurekaDownHealthConfiguration {
@Bean
public DiscoveryHealthIndicator discoveryHealthIndicator() {
return new DiscoveryClientHealthIndicator(null, null) {
@@ -161,8 +165,12 @@ public class EurekaHealthCheckHandlerTests {
}
@Bean
public DiscoveryCompositeHealthIndicator discoveryCompositeHealthIndicator(List<DiscoveryHealthIndicator> indicators) {
return new DiscoveryCompositeHealthIndicator(new OrderedHealthAggregator(), indicators);
public DiscoveryCompositeHealthIndicator discoveryCompositeHealthIndicator(
List<DiscoveryHealthIndicator> indicators) {
return new DiscoveryCompositeHealthIndicator(new OrderedHealthAggregator(),
indicators);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,14 +12,15 @@
* 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 org.springframework.cloud.netflix.eureka;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
@@ -33,10 +34,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.StringUtils;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Dave Syer
@@ -47,7 +46,9 @@ import static org.junit.Assert.assertTrue;
public class EurekaInstanceConfigBeanTests {
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
private String hostName;
private String ipAddress;
@Before
@@ -68,16 +69,17 @@ public class EurekaInstanceConfigBeanTests {
@Test
public void basicBinding() {
TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context);
TestPropertyValues.of("eureka.instance.appGroupName=mygroup")
.applyTo(this.context);
setupContext();
assertEquals("mygroup", getInstanceConfig().getAppGroupName());
assertThat(getInstanceConfig().getAppGroupName()).isEqualTo("mygroup");
}
@Test
public void nonSecurePort() {
TestPropertyValues.of("eureka.instance.nonSecurePort:8888").applyTo(this.context);
setupContext();
assertEquals(8888, getInstanceConfig().getNonSecurePort());
assertThat(getInstanceConfig().getNonSecurePort()).isEqualTo(8888);
}
@Test
@@ -85,76 +87,82 @@ public class EurekaInstanceConfigBeanTests {
TestPropertyValues.of("eureka.instance.instanceId:special").applyTo(this.context);
setupContext();
EurekaInstanceConfigBean instance = getInstanceConfig();
assertEquals("special", instance.getInstanceId());
assertThat(instance.getInstanceId()).isEqualTo("special");
}
@Test
public void initialHostName() {
TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context);
TestPropertyValues.of("eureka.instance.appGroupName=mygroup")
.applyTo(this.context);
setupContext();
if (this.hostName != null) {
assertEquals(this.hostName, getInstanceConfig().getHostname());
assertThat(getInstanceConfig().getHostname()).isEqualTo(this.hostName);
}
}
@Test
public void refreshHostName() {
TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context);
TestPropertyValues.of("eureka.instance.appGroupName=mygroup")
.applyTo(this.context);
setupContext();
ReflectionTestUtils.setField(getInstanceConfig(), "hostname", "marvin");
assertEquals("marvin", getInstanceConfig().getHostname());
assertThat(getInstanceConfig().getHostname()).isEqualTo("marvin");
getInstanceConfig().getHostName(true);
if (this.hostName != null) {
assertEquals(this.hostName, getInstanceConfig().getHostname());
assertThat(getInstanceConfig().getHostname()).isEqualTo(this.hostName);
}
}
@Test
public void refreshHostNameWhenSetByUser() {
TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context);
TestPropertyValues.of("eureka.instance.appGroupName=mygroup")
.applyTo(this.context);
setupContext();
getInstanceConfig().setHostname("marvin");
assertEquals("marvin", getInstanceConfig().getHostname());
assertThat(getInstanceConfig().getHostname()).isEqualTo("marvin");
getInstanceConfig().getHostName(true);
assertEquals("marvin", getInstanceConfig().getHostname());
assertThat(getInstanceConfig().getHostname()).isEqualTo("marvin");
}
@Test
public void initialIpAddress() {
TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context);
TestPropertyValues.of("eureka.instance.appGroupName=mygroup")
.applyTo(this.context);
setupContext();
if (this.ipAddress != null) {
assertEquals(this.ipAddress, getInstanceConfig().getIpAddress());
assertThat(getInstanceConfig().getIpAddress()).isEqualTo(this.ipAddress);
}
}
@Test
public void refreshIpAddress() {
TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context);
TestPropertyValues.of("eureka.instance.appGroupName=mygroup")
.applyTo(this.context);
setupContext();
ReflectionTestUtils.setField(getInstanceConfig(), "ipAddress", "10.0.0.1");
assertEquals("10.0.0.1", getInstanceConfig().getIpAddress());
assertThat(getInstanceConfig().getIpAddress()).isEqualTo("10.0.0.1");
getInstanceConfig().getHostName(true);
if (this.ipAddress != null) {
assertEquals(this.ipAddress, getInstanceConfig().getIpAddress());
assertThat(getInstanceConfig().getIpAddress()).isEqualTo(this.ipAddress);
}
}
@Test
public void refreshIpAddressWhenSetByUser() {
TestPropertyValues.of("eureka.instance.appGroupName=mygroup").applyTo(this.context);
TestPropertyValues.of("eureka.instance.appGroupName=mygroup")
.applyTo(this.context);
setupContext();
getInstanceConfig().setIpAddress("10.0.0.1");
assertEquals("10.0.0.1", getInstanceConfig().getIpAddress());
assertThat(getInstanceConfig().getIpAddress()).isEqualTo("10.0.0.1");
getInstanceConfig().getHostName(true);
assertEquals("10.0.0.1", getInstanceConfig().getIpAddress());
assertThat(getInstanceConfig().getIpAddress()).isEqualTo("10.0.0.1");
}
@Test
public void testDefaultInitialStatus() {
setupContext();
assertEquals("initialStatus wrong", InstanceStatus.UP,
getInstanceConfig().getInitialStatus());
assertThat(getInstanceConfig().getInitialStatus()).as("initialStatus wrong")
.isEqualTo(InstanceStatus.UP);
}
@Test(expected = BeanCreationException.class)
@@ -165,19 +173,21 @@ public class EurekaInstanceConfigBeanTests {
@Test
public void testCustomInitialStatus() {
TestPropertyValues.of("eureka.instance.initial-status:STARTING").applyTo(this.context);
TestPropertyValues.of("eureka.instance.initial-status:STARTING")
.applyTo(this.context);
setupContext();
assertEquals("initialStatus wrong", InstanceStatus.STARTING,
getInstanceConfig().getInitialStatus());
assertThat(getInstanceConfig().getInitialStatus()).as("initialStatus wrong")
.isEqualTo(InstanceStatus.STARTING);
}
@Test
public void testPreferIpAddress() throws Exception {
TestPropertyValues.of("eureka.instance.preferIpAddress:true").applyTo(this.context);
TestPropertyValues.of("eureka.instance.preferIpAddress:true")
.applyTo(this.context);
setupContext();
EurekaInstanceConfigBean instance = getInstanceConfig();
assertTrue("Wrong hostname: " + instance.getHostname(),
getInstanceConfig().getHostname().equals(instance.getIpAddress()));
assertThat(getInstanceConfig().getHostname().equals(instance.getIpAddress()))
.as("Wrong hostname: " + instance.getHostname()).isTrue();
}
@@ -185,47 +195,62 @@ public class EurekaInstanceConfigBeanTests {
public void testDefaultVirtualHostName() throws Exception {
TestPropertyValues.of("spring.application.name:myapp").applyTo(this.context);
setupContext();
assertEquals("virtualHostName wrong", "myapp", getInstanceConfig().getVirtualHostName());
assertEquals("secureVirtualHostName wrong", "myapp", getInstanceConfig().getSecureVirtualHostName());
assertThat(getInstanceConfig().getVirtualHostName()).as("virtualHostName wrong")
.isEqualTo("myapp");
assertThat(getInstanceConfig().getSecureVirtualHostName())
.as("secureVirtualHostName wrong").isEqualTo("myapp");
}
@Test
public void testCustomVirtualHostName() throws Exception {
TestPropertyValues.of("spring.application.name:myapp", "eureka.instance.virtualHostName=myvirthost",
"eureka.instance.secureVirtualHostName=mysecurevirthost").applyTo(this.context);
TestPropertyValues
.of("spring.application.name:myapp",
"eureka.instance.virtualHostName=myvirthost",
"eureka.instance.secureVirtualHostName=mysecurevirthost")
.applyTo(this.context);
setupContext();
assertEquals("virtualHostName wrong", "myvirthost", getInstanceConfig().getVirtualHostName());
assertEquals("secureVirtualHostName wrong", "mysecurevirthost", getInstanceConfig().getSecureVirtualHostName());
assertThat(getInstanceConfig().getVirtualHostName()).as("virtualHostName wrong")
.isEqualTo("myvirthost");
assertThat(getInstanceConfig().getSecureVirtualHostName())
.as("secureVirtualHostName wrong").isEqualTo("mysecurevirthost");
}
@Test
public void testDefaultAppName() throws Exception {
setupContext();
assertEquals("default app name is wrong", "unknown", getInstanceConfig().getAppname());
assertEquals("default virtual hostname is wrong", "unknown", getInstanceConfig().getVirtualHostName());
assertEquals("default secure virtual hostname is wrong", "unknown", getInstanceConfig().getSecureVirtualHostName());
assertThat(getInstanceConfig().getAppname()).as("default app name is wrong")
.isEqualTo("unknown");
assertThat(getInstanceConfig().getVirtualHostName())
.as("default virtual hostname is wrong").isEqualTo("unknown");
assertThat(getInstanceConfig().getSecureVirtualHostName())
.as("default secure virtual hostname is wrong").isEqualTo("unknown");
}
@Test
public void testCustomInstanceId() throws Exception {
TestPropertyValues.of("eureka.instance.instanceId=myinstance").applyTo(this.context);
TestPropertyValues.of("eureka.instance.instanceId=myinstance")
.applyTo(this.context);
setupContext();
assertEquals("instance id is wrong", "myinstance", getInstanceConfig().getInstanceId());
assertThat(getInstanceConfig().getInstanceId()).as("instance id is wrong")
.isEqualTo("myinstance");
}
@Test
public void testCustomInstanceIdWithMetadata() throws Exception {
TestPropertyValues.of("eureka.instance.metadataMap.instanceId=myinstance").applyTo(this.context);
TestPropertyValues.of("eureka.instance.metadataMap.instanceId=myinstance")
.applyTo(this.context);
setupContext();
assertEquals("instance id is wrong", "myinstance", getInstanceConfig().getInstanceId());
assertThat(getInstanceConfig().getInstanceId()).as("instance id is wrong")
.isEqualTo("myinstance");
}
@Test
public void testDefaultInstanceId() throws Exception {
setupContext();
assertEquals("default instance id is wrong", null, getInstanceConfig().getInstanceId());
assertThat(getInstanceConfig().getInstanceId()).as("default instance id is wrong")
.isEqualTo(null);
}
private void setupContext() {
@@ -241,11 +266,14 @@ public class EurekaInstanceConfigBeanTests {
@Configuration
@EnableConfigurationProperties
protected static class TestConfiguration {
@Autowired
ConfigurableEnvironment env;
@Bean
public EurekaInstanceConfigBean eurekaInstanceConfigBean() {
EurekaInstanceConfigBean configBean = new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties()));
EurekaInstanceConfigBean configBean = new EurekaInstanceConfigBean(
new InetUtils(new InetUtilsProperties()));
String springAppName = this.env.getProperty("spring.application.name", "");
if (StringUtils.hasText(springAppName)) {
configBean.setSecureVirtualHostName(springAppName);
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,14 +12,15 @@
* 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 org.springframework.cloud.netflix.eureka;
import java.io.IOException;
import com.netflix.appinfo.InstanceInfo;
import org.junit.Test;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.util.TestPropertyValues;
@@ -29,33 +30,31 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.appinfo.InstanceInfo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
public class InstanceInfoFactoryTests {
private AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
@Test
public void instanceIdIsHostNameByDefault() throws IOException {
InstanceInfo instanceInfo = setupInstance();
try (InetUtils utils = new InetUtils(new InetUtilsProperties())) {
assertEquals(utils.findFirstNonLoopbackHostInfo().getHostname(),
instanceInfo.getId());
assertThat(instanceInfo.getId())
.isEqualTo(utils.findFirstNonLoopbackHostInfo().getHostname());
}
}
@Test
public void instanceIdIsIpWhenIpPreferred() throws Exception {
InstanceInfo instanceInfo = setupInstance("eureka.instance.preferIpAddress:true");
assertTrue(instanceInfo.getId().matches("(\\d+\\.){3}\\d+"));
assertThat(instanceInfo.getId().matches("(\\d+\\.){3}\\d+")).isTrue();
}
@Test
public void instanceInfoIdIsInstanceIdWhenSet() {
InstanceInfo instanceInfo = setupInstance("eureka.instance.instanceId:special");
assertEquals("special", instanceInfo.getId());
assertThat(instanceInfo.getId()).isEqualTo("special");
}
private InstanceInfo setupInstance(String... pairs) {
@@ -76,9 +75,12 @@ public class InstanceInfoFactoryTests {
@Configuration
@EnableConfigurationProperties
protected static class TestConfiguration {
@Bean
public EurekaInstanceConfigBean eurekaInstanceConfigBean() {
return new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties()));
}
}
}
@@ -1,25 +1,25 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* * Copyright 2013-2016 the original author or authors.
* *
* * 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.
* 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 org.springframework.cloud.netflix.eureka.config;
import com.netflix.discovery.EurekaClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.context.scope.refresh.RefreshScopeRefreshedEvent;
@@ -27,8 +27,6 @@ import org.springframework.cloud.netflix.eureka.sample.RefreshEurekaSampleApplic
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.test.context.junit4.SpringRunner;
import com.netflix.discovery.EurekaClient;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@@ -48,9 +46,12 @@ public class ConfigRefreshTests {
private EurekaClient client;
@Test
// This test is used to verify that getApplications is called the correct number of times
// when a refresh event is fired. The getApplications call in EurekaClientConfigurationRefresher.onApplicationEvent
// ensures that the EurekaClient bean is recreated after a refresh event and that we reregister the client with
// This test is used to verify that getApplications is called the correct number of
// times
// when a refresh event is fired. The getApplications call in
// EurekaClientConfigurationRefresher.onApplicationEvent
// ensures that the EurekaClient bean is recreated after a refresh event and that we
// reregister the client with
// the server
public void verifyGetApplications() {
if (publisher != null) {
@@ -58,4 +59,5 @@ public class ConfigRefreshTests {
}
verify(client, times(3)).getApplications();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,16 +12,19 @@
* 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 org.springframework.cloud.netflix.eureka.config;
import java.util.Arrays;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import org.junit.After;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.test.util.TestPropertyValues;
import org.springframework.cloud.commons.util.UtilAutoConfiguration;
@@ -34,11 +37,7 @@ import org.springframework.context.annotation.AnnotationConfigApplicationContext
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
import static org.springframework.cloud.config.client.ConfigClientProperties.Discovery.DEFAULT_CONFIG_SERVER;
@@ -65,18 +64,19 @@ public class DiscoveryClientConfigServiceAutoConfigurationTests {
setup("spring.cloud.config.discovery.enabled=true",
"eureka.instance.metadataMap.foo:bar",
"eureka.instance.nonSecurePort:7001", "eureka.instance.hostname:foo");
assertEquals(1, this.context.getBeanNamesForType(
EurekaDiscoveryClientConfigServiceAutoConfiguration.class).length);
assertThat(this.context.getBeanNamesForType(
EurekaDiscoveryClientConfigServiceAutoConfiguration.class).length)
.isEqualTo(1);
EurekaClient eurekaClient = this.context.getParent().getBean(EurekaClient.class);
Mockito.verify(eurekaClient, times(2)).getInstancesByVipAddress(DEFAULT_CONFIG_SERVER,
false);
Mockito.verify(eurekaClient, times(2))
.getInstancesByVipAddress(DEFAULT_CONFIG_SERVER, false);
Mockito.verify(eurekaClient, times(1)).shutdown();
ConfigClientProperties locator = this.context
.getBean(ConfigClientProperties.class);
assertEquals("http://foo:7001/", locator.getUri()[0]);
assertThat(locator.getUri()[0]).isEqualTo("http://foo:7001/");
ApplicationInfoManager infoManager = this.context
.getBean(ApplicationInfoManager.class);
assertEquals("bar", infoManager.getInfo().getMetadata().get("foo"));
assertThat(infoManager.getInfo().getMetadata().get("foo")).isEqualTo("bar");
}
private void setup(String... env) {
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,15 +16,15 @@
package org.springframework.cloud.netflix.eureka.config;
import com.netflix.appinfo.EurekaInstanceConfig;
import org.junit.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.cloud.config.server.config.ConfigServerProperties;
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
import com.netflix.appinfo.EurekaInstanceConfig;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Dave Syer
@@ -37,8 +37,9 @@ public class EurekaClientConfigServerAutoConfigurationTests {
new ApplicationContextRunner().withConfiguration(
AutoConfigurations.of(EurekaClientConfigServerAutoConfiguration.class))
.run(c -> {
assertEquals(0,
c.getBeanNamesForType(EurekaInstanceConfigBean.class).length);
assertThat(
c.getBeanNamesForType(EurekaInstanceConfigBean.class).length)
.isEqualTo(0);
});
}
@@ -50,10 +51,11 @@ public class EurekaClientConfigServerAutoConfigurationTests {
ConfigServerProperties.class, EurekaInstanceConfigBean.class))
.withPropertyValues("spring.cloud.config.server.prefix=/config")
.run(c -> {
assertEquals(1,
c.getBeanNamesForType(EurekaInstanceConfig.class).length);
assertThat(c.getBeanNamesForType(EurekaInstanceConfig.class).length)
.isEqualTo(1);
EurekaInstanceConfig instance = c.getBean(EurekaInstanceConfig.class);
assertEquals("/config", instance.getMetadataMap().get("configPath"));
assertThat(instance.getMetadataMap().get("configPath"))
.isEqualTo("/config");
});
}
@@ -64,12 +66,14 @@ public class EurekaClientConfigServerAutoConfigurationTests {
EurekaClientConfigServerAutoConfiguration.class,
ConfigServerProperties.class, EurekaInstanceConfigBean.class))
.withPropertyValues("spring.cloud.config.server.prefix=/config")
.withPropertyValues("eureka.instance.metadataMap.configPath=/differentpath")
.withPropertyValues(
"eureka.instance.metadataMap.configPath=/differentpath")
.run(c -> {
assertEquals(1,
c.getBeanNamesForType(EurekaInstanceConfig.class).length);
assertThat(c.getBeanNamesForType(EurekaInstanceConfig.class).length)
.isEqualTo(1);
EurekaInstanceConfig instance = c.getBean(EurekaInstanceConfig.class);
assertEquals("/differentpath", instance.getMetadataMap().get("configPath"));
assertThat(instance.getMetadataMap().get("configPath"))
.isEqualTo("/differentpath");
});
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,9 +16,10 @@
package org.springframework.cloud.netflix.eureka.config;
import org.junit.Assert;
import com.netflix.discovery.DiscoveryClient.DiscoveryClientOptionalArgs;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
@@ -26,7 +27,7 @@ import org.springframework.cloud.netflix.eureka.sample.EurekaSampleApplication;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.netflix.discovery.DiscoveryClient.DiscoveryClientOptionalArgs;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Daniel Lavoie
@@ -35,11 +36,13 @@ import com.netflix.discovery.DiscoveryClient.DiscoveryClientOptionalArgs;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class JerseyOptionalArgsConfigurationTest {
@Autowired
private DiscoveryClientOptionalArgs optionalArgs;
@Test
public void contextLoads() {
Assert.assertNotNull(optionalArgs);
assertThat(optionalArgs).isNotNull();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,9 +16,9 @@
package org.springframework.cloud.netflix.eureka.config;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
@@ -29,6 +29,8 @@ import org.springframework.cloud.test.ClassPathExclusions;
import org.springframework.cloud.test.ModifiedClassPathRunner;
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Daniel Lavoie
*/
@@ -36,12 +38,15 @@ import org.springframework.context.ConfigurableApplicationContext;
@ClassPathExclusions({ "jersey-client-*", "jersey-core-*", "jersey-apache-client4-*" })
@SpringBootTest(classes = EurekaSampleApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
public class RestTemplateOptionalArgsConfigurationTest {
@Test
public void contextLoads() {
try (ConfigurableApplicationContext context = new SpringApplicationBuilder()
.web(WebApplicationType.NONE).sources(EurekaSampleApplication.class).run()) {
Assert.assertNotNull(
context.getBean(RestTemplateDiscoveryClientOptionalArgs.class));
.web(WebApplicationType.NONE).sources(EurekaSampleApplication.class)
.run()) {
assertThat(context.getBean(RestTemplateDiscoveryClientOptionalArgs.class))
.isNotNull();
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,11 @@
package org.springframework.cloud.netflix.eureka.healthcheck;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
@@ -29,11 +32,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests the Eureka health check handler.
@@ -55,8 +54,8 @@ public class EurekaHealthCheckTests {
InstanceInfo.InstanceStatus status = this.discoveryClient.getHealthCheckHandler()
.getStatus(InstanceInfo.InstanceStatus.UNKNOWN);
assertNotNull(status);
assertEquals(InstanceInfo.InstanceStatus.OUT_OF_SERVICE, status);
assertThat(status).isNotNull();
assertThat(status).isEqualTo(InstanceInfo.InstanceStatus.OUT_OF_SERVICE);
}
@Configuration
@@ -72,5 +71,7 @@ public class EurekaHealthCheckTests {
}
};
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -62,19 +62,14 @@ import static org.springframework.util.Assert.isTrue;
@RestController
@SpringBootApplication
public class EurekaServerMockApplication {
private static final InstanceInfo INFO = InstanceInfo.Builder.newBuilder()
.setInstanceId("app1instance1")
.setAppName("app1")
.setAppNameForDeser("app1fordeser")
.setAppGroupName("app1group")
.setAppGroupNameForDeser("app1group1fordeser")
.setHostName("app1host1")
.setInstanceId("app1instance1").setAppName("app1")
.setAppNameForDeser("app1fordeser").setAppGroupName("app1group")
.setAppGroupNameForDeser("app1group1fordeser").setHostName("app1host1")
.setStatus(InstanceInfo.InstanceStatus.UP)
.setOverriddenStatus(InstanceInfo.InstanceStatus.DOWN)
.setIPAddr("127.0.0.1")
.setSID("app1sid")
.setPort(8080)
.setSecurePort(4443)
.setOverriddenStatus(InstanceInfo.InstanceStatus.DOWN).setIPAddr("127.0.0.1")
.setSID("app1sid").setPort(8080).setSecurePort(4443)
.enablePort(InstanceInfo.PortType.UNSECURE, true)
.setHomePageUrl("/", "http://localhost/")
.setHomePageUrlForDeser("http://localhost/")
@@ -82,25 +77,20 @@ public class EurekaServerMockApplication {
.setStatusPageUrlForDeser("http://localhost/status")
.setHealthCheckUrls("/ping", "http://localhost/ping", null)
.setHealthCheckUrlsForDeser("http://localhost/ping", null)
.setVIPAddress("localhost:8080")
.setVIPAddressDeser("localhost:8080")
.setVIPAddress("localhost:8080").setVIPAddressDeser("localhost:8080")
.setSecureVIPAddress("localhost:4443")
.setSecureVIPAddressDeser("localhost:4443")
.setDataCenterInfo(new MyDataCenterInfo(DataCenterInfo.Name.MyOwn))
.setLeaseInfo(LeaseInfo.Builder.newBuilder()
.setDurationInSecs(30)
.setLeaseInfo(LeaseInfo.Builder.newBuilder().setDurationInSecs(30)
.setRenewalIntervalInSecs(30)
.setEvictionTimestamp(System.currentTimeMillis() + 30000)
.setRenewalTimestamp(System.currentTimeMillis() - 1000)
.setRegistrationTimestamp(System.currentTimeMillis()-2000)
.build())
.add("metadatakey1", "metadatavalue1")
.setASGName("asg1")
.setRegistrationTimestamp(System.currentTimeMillis() - 2000).build())
.add("metadatakey1", "metadatavalue1").setASGName("asg1")
.setIsCoordinatingDiscoveryServer(false)
.setLastUpdatedTimestamp(System.currentTimeMillis())
.setLastDirtyTimestamp(System.currentTimeMillis())
.setActionType(InstanceInfo.ActionType.ADDED)
.setNamespace("namespace1")
.setActionType(InstanceInfo.ActionType.ADDED).setNamespace("namespace1")
.build();
/**
@@ -119,7 +109,8 @@ public class EurekaServerMockApplication {
@RequestBody InstanceInfo instanceInfo) {
isTrue(instanceInfo.getPort() != DEFAULT_PORT && instanceInfo.getPort() != 0,
"Port not received from client");
isTrue(instanceInfo.getSecurePort() != DEFAULT_SECURE_PORT && instanceInfo.getSecurePort() != 0,
isTrue(instanceInfo.getSecurePort() != DEFAULT_SECURE_PORT
&& instanceInfo.getSecurePort() != 0,
"Secure Port not received from client");
// Nothing to do
}
@@ -140,9 +131,10 @@ public class EurekaServerMockApplication {
if ("fourOFour".equals(appName)) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<InstanceInfo>(new InstanceInfo(null, null, null, null, null, null, null, null, null,
null, null, null, null, 0, null, null, null, null, null, null, null, new HashMap<String, String>(), 0l,
0l, null, null), HttpStatus.OK);
return new ResponseEntity<InstanceInfo>(new InstanceInfo(null, null, null, null,
null, null, null, null, null, null, null, null, null, 0, null, null, null,
null, null, null, null, new HashMap<>(), 0L, 0L, null, null),
HttpStatus.OK);
}
@ResponseStatus(HttpStatus.OK)
@@ -160,20 +152,21 @@ public class EurekaServerMockApplication {
}
@GetMapping(value = { "/apps", "/apps/delta", "/vips/{address}", "/svips/{address}" })
@GetMapping({ "/apps", "/apps/delta", "/vips/{address}", "/svips/{address}" })
public Applications getApplications(@PathVariable(required = false) String address,
@RequestParam(required = false) String regions) {
Applications applications = new Applications();
applications.addApplication(new Application("app1", Collections.singletonList(INFO)));
applications
.addApplication(new Application("app1", Collections.singletonList(INFO)));
return applications;
}
@GetMapping(value = "/apps/{appName}")
@GetMapping("/apps/{appName}")
public Application getApplication(@PathVariable String appName) {
return new Application();
}
@GetMapping(value = { "/apps/{appName}/{id}", "/instances/{id}" })
@GetMapping({ "/apps/{appName}/{id}", "/instances/{id}" })
public InstanceInfo getInstance(@PathVariable(required = false) String appName,
@PathVariable String id) {
return INFO;
@@ -181,8 +174,8 @@ public class EurekaServerMockApplication {
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
protected static class TestSecurityConfiguration extends WebSecurityConfigurerAdapter {
protected static class TestSecurityConfiguration
extends WebSecurityConfigurerAdapter {
TestSecurityConfiguration() {
super(true);
@@ -191,16 +184,17 @@ public class EurekaServerMockApplication {
@Bean
public UserDetailsService userDetailsService() {
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("test").password("{noop}test").roles("USER").build());
manager.createUser(User.withUsername("test").password("{noop}test")
.roles("USER").build());
return manager;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
// super.configure(http);
http.antMatcher("/apps/**")
.httpBasic();
http.antMatcher("/apps/**").httpBasic();
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,16 @@
package org.springframework.cloud.netflix.eureka.http;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider;
import com.netflix.discovery.shared.Applications;
import org.junit.Assert;
import com.netflix.discovery.shared.resolver.DefaultEndpoint;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
@@ -31,11 +36,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.appinfo.InstanceInfo.InstanceStatus;
import com.netflix.appinfo.providers.EurekaConfigBasedInstanceInfoProvider;
import com.netflix.discovery.shared.resolver.DefaultEndpoint;
import com.netflix.discovery.shared.transport.EurekaHttpClient;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Daniel Lavoie
@@ -45,6 +46,7 @@ import com.netflix.discovery.shared.transport.EurekaHttpClient;
"security.basic.enabled=true" }, webEnvironment = WebEnvironment.RANDOM_PORT)
@DirtiesContext
public class RestTemplateEurekaHttpClientTest {
@Autowired
private InetUtils inetUtils;
@@ -52,6 +54,7 @@ public class RestTemplateEurekaHttpClientTest {
private String serviceUrl;
private EurekaHttpClient eurekaHttpClient;
private InstanceInfo info;
@Before
@@ -76,45 +79,45 @@ public class RestTemplateEurekaHttpClientTest {
@Test
public void testRegister() {
Assert.assertEquals(HttpStatus.OK.value(),
eurekaHttpClient.register(info).getStatusCode());
assertThat(eurekaHttpClient.register(info).getStatusCode())
.isEqualTo(HttpStatus.OK.value());
}
@Test
public void testCancel() {
Assert.assertEquals(HttpStatus.OK.value(),
eurekaHttpClient.cancel("test", "test").getStatusCode());
assertThat(eurekaHttpClient.cancel("test", "test").getStatusCode())
.isEqualTo(HttpStatus.OK.value());
}
@Test
public void testSendHeartBeat() {
Assert.assertEquals(HttpStatus.OK.value(), eurekaHttpClient
.sendHeartBeat("test", "test", info, null).getStatusCode());
assertThat(eurekaHttpClient.sendHeartBeat("test", "test", info, null)
.getStatusCode()).isEqualTo(HttpStatus.OK.value());
}
@Test
public void testSendHeartBeatFourOFour() {
Assert.assertEquals(HttpStatus.NOT_FOUND.value(), eurekaHttpClient
.sendHeartBeat("fourOFour", "test", info, null).getStatusCode());
assertThat(eurekaHttpClient.sendHeartBeat("fourOFour", "test", info, null)
.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND.value());
}
@Test
public void testStatusUpdate() {
Assert.assertEquals(HttpStatus.OK.value(), eurekaHttpClient
.statusUpdate("test", "test", InstanceStatus.UP, info).getStatusCode());
assertThat(eurekaHttpClient.statusUpdate("test", "test", InstanceStatus.UP, info)
.getStatusCode()).isEqualTo(HttpStatus.OK.value());
}
@Test
public void testDeleteStatusOverride() {
Assert.assertEquals(HttpStatus.OK.value(), eurekaHttpClient
.deleteStatusOverride("test", "test", info).getStatusCode());
assertThat(eurekaHttpClient.deleteStatusOverride("test", "test", info)
.getStatusCode()).isEqualTo(HttpStatus.OK.value());
}
@Test
public void testGetApplications() {
Applications entity = eurekaHttpClient.getApplications().getEntity();
Assert.assertNotNull(entity);
Assert.assertNotNull(eurekaHttpClient.getApplications("us", "eu").getEntity());
assertThat(entity).isNotNull();
assertThat(eurekaHttpClient.getApplications("us", "eu").getEntity()).isNotNull();
}
@Test
@@ -145,4 +148,5 @@ public class RestTemplateEurekaHttpClientTest {
eurekaHttpClient.getInstance("test");
eurekaHttpClient.getInstance("test", "test");
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,8 +22,10 @@ import org.junit.Test;
* @author Daniel Lavoie
*/
public class RestTemplateTransportClientFactoriesTest {
@Test(expected = UnsupportedOperationException.class)
public void testJerseyIsUnsuported() {
new RestTemplateTransportClientFactories().newTransportClientFactory(null, null);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,16 +16,16 @@
package org.springframework.cloud.netflix.eureka.http;
import com.netflix.discovery.shared.resolver.DefaultEndpoint;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.netflix.discovery.shared.resolver.DefaultEndpoint;
/**
* @author Daniel Lavoie
*/
public class RestTemplateTransportClientFactoryTest {
private RestTemplateTransportClientFactory transportClientFatory;
@Before
@@ -54,4 +54,5 @@ public class RestTemplateTransportClientFactoryTest {
public void shutdown() {
transportClientFatory.shutdown();
}
}
@@ -1,7 +1,24 @@
/*
* Copyright 2017-2019 the original author or authors.
*
* 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 org.springframework.cloud.netflix.eureka.metadata;
import org.junit.Before;
import org.junit.Test;
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
import static org.assertj.core.api.Assertions.assertThat;
@@ -11,7 +28,9 @@ import static org.mockito.Mockito.when;
public class DefaultManagementMetadataProviderTest {
private static final EurekaInstanceConfigBean INSTANCE = mock(EurekaInstanceConfigBean.class);
private static final EurekaInstanceConfigBean INSTANCE = mock(
EurekaInstanceConfigBean.class);
private final ManagementMetadataProvider provider = new DefaultManagementMetadataProvider();
@Before
@@ -28,7 +47,8 @@ public class DefaultManagementMetadataProviderTest {
String serverContextPath = "/";
String managementContextPath = null;
Integer managementPort = null;
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort);
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath,
managementContextPath, managementPort);
assertThat(actual).isNull();
}
@@ -39,7 +59,8 @@ public class DefaultManagementMetadataProviderTest {
String serverContextPath = "/";
String managementContextPath = null;
Integer managementPort = 0;
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort);
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath,
managementContextPath, managementPort);
assertThat(actual).isNull();
}
@@ -50,7 +71,8 @@ public class DefaultManagementMetadataProviderTest {
String serverContextPath = "/";
String managementContextPath = null;
Integer managementPort = null;
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort);
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath,
managementContextPath, managementPort);
assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/health");
assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty();
@@ -64,7 +86,8 @@ public class DefaultManagementMetadataProviderTest {
String serverContextPath = "/";
String managementContextPath = null;
Integer managementPort = 8888;
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort);
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath,
managementContextPath, managementPort);
assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/health");
assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty();
@@ -78,7 +101,8 @@ public class DefaultManagementMetadataProviderTest {
String serverContextPath = "/Server";
String managementContextPath = null;
Integer managementPort = 8888;
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort);
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath,
managementContextPath, managementPort);
assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/health");
assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty();
@@ -87,16 +111,20 @@ public class DefaultManagementMetadataProviderTest {
}
@Test
public void serverPortManagementPortServerContextPathManagementContextPath() throws Exception {
public void serverPortManagementPortServerContextPathManagementContextPath()
throws Exception {
int serverPort = 7777;
String serverContextPath = "/Server";
String managementContextPath = "/Management";
Integer managementPort = 8888;
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort);
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath,
managementContextPath, managementPort);
assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/Management/health");
assertThat(actual.getHealthCheckUrl())
.isEqualTo("http://host:8888/Management/health");
assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty();
assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/Management/info");
assertThat(actual.getStatusPageUrl())
.isEqualTo("http://host:8888/Management/info");
assertThat(actual.getManagementPort()).isEqualTo(8888);
}
@@ -106,11 +134,14 @@ public class DefaultManagementMetadataProviderTest {
String serverContextPath = "/Server";
String managementContextPath = "/Management";
Integer managementPort = null;
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort);
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath,
managementContextPath, managementPort);
assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/Server/Management/health");
assertThat(actual.getHealthCheckUrl())
.isEqualTo("http://host:7777/Server/Management/health");
assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty();
assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/Server/Management/info");
assertThat(actual.getStatusPageUrl())
.isEqualTo("http://host:7777/Server/Management/info");
assertThat(actual.getManagementPort()).isEqualTo(7777);
}
@@ -120,11 +151,14 @@ public class DefaultManagementMetadataProviderTest {
String serverContextPath = "/";
String managementContextPath = "/Management";
Integer managementPort = null;
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort);
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath,
managementContextPath, managementPort);
assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/Management/health");
assertThat(actual.getHealthCheckUrl())
.isEqualTo("http://host:7777/Management/health");
assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty();
assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/Management/info");
assertThat(actual.getStatusPageUrl())
.isEqualTo("http://host:7777/Management/info");
assertThat(actual.getManagementPort()).isEqualTo(7777);
}
@@ -134,9 +168,11 @@ public class DefaultManagementMetadataProviderTest {
String serverContextPath = "/Server";
String managementContextPath = null;
Integer managementPort = null;
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort);
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath,
managementContextPath, managementPort);
assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:7777/Server/health");
assertThat(actual.getHealthCheckUrl())
.isEqualTo("http://host:7777/Server/health");
assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty();
assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:7777/Server/info");
assertThat(actual.getManagementPort()).isEqualTo(7777);
@@ -148,11 +184,14 @@ public class DefaultManagementMetadataProviderTest {
String serverContextPath = "/";
String managementContextPath = "/Management";
Integer managementPort = 8888;
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort);
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath,
managementContextPath, managementPort);
assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/Management/health");
assertThat(actual.getHealthCheckUrl())
.isEqualTo("http://host:8888/Management/health");
assertThat(actual.getSecureHealthCheckUrl()).isNullOrEmpty();
assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/Management/info");
assertThat(actual.getStatusPageUrl())
.isEqualTo("http://host:8888/Management/info");
assertThat(actual.getManagementPort()).isEqualTo(8888);
}
@@ -164,14 +203,16 @@ public class DefaultManagementMetadataProviderTest {
String managementContextPath = "/Management";
Integer managementPort = 8888;
doReturn(true).when(INSTANCE).isSecurePortEnabled();
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath, managementContextPath, managementPort);
ManagementMetadata actual = provider.get(INSTANCE, serverPort, serverContextPath,
managementContextPath, managementPort);
assertThat(actual.getHealthCheckUrl()).isEqualTo("http://host:8888/Management/health");
assertThat(actual.getSecureHealthCheckUrl()).isEqualTo("https://host:8888/Management/health");
assertThat(actual.getStatusPageUrl()).isEqualTo("http://host:8888/Management/info");
assertThat(actual.getHealthCheckUrl())
.isEqualTo("http://host:8888/Management/health");
assertThat(actual.getSecureHealthCheckUrl())
.isEqualTo("https://host:8888/Management/health");
assertThat(actual.getStatusPageUrl())
.isEqualTo("http://host:8888/Management/info");
assertThat(actual.getManagementPort()).isEqualTo(8888);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package org.springframework.cloud.netflix.eureka.sample;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.annotation.DirtiesContext;
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,9 @@ package org.springframework.cloud.netflix.eureka.sample;
import java.io.Closeable;
import java.io.IOException;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@@ -36,9 +39,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.netflix.appinfo.HealthCheckHandler;
import com.netflix.appinfo.InstanceInfo;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
@Configuration
@@ -97,8 +97,7 @@ public class EurekaSampleApplication implements ApplicationContextAware, Closeab
config.setInstanceId("127.0.0.1:customapp:4444");
this.registration = EurekaRegistration.builder(config)
.with(this.clientConfig, this.context)
.build();
.with(this.clientConfig, this.context).build();
this.serviceRegistry.register(this.registration);
return config.getInstanceId();
@@ -114,4 +113,5 @@ public class EurekaSampleApplication implements ApplicationContextAware, Closeab
public void close() throws IOException {
deregister();
}
}
@@ -1,23 +1,23 @@
/*
* Copyright 2017-2019 the original author or authors.
*
* * Copyright 2013-2016 the original author or authors.
* *
* * 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.
* 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 org.springframework.cloud.netflix.eureka.sample;
import com.netflix.discovery.EurekaClient;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.netflix.eureka.CloudEurekaClient;
import org.springframework.context.annotation.Bean;
@@ -25,8 +25,6 @@ import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import com.netflix.discovery.EurekaClient;
import static org.mockito.Mockito.mock;
/**
@@ -42,4 +40,5 @@ public class RefreshEurekaSampleApplication {
public EurekaClient getClient() {
return mock(CloudEurekaClient.class);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2018 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,14 +12,16 @@
* 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 org.springframework.cloud.netflix.eureka.serviceregistry;
import java.util.Map;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import org.junit.Test;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import org.springframework.cloud.netflix.eureka.CloudEurekaClient;
@@ -27,9 +29,6 @@ import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean;
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
import org.springframework.context.ApplicationEventPublisher;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import static com.netflix.appinfo.InstanceInfo.InstanceStatus.DOWN;
import static com.netflix.appinfo.InstanceInfo.InstanceStatus.OUT_OF_SERVICE;
import static com.netflix.appinfo.InstanceInfo.InstanceStatus.UNKNOWN;
@@ -49,13 +48,15 @@ public class EurekaServiceRegistryTests {
EurekaServiceRegistry registry = new EurekaServiceRegistry();
CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class);
ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class);
ApplicationInfoManager applicationInfoManager = mock(
ApplicationInfoManager.class);
when(applicationInfoManager.getInfo()).thenReturn(mock(InstanceInfo.class));
EurekaRegistration registration = EurekaRegistration.builder(new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties())))
.with(eurekaClient)
.with(applicationInfoManager)
EurekaRegistration registration = EurekaRegistration
.builder(new EurekaInstanceConfigBean(
new InetUtils(new InetUtilsProperties())))
.with(eurekaClient).with(applicationInfoManager)
.with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class))
.build();
@@ -68,33 +69,28 @@ public class EurekaServiceRegistryTests {
public void eurekaClientGetStatus() {
EurekaServiceRegistry registry = new EurekaServiceRegistry();
EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties()));
EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(
new InetUtils(new InetUtilsProperties()));
config.setAppname("myapp");
config.setInstanceId("1234");
InstanceInfo local = InstanceInfo.Builder.newBuilder()
.setAppName("myapp")
.setInstanceId("1234")
.setStatus(DOWN)
.build();
InstanceInfo local = InstanceInfo.Builder.newBuilder().setAppName("myapp")
.setInstanceId("1234").setStatus(DOWN).build();
InstanceInfo remote = InstanceInfo.Builder.newBuilder()
.setAppName("myapp")
.setInstanceId("1234")
.setStatus(DOWN)
.setOverriddenStatus(OUT_OF_SERVICE)
InstanceInfo remote = InstanceInfo.Builder.newBuilder().setAppName("myapp")
.setInstanceId("1234").setStatus(DOWN).setOverriddenStatus(OUT_OF_SERVICE)
.build();
CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class);
when(eurekaClient.getInstanceInfo(local.getAppName(), local.getId()))
.thenReturn(remote);
ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class);
ApplicationInfoManager applicationInfoManager = mock(
ApplicationInfoManager.class);
when(applicationInfoManager.getInfo()).thenReturn(local);
EurekaRegistration registration = EurekaRegistration.builder(config)
.with(eurekaClient)
.with(applicationInfoManager)
.with(eurekaClient).with(applicationInfoManager)
.with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class))
.build();
@@ -106,31 +102,29 @@ public class EurekaServiceRegistryTests {
Map<Object, Object> map = (Map<Object, Object>) status;
assertThat(map).hasSize(2)
.containsEntry("status", DOWN.toString())
assertThat(map).hasSize(2).containsEntry("status", DOWN.toString())
.containsEntry("overriddenStatus", OUT_OF_SERVICE.toString());
}
@Test
public void eurekaClientGetStatusNoInstance() {
EurekaServiceRegistry registry = new EurekaServiceRegistry();
EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(new InetUtils(new InetUtilsProperties()));
EurekaInstanceConfigBean config = new EurekaInstanceConfigBean(
new InetUtils(new InetUtilsProperties()));
config.setAppname("myapp");
config.setInstanceId("1234");
CloudEurekaClient eurekaClient = mock(CloudEurekaClient.class);
when(eurekaClient.getInstanceInfo("myapp", "1234"))
.thenReturn(null);
when(eurekaClient.getInstanceInfo("myapp", "1234")).thenReturn(null);
ApplicationInfoManager applicationInfoManager = mock(ApplicationInfoManager.class);
ApplicationInfoManager applicationInfoManager = mock(
ApplicationInfoManager.class);
when(applicationInfoManager.getInfo()).thenReturn(mock(InstanceInfo.class));
EurekaRegistration registration = EurekaRegistration.builder(config)
.with(eurekaClient)
.with(applicationInfoManager)
.with(eurekaClient).with(applicationInfoManager)
.with(new EurekaClientConfigBean(), mock(ApplicationEventPublisher.class))
.build();
@@ -142,7 +136,7 @@ public class EurekaServiceRegistryTests {
Map<Object, Object> map = (Map<Object, Object>) status;
assertThat(map).hasSize(1)
.containsEntry("status", UNKNOWN.toString());
assertThat(map).hasSize(1).containsEntry("status", UNKNOWN.toString());
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,18 +22,15 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.client.config.CommonClientConfigKey;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ServerList;
import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
@@ -52,18 +49,19 @@ public class DomainExtractingServerListTests {
static final String INSTANCE_ID = "myInstanceId";
private Map<String, String> metadata = Collections.<String, String> singletonMap(
"instanceId", INSTANCE_ID);
private Map<String, String> metadata = Collections
.<String, String>singletonMap("instanceId", INSTANCE_ID);
@Test
public void testDomainExtractingServer() {
DomainExtractingServerList serverList = getDomainExtractingServerList(
new DefaultClientConfigImpl(), true);
List<DiscoveryEnabledServer> servers = serverList.getInitialListOfServers();
assertNotNull("servers was null", servers);
assertEquals("servers was not size 1", 1, servers.size());
assertThat(servers).as("servers was null").isNotNull();
assertThat(servers.size()).as("servers was not size 1").isEqualTo(1);
DomainExtractingServer des = assertDomainExtractingServer(servers, ZONE);
assertEquals("hostPort was wrong", HOST_NAME + ":" + PORT, des.getHostPort());
assertThat(des.getHostPort()).as("hostPort was wrong")
.isEqualTo(HOST_NAME + ":" + PORT);
}
@Test
@@ -74,10 +72,10 @@ public class DomainExtractingServerListTests {
DomainExtractingServerList serverList = getDomainExtractingServerList(
new DefaultClientConfigImpl(), false);
List<DiscoveryEnabledServer> servers = serverList.getInitialListOfServers();
assertNotNull("servers was null", servers);
assertEquals("servers was not size 1", 1, servers.size());
assertThat(servers).as("servers was null").isNotNull();
assertThat(servers.size()).as("servers was not size 1").isEqualTo(1);
DomainExtractingServer des = assertDomainExtractingServer(servers, "us-west-1");
assertEquals("Zone was wrong", "us-west-1", des.getZone());
assertThat(des.getZone()).as("Zone was wrong").isEqualTo("us-west-1");
}
@Test
@@ -85,20 +83,22 @@ public class DomainExtractingServerListTests {
DomainExtractingServerList serverList = getDomainExtractingServerList(
new DefaultClientConfigImpl(), false);
List<DiscoveryEnabledServer> servers = serverList.getInitialListOfServers();
assertNotNull("servers was null", servers);
assertEquals("servers was not size 1", 1, servers.size());
assertThat(servers).as("servers was null").isNotNull();
assertThat(servers.size()).as("servers was not size 1").isEqualTo(1);
DomainExtractingServer des = assertDomainExtractingServer(servers, null);
assertEquals("hostPort was wrong", HOST_NAME + ":" + PORT, des.getHostPort());
assertThat(des.getHostPort()).as("hostPort was wrong")
.isEqualTo(HOST_NAME + ":" + PORT);
}
protected DomainExtractingServer assertDomainExtractingServer(
List<DiscoveryEnabledServer> servers, String zone) {
Server actualServer = servers.get(0);
assertTrue("server was not a DomainExtractingServer",
actualServer instanceof DomainExtractingServer);
assertThat(actualServer instanceof DomainExtractingServer)
.as("server was not a DomainExtractingServer").isTrue();
DomainExtractingServer des = DomainExtractingServer.class.cast(actualServer);
assertEquals("zone was wrong", zone, des.getZone());
assertEquals("instanceId was wrong", HOST_NAME + ":" + INSTANCE_ID, des.getId());
assertThat(des.getZone()).as("zone was wrong").isEqualTo(zone);
assertThat(des.getId()).as("instanceId was wrong")
.isEqualTo(HOST_NAME + ":" + INSTANCE_ID);
return des;
}
@@ -109,10 +109,11 @@ public class DomainExtractingServerListTests {
DomainExtractingServerList serverList = getDomainExtractingServerList(config,
true);
List<DiscoveryEnabledServer> servers = serverList.getInitialListOfServers();
assertNotNull("servers was null", servers);
assertEquals("servers was not size 1", 1, servers.size());
assertThat(servers).as("servers was null").isNotNull();
assertThat(servers.size()).as("servers was not size 1").isEqualTo(1);
DomainExtractingServer des = assertDomainExtractingServer(servers, ZONE);
assertEquals("hostPort was wrong", IP_ADDR + ":" + PORT, des.getHostPort());
assertThat(des.getHostPort()).as("hostPort was wrong")
.isEqualTo(IP_ADDR + ":" + PORT);
}
protected DomainExtractingServerList getDomainExtractingServerList(
@@ -127,8 +128,8 @@ public class DomainExtractingServerListTests {
given(instanceInfo.getHostName()).willReturn(HOST_NAME);
given(instanceInfo.getIPAddr()).willReturn(IP_ADDR);
given(instanceInfo.getPort()).willReturn(PORT);
given(originalServerList.getInitialListOfServers()).willReturn(
Arrays.asList(server));
given(originalServerList.getInitialListOfServers())
.willReturn(Arrays.asList(server));
return new DomainExtractingServerList(originalServerList, config,
approximateZoneFromHostname);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +22,7 @@ import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import com.netflix.niws.loadbalancer.NIWSDiscoveryPing;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@@ -42,7 +43,7 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Ribbon Eureka client should be disabled if Eureka client is not enabled
* Ribbon Eureka client should be disabled if Eureka client is not enabled.
*
* @author Biju Kunjummen
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,26 +16,24 @@
package org.springframework.cloud.netflix.ribbon.eureka;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean;
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import com.netflix.config.ConfigurationManager;
import com.netflix.config.DeploymentContext.ContextKey;
import com.netflix.config.DynamicStringProperty;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.cloud.commons.util.InetUtilsProperties;
import org.springframework.cloud.netflix.eureka.EurekaClientConfigBean;
import org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean;
import org.springframework.cloud.netflix.ribbon.SpringClientFactory;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.cloud.netflix.ribbon.RibbonUtils.VALUE_NOT_SET;
import static org.springframework.cloud.netflix.ribbon.RibbonUtils.getProperty;
import static org.springframework.cloud.netflix.ribbon.RibbonUtils.getRibbonKey;
@@ -64,12 +62,13 @@ public class EurekaRibbonClientConfigurationTests {
client, "service", configBean, false);
clientPreprocessor.preprocess();
ILoadBalancer balancer = clientFactory.getLoadBalancer("service");
assertNotNull(balancer);
assertThat(balancer).isNotNull();
@SuppressWarnings("unchecked")
ZoneAwareLoadBalancer<DiscoveryEnabledServer> aware = (ZoneAwareLoadBalancer<DiscoveryEnabledServer>) balancer;
assertTrue(aware.getServerListImpl() instanceof DomainExtractingServerList);
assertEquals("foo",
ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone));
assertThat(aware.getServerListImpl() instanceof DomainExtractingServerList)
.isTrue();
assertThat(ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone))
.isEqualTo("foo");
}
private EurekaInstanceConfigBean getEurekaInstanceConfigBean() {
@@ -86,12 +85,12 @@ public class EurekaRibbonClientConfigurationTests {
String suffix = "mySuffix";
String value = "myValue";
DynamicStringProperty property = getProperty(getRibbonKey(serviceId, suffix));
assertEquals("property doesn't have default value", VALUE_NOT_SET,
property.get());
assertThat(property.get()).as("property doesn't have default value")
.isEqualTo(VALUE_NOT_SET);
setRibbonProperty(serviceId, suffix, value);
assertEquals("property has wrong value", value, property.get());
assertThat(property.get()).as("property has wrong value").isEqualTo(value);
setRibbonProperty(serviceId, suffix, value);
assertEquals("property has wrong value", value, property.get());
assertThat(property.get()).as("property has wrong value").isEqualTo(value);
}
@Test
@@ -102,8 +101,8 @@ public class EurekaRibbonClientConfigurationTests {
EurekaRibbonClientConfiguration preprocessor = new EurekaRibbonClientConfiguration(
client, "myService", configBean, false);
preprocessor.preprocess();
assertEquals("myZone",
ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone));
assertThat(ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone))
.isEqualTo("myZone");
}
@Test
@@ -113,8 +112,8 @@ public class EurekaRibbonClientConfigurationTests {
EurekaRibbonClientConfiguration preprocessor = new EurekaRibbonClientConfiguration(
client, "myService", configBean, false);
preprocessor.preprocess();
assertEquals("defaultZone",
ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone));
assertThat(ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone))
.isEqualTo("defaultZone");
}
@Test
@@ -125,8 +124,8 @@ public class EurekaRibbonClientConfigurationTests {
EurekaRibbonClientConfiguration preprocessor = new EurekaRibbonClientConfiguration(
client, "myService", configBean, true);
preprocessor.preprocess();
assertEquals("is.a.test.com",
ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone));
assertThat(ConfigurationManager.getDeploymentContext().getValue(ContextKey.zone))
.isEqualTo("is.a.test.com");
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,13 @@
package org.springframework.cloud.netflix.ribbon.eureka;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidanceRule;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import com.netflix.niws.loadbalancer.NIWSDiscoveryPing;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
@@ -35,11 +40,6 @@ import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidanceRule;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import com.netflix.niws.loadbalancer.NIWSDiscoveryPing;
/**
* @author Dave Syer
*/
@@ -68,13 +68,13 @@ public class EurekaRibbonClientPreprocessorIntegrationTests {
@Test
public void serverIntrospectorDefaultsToEureka() throws Exception {
EurekaServerIntrospector.class.cast(this.factory.getInstance("foo", ServerIntrospector.class));
EurekaServerIntrospector.class
.cast(this.factory.getInstance("foo", ServerIntrospector.class));
}
@SuppressWarnings("unchecked")
private ZoneAwareLoadBalancer<Server> getLoadBalancer() {
return (ZoneAwareLoadBalancer<Server>) this.factory
.getLoadBalancer("foo");
return (ZoneAwareLoadBalancer<Server>) this.factory.getLoadBalancer("foo");
}
@Configuration
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,8 +16,15 @@
package org.springframework.cloud.netflix.ribbon.eureka;
import com.netflix.discovery.EurekaClient;
import com.netflix.loadbalancer.ConfigurationBasedServerList;
import com.netflix.loadbalancer.DummyPing;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import com.netflix.niws.loadbalancer.NIWSDiscoveryPing;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
@@ -32,13 +39,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;
import com.netflix.discovery.EurekaClient;
import com.netflix.loadbalancer.ConfigurationBasedServerList;
import com.netflix.loadbalancer.DummyPing;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import com.netflix.niws.loadbalancer.NIWSDiscoveryPing;
import static org.mockito.Mockito.mock;
/**
@@ -72,13 +72,16 @@ public class EurekaRibbonClientPropertyOverrideIntegrationTests {
@Configuration
@RibbonClients
@ImportAutoConfiguration({ UtilAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class,
ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class,
RibbonEurekaAutoConfiguration.class })
@ImportAutoConfiguration({ UtilAutoConfiguration.class,
PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class,
RibbonAutoConfiguration.class, RibbonEurekaAutoConfiguration.class })
protected static class TestConfiguration {
@Bean
public EurekaClient eurekaClient() {
return mock(EurekaClient.class);
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,9 +16,14 @@
package org.springframework.cloud.netflix.ribbon.eureka;
import com.netflix.discovery.EurekaClient;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidanceRule;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
@@ -37,12 +42,7 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.netflix.discovery.EurekaClient;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidanceRule;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import static org.junit.Assert.assertEquals;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Dave Syer
@@ -76,9 +76,8 @@ public class RibbonClientPreprocessorIntegrationTests {
@SuppressWarnings("unchecked")
ZoneAwareLoadBalancer<Server> loadBalancer = (ZoneAwareLoadBalancer<Server>) this.factory
.getLoadBalancer("foo");
assertEquals("myTestZone",
ZonePreferenceServerListFilter.class.cast(loadBalancer.getFilter())
.getZone());
assertThat(ZonePreferenceServerListFilter.class.cast(loadBalancer.getFilter())
.getZone()).isEqualTo("myTestZone");
}
@Configuration
@@ -86,6 +85,7 @@ public class RibbonClientPreprocessorIntegrationTests {
@ImportAutoConfiguration({ PropertyPlaceholderAutoConfiguration.class,
ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class })
protected static class PlainConfiguration {
}
@Configuration
@@ -94,14 +94,17 @@ public class RibbonClientPreprocessorIntegrationTests {
ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class,
RibbonEurekaAutoConfiguration.class })
protected static class TestConfiguration {
@Bean
EurekaClient eurekaClient() {
return Mockito.mock(EurekaClient.class);
}
}
@Configuration
protected static class FooConfiguration {
@Bean
public ZonePreferenceServerListFilter serverListFilter() {
ZonePreferenceServerListFilter filter = new ZonePreferenceServerListFilter();
@@ -111,10 +114,11 @@ public class RibbonClientPreprocessorIntegrationTests {
@Bean
public EurekaInstanceConfigBean getEurekaInstanceConfigBean() {
EurekaInstanceConfigBean bean = new EurekaInstanceConfigBean(new InetUtils(
new InetUtilsProperties()));
EurekaInstanceConfigBean bean = new EurekaInstanceConfigBean(
new InetUtils(new InetUtilsProperties()));
return bean;
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2016-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.ribbon.eureka;
@@ -21,6 +20,7 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringBootConfiguration;
@@ -39,9 +39,9 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
* @author Spencer Gibb
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RibbonEurekaAutoConfigurationTests.EurekaClientDisabledApp.class,
properties = { "eureka.client.enabled=false", "spring.application.name=eurekadisabledtest" },
webEnvironment = RANDOM_PORT)
@SpringBootTest(classes = RibbonEurekaAutoConfigurationTests.EurekaClientDisabledApp.class, properties = {
"eureka.client.enabled=false",
"spring.application.name=eurekadisabledtest" }, webEnvironment = RANDOM_PORT)
@DirtiesContext
public class RibbonEurekaAutoConfigurationTests {
@@ -58,12 +58,14 @@ public class RibbonEurekaAutoConfigurationTests {
public static class EurekaClientDisabledApp {
@Bean
public TestLoadbalancerClient testLoadbalanceClient(LoadBalancerClient loadBalancerClient) {
public TestLoadbalancerClient testLoadbalanceClient(
LoadBalancerClient loadBalancerClient) {
return new TestLoadbalancerClient(loadBalancerClient);
}
@Bean
public CommandLineRunner commandLineRunner(final TestLoadbalancerClient testLoadbalancerClient) {
public CommandLineRunner commandLineRunner(
final TestLoadbalancerClient testLoadbalancerClient) {
return new CommandLineRunner() {
@Override
public void run(String... args) throws Exception {
@@ -71,6 +73,7 @@ public class RibbonEurekaAutoConfigurationTests {
}
};
}
}
private static class TestLoadbalancerClient {
@@ -78,22 +81,27 @@ public class RibbonEurekaAutoConfigurationTests {
Log log = LogFactory.getLog(this.getClass());
private LoadBalancerClient loadBalancerClient;
private boolean instanceFound = false;
public TestLoadbalancerClient(LoadBalancerClient loadBalancerClient) {
TestLoadbalancerClient(LoadBalancerClient loadBalancerClient) {
this.loadBalancerClient = loadBalancerClient;
}
public void doStuff() {
ServiceInstance serviceInstance = loadBalancerClient.choose("http://host/doStuff");
ServiceInstance serviceInstance = loadBalancerClient
.choose("http://host/doStuff");
if (serviceInstance != null) {
log.info("There is a service instance, because Eureka discovery is enabled and the service is registered");
log.info(
"There is a service instance, because Eureka discovery is enabled and the service is registered");
instanceFound = true;
}
else {
log.warn("No instance found, because Eureka is disabled or there is no service matching.");
}
log.warn(
"No instance found, because Eureka is disabled or there is no service matching.");
}
}
}
}
@@ -1,4 +1,5 @@
/* Copyright 2013-2015 the original author or authors.
/*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,14 +13,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.netflix.ribbon.eureka;
import static org.junit.Assert.assertTrue;
package org.springframework.cloud.netflix.ribbon.eureka;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
*
* @author Ryan Baxter
*
*/
@@ -27,9 +28,11 @@ public class ZoneUtilsTests {
@Test
public void extractApproximateZoneTest() {
assertTrue("foo".equals(ZoneUtils.extractApproximateZone("foo")));
assertTrue("bar".equals(ZoneUtils.extractApproximateZone("foo.bar")));
assertTrue("world.foo.bar".equals(ZoneUtils
.extractApproximateZone("hello.world.foo.bar")));
assertThat("foo".equals(ZoneUtils.extractApproximateZone("foo"))).isTrue();
assertThat("bar".equals(ZoneUtils.extractApproximateZone("foo.bar"))).isTrue();
assertThat("world.foo.bar"
.equals(ZoneUtils.extractApproximateZone("hello.world.foo.bar")))
.isTrue();
}
}
@@ -1,3 +1,19 @@
/*
* Copyright 2013-2019 the original author or authors.
*
* 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 org.springframework.cloud.netflix.eureka.server;
import java.io.IOException;
@@ -7,9 +23,6 @@ import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.function.Supplier;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
@@ -30,6 +43,9 @@ import com.netflix.discovery.converters.wrappers.CodecWrappers.LegacyJacksonJson
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Applications;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import static com.netflix.discovery.converters.wrappers.CodecWrappers.getCodecName;
/**
@@ -68,11 +84,27 @@ public class CloudJacksonJson extends LegacyJacksonJson {
return this.codec.readValue(type, inputStream);
}
static InstanceInfo updateIfNeeded(final InstanceInfo info) {
if (info.getInstanceId() == null && info.getMetadata() != null) {
String instanceId = info.getMetadata().get("instanceId");
if (StringUtils.hasText(instanceId)) {
// backwards compatibility for Angel
if (StringUtils.hasText(info.getHostName())
&& !instanceId.startsWith(info.getHostName())) {
instanceId = info.getHostName() + ":" + instanceId;
}
return new InstanceInfo.Builder(info).setInstanceId(instanceId).build();
}
}
return info;
}
static class CloudJacksonCodec extends EurekaJacksonCodec {
private static final Version VERSION = new Version(1, 1, 0, null, null, null);
@SuppressWarnings("deprecation")
public CloudJacksonCodec() {
CloudJacksonCodec() {
super();
ObjectMapper mapper = new ObjectMapper();
@@ -99,12 +131,12 @@ public class CloudJacksonJson extends LegacyJacksonJson {
mapper.registerModule(module);
HashMap<Class<?>, Supplier<ObjectReader>> readers = new HashMap<>();
readers.put(InstanceInfo.class, ()-> mapper.reader().withType(InstanceInfo.class)
.withRootName("instance"));
readers.put(Application.class, ()-> mapper.reader().withType(Application.class)
.withRootName("application"));
readers.put(Applications.class, ()-> mapper.reader().withType(Applications.class)
.withRootName("applications"));
readers.put(InstanceInfo.class, () -> mapper.reader()
.withType(InstanceInfo.class).withRootName("instance"));
readers.put(Application.class, () -> mapper.reader()
.withType(Application.class).withRootName("application"));
readers.put(Applications.class, () -> mapper.reader()
.withType(Applications.class).withRootName("applications"));
setField("objectReaderByClass", readers);
HashMap<Class<?>, ObjectWriter> writers = new HashMap<>();
@@ -124,9 +156,11 @@ public class CloudJacksonJson extends LegacyJacksonJson {
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, this, value);
}
}
static class CloudInstanceInfoSerializer extends InstanceInfoSerializer {
@Override
public void serialize(final InstanceInfo info, JsonGenerator jgen,
SerializerProvider provider) throws IOException {
@@ -134,20 +168,7 @@ public class CloudJacksonJson extends LegacyJacksonJson {
InstanceInfo updated = updateIfNeeded(info);
super.serialize(updated, jgen, provider);
}
}
static InstanceInfo updateIfNeeded(final InstanceInfo info) {
if (info.getInstanceId() == null && info.getMetadata() != null) {
String instanceId = info.getMetadata().get("instanceId");
if (StringUtils.hasText(instanceId)) {
// backwards compatibility for Angel
if (StringUtils.hasText(info.getHostName()) && !instanceId.startsWith(info.getHostName())) {
instanceId = info.getHostName()+":"+instanceId;
}
return new InstanceInfo.Builder(info).setInstanceId(instanceId).build();
}
}
return info;
}
static class CloudInstanceInfoDeserializer extends InstanceInfoDeserializer {
@@ -157,10 +178,13 @@ public class CloudJacksonJson extends LegacyJacksonJson {
}
@Override
public InstanceInfo deserialize(JsonParser jp, DeserializationContext context) throws IOException {
public InstanceInfo deserialize(JsonParser jp, DeserializationContext context)
throws IOException {
InstanceInfo info = super.deserialize(jp, context);
InstanceInfo updated = updateIfNeeded(info);
return updated;
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,7 +25,8 @@ import java.lang.annotation.Target;
import org.springframework.context.annotation.Import;
/**
* Annotation to activate Eureka Server related configuration {@link EurekaServerAutoConfiguration}
* Annotation to activate Eureka Server related configuration.
* {@link EurekaServerAutoConfiguration}
*
* @author Dave Syer
* @author Biju Kunjummen
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -27,15 +27,6 @@ import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.netflix.appinfo.AmazonInfo;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.DataCenterInfo;
@@ -43,10 +34,19 @@ import com.netflix.appinfo.InstanceInfo;
import com.netflix.config.ConfigurationManager;
import com.netflix.discovery.shared.Application;
import com.netflix.discovery.shared.Pair;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.EurekaServerContextHolder;
import com.netflix.eureka.cluster.PeerEurekaNode;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl;
import com.netflix.eureka.resources.StatusResource;
import com.netflix.eureka.util.StatusInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author Spencer Gibb
* @author Gang Li
@@ -57,6 +57,7 @@ public class EurekaController {
@Value("${eureka.dashboard.path:/}")
private String dashboardPath = "";
private ApplicationInfoManager applicationInfoManager;
public EurekaController(ApplicationInfoManager applicationInfoManager) {
@@ -109,8 +110,8 @@ public class EurekaController {
protected void populateBase(HttpServletRequest request, Map<String, Object> model) {
model.put("time", new Date());
model.put("basePath", "/");
model.put("dashboardPath", this.dashboardPath.equals("/") ? ""
: this.dashboardPath);
model.put("dashboardPath",
this.dashboardPath.equals("/") ? "" : this.dashboardPath);
populateHeader(model);
populateNavbar(request, model);
}
@@ -118,10 +119,10 @@ public class EurekaController {
private void populateHeader(Map<String, Object> model) {
model.put("currentTime", StatusResource.getCurrentTimeAsString());
model.put("upTime", StatusInfo.getUpTime());
model.put("environment", ConfigurationManager.getDeploymentContext()
.getDeploymentEnvironment());
model.put("datacenter", ConfigurationManager.getDeploymentContext()
.getDeploymentDatacenter());
model.put("environment",
ConfigurationManager.getDeploymentContext().getDeploymentEnvironment());
model.put("datacenter",
ConfigurationManager.getDeploymentContext().getDeploymentDatacenter());
PeerAwareInstanceRegistry registry = getRegistry();
model.put("registry", registry);
model.put("isBelowRenewThresold", registry.isBelowRenewThresold() == 1);
@@ -146,7 +147,8 @@ public class EurekaController {
private void populateNavbar(HttpServletRequest request, Map<String, Object> model) {
Map<String, String> replicas = new LinkedHashMap<>();
List<PeerEurekaNode> list = getServerContext().getPeerEurekaNodes().getPeerNodesView();
List<PeerEurekaNode> list = getServerContext().getPeerEurekaNodes()
.getPeerNodesView();
for (PeerEurekaNode node : list) {
try {
URI uri = new URI(node.getServiceUrl());
@@ -275,13 +277,16 @@ public class EurekaController {
protected void filterReplicas(Map<String, Object> model, StatusInfo statusInfo) {
Map<String, String> applicationStats = statusInfo.getApplicationStats();
if (applicationStats.get("registered-replicas").contains("@")) {
applicationStats.put("registered-replicas", scrubBasicAuth(applicationStats.get("registered-replicas")));
applicationStats.put("registered-replicas",
scrubBasicAuth(applicationStats.get("registered-replicas")));
}
if (applicationStats.get("unavailable-replicas").contains("@")) {
applicationStats.put("unavailable-replicas",scrubBasicAuth(applicationStats.get("unavailable-replicas")));
applicationStats.put("unavailable-replicas",
scrubBasicAuth(applicationStats.get("unavailable-replicas")));
}
if (applicationStats.get("available-replicas").contains("@")) {
applicationStats.put("available-replicas",scrubBasicAuth(applicationStats.get("available-replicas")));
applicationStats.put("available-replicas",
scrubBasicAuth(applicationStats.get("available-replicas")));
}
model.put("applicationStats", applicationStats);
}
@@ -291,11 +296,14 @@ public class EurekaController {
StringBuilder filteredUrls = new StringBuilder();
for (String u : urls) {
if (u.contains("@")) {
filteredUrls.append(u.substring(0,u.indexOf("//")+2)).append(u.substring(u.indexOf("@")+1,u.length())).append(",");
}else{
filteredUrls.append(u.substring(0, u.indexOf("//") + 2))
.append(u.substring(u.indexOf("@") + 1, u.length())).append(",");
}
else {
filteredUrls.append(u).append(",");
}
}
return filteredUrls.substring(0, filteredUrls.length() - 1);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,10 @@
package org.springframework.cloud.netflix.eureka.server;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Objects;
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Configuration properties for the Eureka dashboard (UI).
*
@@ -56,11 +56,14 @@ public class EurekaDashboardProperties {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EurekaDashboardProperties that = (EurekaDashboardProperties) o;
return enabled == that.enabled &&
Objects.equals(path, that.path);
return enabled == that.enabled && Objects.equals(path, that.path);
}
@Override
@@ -76,4 +79,5 @@ public class EurekaDashboardProperties {
sb.append('}');
return sb.toString();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2017 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,8 +24,25 @@ import java.util.Set;
import javax.servlet.Filter;
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
import javax.ws.rs.ext.Provider;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.converters.EurekaJacksonCodec;
import com.netflix.discovery.converters.wrappers.CodecWrapper;
import com.netflix.discovery.converters.wrappers.CodecWrappers;
import com.netflix.eureka.DefaultEurekaServerContext;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.cluster.PeerEurekaNodes;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.resources.DefaultServerCodecs;
import com.netflix.eureka.resources.ServerCodecs;
import com.sun.jersey.api.core.DefaultResourceConfig;
import com.sun.jersey.spi.container.servlet.ServletContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.BeanDefinition;
@@ -50,22 +67,6 @@ import org.springframework.core.type.filter.AnnotationTypeFilter;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.converters.EurekaJacksonCodec;
import com.netflix.discovery.converters.wrappers.CodecWrapper;
import com.netflix.discovery.converters.wrappers.CodecWrappers;
import com.netflix.eureka.DefaultEurekaServerContext;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.EurekaServerContext;
import com.netflix.eureka.cluster.PeerEurekaNodes;
import com.netflix.eureka.registry.PeerAwareInstanceRegistry;
import com.netflix.eureka.resources.DefaultServerCodecs;
import com.netflix.eureka.resources.ServerCodecs;
import com.sun.jersey.api.core.DefaultResourceConfig;
import com.sun.jersey.spi.container.servlet.ServletContainer;
/**
* @author Gunnar Hillert
* @author Biju Kunjummen
@@ -78,11 +79,12 @@ import com.sun.jersey.spi.container.servlet.ServletContainer;
InstanceRegistryProperties.class })
@PropertySource("classpath:/eureka/server.properties")
public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter {
/**
* List of packages containing Jersey resources required by the Eureka server
* List of packages containing Jersey resources required by the Eureka server.
*/
private static final String[] EUREKA_PACKAGES = new String[] { "com.netflix.discovery",
"com.netflix.eureka" };
private static final String[] EUREKA_PACKAGES = new String[] {
"com.netflix.discovery", "com.netflix.eureka" };
@Autowired
private ApplicationInfoManager applicationInfoManager;
@@ -99,6 +101,9 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter {
@Autowired
private InstanceRegistryProperties instanceRegistryProperties;
/**
* A {@link CloudJacksonJson} instance.
*/
public static final CloudJacksonJson JACKSON_JSON = new CloudJacksonJson();
@Bean
@@ -107,20 +112,6 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter {
EurekaServerAutoConfiguration.class);
}
@Configuration
protected static class EurekaServerConfigBeanConfiguration {
@Bean
@ConditionalOnMissingBean
public EurekaServerConfig eurekaServerConfig(EurekaClientConfig clientConfig) {
EurekaServerConfigBean server = new EurekaServerConfigBean();
if (clientConfig.shouldRegisterWithEureka()) {
// Set a sensible default if we are supposed to replicate
server.setRegistrySyncRetries(5);
}
return server;
}
}
@Bean
@ConditionalOnProperty(prefix = "eureka.dashboard", name = "enabled", matchIfMissing = true)
public EurekaController eurekaController() {
@@ -148,16 +139,6 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter {
: codec;
}
class CloudServerCodecs extends DefaultServerCodecs {
public CloudServerCodecs(EurekaServerConfig serverConfig) {
super(getFullJson(serverConfig),
CodecWrappers.getCodec(CodecWrappers.JacksonJsonMini.class),
getFullXml(serverConfig),
CodecWrappers.getCodec(CodecWrappers.JacksonXmlMini.class));
}
}
@Bean
public PeerAwareInstanceRegistry peerAwareInstanceRegistry(
ServerCodecs serverCodecs) {
@@ -176,11 +157,112 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter {
this.eurekaClientConfig, serverCodecs, this.applicationInfoManager);
}
@Bean
public EurekaServerContext eurekaServerContext(ServerCodecs serverCodecs,
PeerAwareInstanceRegistry registry, PeerEurekaNodes peerEurekaNodes) {
return new DefaultEurekaServerContext(this.eurekaServerConfig, serverCodecs,
registry, peerEurekaNodes, this.applicationInfoManager);
}
@Bean
public EurekaServerBootstrap eurekaServerBootstrap(PeerAwareInstanceRegistry registry,
EurekaServerContext serverContext) {
return new EurekaServerBootstrap(this.applicationInfoManager,
this.eurekaClientConfig, this.eurekaServerConfig, registry,
serverContext);
}
/**
* {@link PeerEurekaNodes} which updates peers when /refresh is invoked.
* Peers are updated only if
* <code>eureka.client.use-dns-for-fetching-service-urls</code> is
* Register the Jersey filter.
* @param eurekaJerseyApp an {@link Application} for the filter to be registered
* @return a jersey {@link FilterRegistrationBean}
*/
@Bean
public FilterRegistrationBean jerseyFilterRegistration(
javax.ws.rs.core.Application eurekaJerseyApp) {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new ServletContainer(eurekaJerseyApp));
bean.setOrder(Ordered.LOWEST_PRECEDENCE);
bean.setUrlPatterns(
Collections.singletonList(EurekaConstants.DEFAULT_PREFIX + "/*"));
return bean;
}
/**
* Construct a Jersey {@link javax.ws.rs.core.Application} with all the resources
* required by the Eureka server.
* @param environment an {@link Environment} instance to retrieve classpath resources
* @param resourceLoader a {@link ResourceLoader} instance to get classloader from
* @return created {@link Application} object
*/
@Bean
public javax.ws.rs.core.Application jerseyApplication(Environment environment,
ResourceLoader resourceLoader) {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
false, environment);
// Filter to include only classes that have a particular annotation.
//
provider.addIncludeFilter(new AnnotationTypeFilter(Path.class));
provider.addIncludeFilter(new AnnotationTypeFilter(Provider.class));
// Find classes in Eureka packages (or subpackages)
//
Set<Class<?>> classes = new HashSet<>();
for (String basePackage : EUREKA_PACKAGES) {
Set<BeanDefinition> beans = provider.findCandidateComponents(basePackage);
for (BeanDefinition bd : beans) {
Class<?> cls = ClassUtils.resolveClassName(bd.getBeanClassName(),
resourceLoader.getClassLoader());
classes.add(cls);
}
}
// Construct the Jersey ResourceConfig
Map<String, Object> propsAndFeatures = new HashMap<>();
propsAndFeatures.put(
// Skip static content used by the webapp
ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX,
EurekaConstants.DEFAULT_PREFIX + "/(fonts|images|css|js)/.*");
DefaultResourceConfig rc = new DefaultResourceConfig(classes);
rc.setPropertiesAndFeatures(propsAndFeatures);
return rc;
}
@Bean
public FilterRegistrationBean traceFilterRegistration(
@Qualifier("httpTraceFilter") Filter filter) {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(filter);
bean.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
return bean;
}
@Configuration
protected static class EurekaServerConfigBeanConfiguration {
@Bean
@ConditionalOnMissingBean
public EurekaServerConfig eurekaServerConfig(EurekaClientConfig clientConfig) {
EurekaServerConfigBean server = new EurekaServerConfigBean();
if (clientConfig.shouldRegisterWithEureka()) {
// Set a sensible default if we are supposed to replicate
server.setRegistrySyncRetries(5);
}
return server;
}
}
/**
* {@link PeerEurekaNodes} which updates peers when /refresh is invoked. Peers are
* updated only if <code>eureka.client.use-dns-for-fetching-service-urls</code> is
* <code>false</code> and one of following properties have changed.
* <p>
* </p>
* <ul>
* <li><code>eureka.client.availability-zones</code></li>
@@ -191,13 +273,12 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter {
static class RefreshablePeerEurekaNodes extends PeerEurekaNodes
implements ApplicationListener<EnvironmentChangeEvent> {
public RefreshablePeerEurekaNodes(
final PeerAwareInstanceRegistry registry,
RefreshablePeerEurekaNodes(final PeerAwareInstanceRegistry registry,
final EurekaServerConfig serverConfig,
final EurekaClientConfig clientConfig,
final ServerCodecs serverCodecs,
final EurekaClientConfig clientConfig, final ServerCodecs serverCodecs,
final ApplicationInfoManager applicationInfoManager) {
super(registry, serverConfig, clientConfig, serverCodecs, applicationInfoManager);
super(registry, serverConfig, clientConfig, serverCodecs,
applicationInfoManager);
}
@Override
@@ -225,94 +306,25 @@ public class EurekaServerAutoConfiguration extends WebMvcConfigurerAdapter {
for (final String key : changedKeys) {
// property keys are not expected to be null.
if (key.startsWith("eureka.client.service-url.") ||
key.startsWith("eureka.client.availability-zones.")) {
if (key.startsWith("eureka.client.service-url.")
|| key.startsWith("eureka.client.availability-zones.")) {
return true;
}
}
return false;
}
}
@Bean
public EurekaServerContext eurekaServerContext(ServerCodecs serverCodecs,
PeerAwareInstanceRegistry registry, PeerEurekaNodes peerEurekaNodes) {
return new DefaultEurekaServerContext(this.eurekaServerConfig, serverCodecs,
registry, peerEurekaNodes, this.applicationInfoManager);
class CloudServerCodecs extends DefaultServerCodecs {
CloudServerCodecs(EurekaServerConfig serverConfig) {
super(getFullJson(serverConfig),
CodecWrappers.getCodec(CodecWrappers.JacksonJsonMini.class),
getFullXml(serverConfig),
CodecWrappers.getCodec(CodecWrappers.JacksonXmlMini.class));
}
@Bean
public EurekaServerBootstrap eurekaServerBootstrap(PeerAwareInstanceRegistry registry,
EurekaServerContext serverContext) {
return new EurekaServerBootstrap(this.applicationInfoManager,
this.eurekaClientConfig, this.eurekaServerConfig, registry,
serverContext);
}
/**
* Register the Jersey filter
*/
@Bean
public FilterRegistrationBean jerseyFilterRegistration(
javax.ws.rs.core.Application eurekaJerseyApp) {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new ServletContainer(eurekaJerseyApp));
bean.setOrder(Ordered.LOWEST_PRECEDENCE);
bean.setUrlPatterns(
Collections.singletonList(EurekaConstants.DEFAULT_PREFIX + "/*"));
return bean;
}
/**
* Construct a Jersey {@link javax.ws.rs.core.Application} with all the resources
* required by the Eureka server.
*/
@Bean
public javax.ws.rs.core.Application jerseyApplication(Environment environment,
ResourceLoader resourceLoader) {
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
false, environment);
// Filter to include only classes that have a particular annotation.
//
provider.addIncludeFilter(new AnnotationTypeFilter(Path.class));
provider.addIncludeFilter(new AnnotationTypeFilter(Provider.class));
// Find classes in Eureka packages (or subpackages)
//
Set<Class<?>> classes = new HashSet<>();
for (String basePackage : EUREKA_PACKAGES) {
Set<BeanDefinition> beans = provider.findCandidateComponents(basePackage);
for (BeanDefinition bd : beans) {
Class<?> cls = ClassUtils.resolveClassName(bd.getBeanClassName(),
resourceLoader.getClassLoader());
classes.add(cls);
}
}
// Construct the Jersey ResourceConfig
//
Map<String, Object> propsAndFeatures = new HashMap<>();
propsAndFeatures.put(
// Skip static content used by the webapp
ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX,
EurekaConstants.DEFAULT_PREFIX + "/(fonts|images|css|js)/.*");
DefaultResourceConfig rc = new DefaultResourceConfig(classes);
rc.setPropertiesAndFeatures(propsAndFeatures);
return rc;
}
@Bean
public FilterRegistrationBean traceFilterRegistration(
@Qualifier("httpTraceFilter") Filter filter) {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(filter);
bean.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
return bean;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -65,6 +65,7 @@ public class EurekaServerBootstrap {
protected PeerAwareInstanceRegistry registry;
protected volatile EurekaServerContext serverContext;
protected volatile AwsBinder awsBinder;
public EurekaServerBootstrap(ApplicationInfoManager applicationInfoManager,
@@ -161,6 +162,8 @@ public class EurekaServerBootstrap {
/**
* Server context shutdown hook. Override for custom logic
* @throws Exception - calling {@link AwsBinder#shutdown()} or
* {@link EurekaServerContext#shutdown()} may result in an exception
*/
protected void destroyEurekaServerContext() throws Exception {
EurekaMonitors.shutdown();
@@ -174,6 +177,7 @@ public class EurekaServerBootstrap {
/**
* Users can override to clean up the environment themselves.
* @throws Exception - shutting down Eureka servers may result in an exception
*/
protected void destroyEurekaEnvironment() throws Exception {
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,12 +23,12 @@ import java.util.Map;
import java.util.Objects;
import java.util.Set;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.aws.AwsBindingStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.PropertyResolver;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.aws.AwsBindingStrategy;
import org.springframework.core.style.ToStringCreator;
/**
@@ -38,6 +38,9 @@ import org.springframework.core.style.ToStringCreator;
@ConfigurationProperties(EurekaServerConfigBean.PREFIX)
public class EurekaServerConfigBean implements EurekaServerConfig {
/**
* Eureka server configuration properties prefix.
*/
public static final String PREFIX = "eureka.server";
private static final int MINUTES = 60 * 1000;
@@ -90,6 +93,7 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
private long aSGUpdateIntervalMs = 5 * MINUTES;
private long aSGCacheExpiryTimeoutMs = 10 * MINUTES; // defaults to longer than the
// asg update interval
private long responseCacheAutoExpirationInSeconds = 180;
@@ -296,7 +300,6 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
this.initialCapacityOfResponseCache = initialCapacityOfResponseCache;
}
@Override
public int getHealthStatusMinNumberOfAvailablePeers() {
return this.minAvailableInstancesForPeerReplication;
@@ -378,7 +381,8 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
return this.expectedClientRenewalIntervalSeconds;
}
public void setExpectedClientRenewalIntervalSeconds(int expectedClientRenewalIntervalSeconds) {
public void setExpectedClientRenewalIntervalSeconds(
int expectedClientRenewalIntervalSeconds) {
this.expectedClientRenewalIntervalSeconds = expectedClientRenewalIntervalSeconds;
}
@@ -965,87 +969,95 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
this.minAvailableInstancesForPeerReplication = minAvailableInstancesForPeerReplication;
}
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EurekaServerConfigBean that = (EurekaServerConfigBean) o;
return aSGCacheExpiryTimeoutMs == that.aSGCacheExpiryTimeoutMs &&
aSGQueryTimeoutMs == that.aSGQueryTimeoutMs &&
aSGUpdateIntervalMs == that.aSGUpdateIntervalMs &&
Objects.equals(aWSAccessId, that.aWSAccessId) &&
Objects.equals(aWSSecretKey, that.aWSSecretKey) &&
batchReplication == that.batchReplication &&
bindingStrategy == that.bindingStrategy &&
deltaRetentionTimerIntervalInMs == that.deltaRetentionTimerIntervalInMs &&
disableDelta == that.disableDelta &&
disableDeltaForRemoteRegions == that.disableDeltaForRemoteRegions &&
disableTransparentFallbackToOtherRegion == that.disableTransparentFallbackToOtherRegion &&
eIPBindingRetryIntervalMs == that.eIPBindingRetryIntervalMs &&
eIPBindingRetryIntervalMsWhenUnbound == that.eIPBindingRetryIntervalMsWhenUnbound &&
eIPBindRebindRetries == that.eIPBindRebindRetries &&
enableReplicatedRequestCompression == that.enableReplicatedRequestCompression &&
enableSelfPreservation == that.enableSelfPreservation &&
evictionIntervalTimerInMs == that.evictionIntervalTimerInMs &&
gZipContentFromRemoteRegion == that.gZipContentFromRemoteRegion &&
Objects.equals(jsonCodecName, that.jsonCodecName) &&
Objects.equals(listAutoScalingGroupsRoleName, that.listAutoScalingGroupsRoleName) &&
logIdentityHeaders == that.logIdentityHeaders &&
maxElementsInPeerReplicationPool == that.maxElementsInPeerReplicationPool &&
maxElementsInStatusReplicationPool == that.maxElementsInStatusReplicationPool &&
maxIdleThreadAgeInMinutesForPeerReplication == that.maxIdleThreadAgeInMinutesForPeerReplication &&
maxIdleThreadInMinutesAgeForStatusReplication == that.maxIdleThreadInMinutesAgeForStatusReplication &&
maxThreadsForPeerReplication == that.maxThreadsForPeerReplication &&
maxThreadsForStatusReplication == that.maxThreadsForStatusReplication &&
maxTimeForReplication == that.maxTimeForReplication &&
minAvailableInstancesForPeerReplication == that.minAvailableInstancesForPeerReplication &&
minThreadsForPeerReplication == that.minThreadsForPeerReplication &&
minThreadsForStatusReplication == that.minThreadsForStatusReplication &&
numberOfReplicationRetries == that.numberOfReplicationRetries &&
peerEurekaNodesUpdateIntervalMs == that.peerEurekaNodesUpdateIntervalMs &&
peerEurekaStatusRefreshTimeIntervalMs == that.peerEurekaStatusRefreshTimeIntervalMs &&
peerNodeConnectionIdleTimeoutSeconds == that.peerNodeConnectionIdleTimeoutSeconds &&
peerNodeConnectTimeoutMs == that.peerNodeConnectTimeoutMs &&
peerNodeReadTimeoutMs == that.peerNodeReadTimeoutMs &&
peerNodeTotalConnections == that.peerNodeTotalConnections &&
peerNodeTotalConnectionsPerHost == that.peerNodeTotalConnectionsPerHost &&
primeAwsReplicaConnections == that.primeAwsReplicaConnections &&
Objects.equals(propertyResolver, that.propertyResolver) &&
rateLimiterBurstSize == that.rateLimiterBurstSize &&
rateLimiterEnabled == that.rateLimiterEnabled &&
rateLimiterFullFetchAverageRate == that.rateLimiterFullFetchAverageRate &&
Objects.equals(rateLimiterPrivilegedClients, that.rateLimiterPrivilegedClients) &&
rateLimiterRegistryFetchAverageRate == that.rateLimiterRegistryFetchAverageRate &&
rateLimiterThrottleStandardClients == that.rateLimiterThrottleStandardClients &&
registrySyncRetries == that.registrySyncRetries &&
registrySyncRetryWaitMs == that.registrySyncRetryWaitMs &&
Objects.equals(remoteRegionAppWhitelist, that.remoteRegionAppWhitelist) &&
remoteRegionConnectionIdleTimeoutSeconds == that.remoteRegionConnectionIdleTimeoutSeconds &&
remoteRegionConnectTimeoutMs == that.remoteRegionConnectTimeoutMs &&
remoteRegionFetchThreadPoolSize == that.remoteRegionFetchThreadPoolSize &&
remoteRegionReadTimeoutMs == that.remoteRegionReadTimeoutMs &&
remoteRegionRegistryFetchInterval == that.remoteRegionRegistryFetchInterval &&
remoteRegionTotalConnections == that.remoteRegionTotalConnections &&
remoteRegionTotalConnectionsPerHost == that.remoteRegionTotalConnectionsPerHost &&
Objects.equals(remoteRegionTrustStore, that.remoteRegionTrustStore) &&
Objects.equals(remoteRegionTrustStorePassword, that.remoteRegionTrustStorePassword) &&
Arrays.equals(remoteRegionUrls, that.remoteRegionUrls) &&
Objects.equals(remoteRegionUrlsWithName, that.remoteRegionUrlsWithName) &&
Double.compare(that.renewalPercentThreshold, renewalPercentThreshold) == 0 &&
renewalThresholdUpdateIntervalMs == that.renewalThresholdUpdateIntervalMs &&
responseCacheAutoExpirationInSeconds == that.responseCacheAutoExpirationInSeconds &&
responseCacheUpdateIntervalMs == that.responseCacheUpdateIntervalMs &&
retentionTimeInMSInDeltaQueue == that.retentionTimeInMSInDeltaQueue &&
route53BindingRetryIntervalMs == that.route53BindingRetryIntervalMs &&
route53BindRebindRetries == that.route53BindRebindRetries &&
route53DomainTTL == that.route53DomainTTL &&
syncWhenTimestampDiffers == that.syncWhenTimestampDiffers &&
useReadOnlyResponseCache == that.useReadOnlyResponseCache &&
waitTimeInMsWhenSyncEmpty == that.waitTimeInMsWhenSyncEmpty &&
Objects.equals(xmlCodecName, that.xmlCodecName) &&
initialCapacityOfResponseCache == that.initialCapacityOfResponseCache &&
expectedClientRenewalIntervalSeconds == that.expectedClientRenewalIntervalSeconds &&
useAwsAsgApi == that.useAwsAsgApi &&
Objects.equals(myUrl, that.myUrl);
return aSGCacheExpiryTimeoutMs == that.aSGCacheExpiryTimeoutMs
&& aSGQueryTimeoutMs == that.aSGQueryTimeoutMs
&& aSGUpdateIntervalMs == that.aSGUpdateIntervalMs
&& Objects.equals(aWSAccessId, that.aWSAccessId)
&& Objects.equals(aWSSecretKey, that.aWSSecretKey)
&& batchReplication == that.batchReplication
&& bindingStrategy == that.bindingStrategy
&& deltaRetentionTimerIntervalInMs == that.deltaRetentionTimerIntervalInMs
&& disableDelta == that.disableDelta
&& disableDeltaForRemoteRegions == that.disableDeltaForRemoteRegions
&& disableTransparentFallbackToOtherRegion == that.disableTransparentFallbackToOtherRegion
&& eIPBindingRetryIntervalMs == that.eIPBindingRetryIntervalMs
&& eIPBindingRetryIntervalMsWhenUnbound == that.eIPBindingRetryIntervalMsWhenUnbound
&& eIPBindRebindRetries == that.eIPBindRebindRetries
&& enableReplicatedRequestCompression == that.enableReplicatedRequestCompression
&& enableSelfPreservation == that.enableSelfPreservation
&& evictionIntervalTimerInMs == that.evictionIntervalTimerInMs
&& gZipContentFromRemoteRegion == that.gZipContentFromRemoteRegion
&& Objects.equals(jsonCodecName, that.jsonCodecName)
&& Objects.equals(listAutoScalingGroupsRoleName,
that.listAutoScalingGroupsRoleName)
&& logIdentityHeaders == that.logIdentityHeaders
&& maxElementsInPeerReplicationPool == that.maxElementsInPeerReplicationPool
&& maxElementsInStatusReplicationPool == that.maxElementsInStatusReplicationPool
&& maxIdleThreadAgeInMinutesForPeerReplication == that.maxIdleThreadAgeInMinutesForPeerReplication
&& maxIdleThreadInMinutesAgeForStatusReplication == that.maxIdleThreadInMinutesAgeForStatusReplication
&& maxThreadsForPeerReplication == that.maxThreadsForPeerReplication
&& maxThreadsForStatusReplication == that.maxThreadsForStatusReplication
&& maxTimeForReplication == that.maxTimeForReplication
&& minAvailableInstancesForPeerReplication == that.minAvailableInstancesForPeerReplication
&& minThreadsForPeerReplication == that.minThreadsForPeerReplication
&& minThreadsForStatusReplication == that.minThreadsForStatusReplication
&& numberOfReplicationRetries == that.numberOfReplicationRetries
&& peerEurekaNodesUpdateIntervalMs == that.peerEurekaNodesUpdateIntervalMs
&& peerEurekaStatusRefreshTimeIntervalMs == that.peerEurekaStatusRefreshTimeIntervalMs
&& peerNodeConnectionIdleTimeoutSeconds == that.peerNodeConnectionIdleTimeoutSeconds
&& peerNodeConnectTimeoutMs == that.peerNodeConnectTimeoutMs
&& peerNodeReadTimeoutMs == that.peerNodeReadTimeoutMs
&& peerNodeTotalConnections == that.peerNodeTotalConnections
&& peerNodeTotalConnectionsPerHost == that.peerNodeTotalConnectionsPerHost
&& primeAwsReplicaConnections == that.primeAwsReplicaConnections
&& Objects.equals(propertyResolver, that.propertyResolver)
&& rateLimiterBurstSize == that.rateLimiterBurstSize
&& rateLimiterEnabled == that.rateLimiterEnabled
&& rateLimiterFullFetchAverageRate == that.rateLimiterFullFetchAverageRate
&& Objects.equals(rateLimiterPrivilegedClients,
that.rateLimiterPrivilegedClients)
&& rateLimiterRegistryFetchAverageRate == that.rateLimiterRegistryFetchAverageRate
&& rateLimiterThrottleStandardClients == that.rateLimiterThrottleStandardClients
&& registrySyncRetries == that.registrySyncRetries
&& registrySyncRetryWaitMs == that.registrySyncRetryWaitMs
&& Objects.equals(remoteRegionAppWhitelist, that.remoteRegionAppWhitelist)
&& remoteRegionConnectionIdleTimeoutSeconds == that.remoteRegionConnectionIdleTimeoutSeconds
&& remoteRegionConnectTimeoutMs == that.remoteRegionConnectTimeoutMs
&& remoteRegionFetchThreadPoolSize == that.remoteRegionFetchThreadPoolSize
&& remoteRegionReadTimeoutMs == that.remoteRegionReadTimeoutMs
&& remoteRegionRegistryFetchInterval == that.remoteRegionRegistryFetchInterval
&& remoteRegionTotalConnections == that.remoteRegionTotalConnections
&& remoteRegionTotalConnectionsPerHost == that.remoteRegionTotalConnectionsPerHost
&& Objects.equals(remoteRegionTrustStore, that.remoteRegionTrustStore)
&& Objects.equals(remoteRegionTrustStorePassword,
that.remoteRegionTrustStorePassword)
&& Arrays.equals(remoteRegionUrls, that.remoteRegionUrls)
&& Objects.equals(remoteRegionUrlsWithName, that.remoteRegionUrlsWithName)
&& Double.compare(that.renewalPercentThreshold,
renewalPercentThreshold) == 0
&& renewalThresholdUpdateIntervalMs == that.renewalThresholdUpdateIntervalMs
&& responseCacheAutoExpirationInSeconds == that.responseCacheAutoExpirationInSeconds
&& responseCacheUpdateIntervalMs == that.responseCacheUpdateIntervalMs
&& retentionTimeInMSInDeltaQueue == that.retentionTimeInMSInDeltaQueue
&& route53BindingRetryIntervalMs == that.route53BindingRetryIntervalMs
&& route53BindRebindRetries == that.route53BindRebindRetries
&& route53DomainTTL == that.route53DomainTTL
&& syncWhenTimestampDiffers == that.syncWhenTimestampDiffers
&& useReadOnlyResponseCache == that.useReadOnlyResponseCache
&& waitTimeInMsWhenSyncEmpty == that.waitTimeInMsWhenSyncEmpty
&& Objects.equals(xmlCodecName, that.xmlCodecName)
&& initialCapacityOfResponseCache == that.initialCapacityOfResponseCache
&& expectedClientRenewalIntervalSeconds == that.expectedClientRenewalIntervalSeconds
&& useAwsAsgApi == that.useAwsAsgApi && Objects.equals(myUrl, that.myUrl);
}
@Override
@@ -1053,13 +1065,13 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
return Objects.hash(aSGCacheExpiryTimeoutMs, aSGQueryTimeoutMs,
aSGUpdateIntervalMs, aWSAccessId, aWSSecretKey, batchReplication,
bindingStrategy, deltaRetentionTimerIntervalInMs, disableDelta,
disableDeltaForRemoteRegions,
disableTransparentFallbackToOtherRegion, eIPBindRebindRetries,
eIPBindingRetryIntervalMs, eIPBindingRetryIntervalMsWhenUnbound,
enableReplicatedRequestCompression, enableSelfPreservation,
evictionIntervalTimerInMs, gZipContentFromRemoteRegion,
jsonCodecName, listAutoScalingGroupsRoleName, logIdentityHeaders,
maxElementsInPeerReplicationPool, maxElementsInStatusReplicationPool,
disableDeltaForRemoteRegions, disableTransparentFallbackToOtherRegion,
eIPBindRebindRetries, eIPBindingRetryIntervalMs,
eIPBindingRetryIntervalMsWhenUnbound, enableReplicatedRequestCompression,
enableSelfPreservation, evictionIntervalTimerInMs,
gZipContentFromRemoteRegion, jsonCodecName, listAutoScalingGroupsRoleName,
logIdentityHeaders, maxElementsInPeerReplicationPool,
maxElementsInStatusReplicationPool,
maxIdleThreadAgeInMinutesForPeerReplication,
maxIdleThreadInMinutesAgeForStatusReplication,
maxThreadsForPeerReplication, maxThreadsForStatusReplication,
@@ -1074,21 +1086,18 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
rateLimiterPrivilegedClients, rateLimiterRegistryFetchAverageRate,
rateLimiterThrottleStandardClients, registrySyncRetries,
registrySyncRetryWaitMs, remoteRegionAppWhitelist,
remoteRegionConnectTimeoutMs,
remoteRegionConnectionIdleTimeoutSeconds,
remoteRegionConnectTimeoutMs, remoteRegionConnectionIdleTimeoutSeconds,
remoteRegionFetchThreadPoolSize, remoteRegionReadTimeoutMs,
remoteRegionRegistryFetchInterval, remoteRegionTotalConnections,
remoteRegionTotalConnectionsPerHost, remoteRegionTrustStore,
remoteRegionTrustStorePassword, remoteRegionUrls,
remoteRegionUrlsWithName, renewalPercentThreshold,
renewalThresholdUpdateIntervalMs,
responseCacheAutoExpirationInSeconds,
renewalThresholdUpdateIntervalMs, responseCacheAutoExpirationInSeconds,
responseCacheUpdateIntervalMs, retentionTimeInMSInDeltaQueue,
route53BindRebindRetries, route53BindingRetryIntervalMs,
route53DomainTTL, syncWhenTimestampDiffers,
useReadOnlyResponseCache, waitTimeInMsWhenSyncEmpty, xmlCodecName,
initialCapacityOfResponseCache, expectedClientRenewalIntervalSeconds,
useAwsAsgApi, myUrl);
route53BindRebindRetries, route53BindingRetryIntervalMs, route53DomainTTL,
syncWhenTimestampDiffers, useReadOnlyResponseCache,
waitTimeInMsWhenSyncEmpty, xmlCodecName, initialCapacityOfResponseCache,
expectedClientRenewalIntervalSeconds, useAwsAsgApi, myUrl);
}
@Override
@@ -1101,76 +1110,106 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
.append("aWSSecretKey", this.aWSSecretKey)
.append("batchReplication", this.batchReplication)
.append("bindingStrategy", this.bindingStrategy)
.append("deltaRetentionTimerIntervalInMs", this.deltaRetentionTimerIntervalInMs)
.append("deltaRetentionTimerIntervalInMs",
this.deltaRetentionTimerIntervalInMs)
.append("disableDelta", this.disableDelta)
.append("disableDeltaForRemoteRegions", this.disableDeltaForRemoteRegions)
.append("disableTransparentFallbackToOtherRegion", this.disableTransparentFallbackToOtherRegion)
.append("disableTransparentFallbackToOtherRegion",
this.disableTransparentFallbackToOtherRegion)
.append("eIPBindRebindRetries", this.eIPBindRebindRetries)
.append("eIPBindingRetryIntervalMs", this.eIPBindingRetryIntervalMs)
.append("eIPBindingRetryIntervalMsWhenUnbound", this.eIPBindingRetryIntervalMsWhenUnbound)
.append("enableReplicatedRequestCompression", this.enableReplicatedRequestCompression)
.append("eIPBindingRetryIntervalMsWhenUnbound",
this.eIPBindingRetryIntervalMsWhenUnbound)
.append("enableReplicatedRequestCompression",
this.enableReplicatedRequestCompression)
.append("enableSelfPreservation", this.enableSelfPreservation)
.append("evictionIntervalTimerInMs", this.evictionIntervalTimerInMs)
.append("gZipContentFromRemoteRegion", this.gZipContentFromRemoteRegion)
.append("jsonCodecName", this.jsonCodecName)
.append("listAutoScalingGroupsRoleName", this.listAutoScalingGroupsRoleName)
.append("listAutoScalingGroupsRoleName",
this.listAutoScalingGroupsRoleName)
.append("logIdentityHeaders", this.logIdentityHeaders)
.append("maxElementsInPeerReplicationPool", this.maxElementsInPeerReplicationPool)
.append("maxElementsInStatusReplicationPool", this.maxElementsInStatusReplicationPool)
.append("maxIdleThreadAgeInMinutesForPeerReplication", this.maxIdleThreadAgeInMinutesForPeerReplication)
.append("maxIdleThreadInMinutesAgeForStatusReplication", this.maxIdleThreadInMinutesAgeForStatusReplication)
.append("maxElementsInPeerReplicationPool",
this.maxElementsInPeerReplicationPool)
.append("maxElementsInStatusReplicationPool",
this.maxElementsInStatusReplicationPool)
.append("maxIdleThreadAgeInMinutesForPeerReplication",
this.maxIdleThreadAgeInMinutesForPeerReplication)
.append("maxIdleThreadInMinutesAgeForStatusReplication",
this.maxIdleThreadInMinutesAgeForStatusReplication)
.append("maxThreadsForPeerReplication", this.maxThreadsForPeerReplication)
.append("maxThreadsForStatusReplication", this.maxThreadsForStatusReplication)
.append("maxThreadsForStatusReplication",
this.maxThreadsForStatusReplication)
.append("maxTimeForReplication", this.maxTimeForReplication)
.append("minAvailableInstancesForPeerReplication", this.minAvailableInstancesForPeerReplication)
.append("minAvailableInstancesForPeerReplication",
this.minAvailableInstancesForPeerReplication)
.append("minThreadsForPeerReplication", this.minThreadsForPeerReplication)
.append("minThreadsForStatusReplication", this.minThreadsForStatusReplication)
.append("minThreadsForStatusReplication",
this.minThreadsForStatusReplication)
.append("numberOfReplicationRetries", this.numberOfReplicationRetries)
.append("peerEurekaNodesUpdateIntervalMs", this.peerEurekaNodesUpdateIntervalMs)
.append("peerEurekaStatusRefreshTimeIntervalMs", this.peerEurekaStatusRefreshTimeIntervalMs)
.append("peerEurekaNodesUpdateIntervalMs",
this.peerEurekaNodesUpdateIntervalMs)
.append("peerEurekaStatusRefreshTimeIntervalMs",
this.peerEurekaStatusRefreshTimeIntervalMs)
.append("peerNodeConnectTimeoutMs", this.peerNodeConnectTimeoutMs)
.append("peerNodeConnectionIdleTimeoutSeconds", this.peerNodeConnectionIdleTimeoutSeconds)
.append("peerNodeConnectionIdleTimeoutSeconds",
this.peerNodeConnectionIdleTimeoutSeconds)
.append("peerNodeReadTimeoutMs", this.peerNodeReadTimeoutMs)
.append("peerNodeTotalConnections", this.peerNodeTotalConnections)
.append("peerNodeTotalConnectionsPerHost", this.peerNodeTotalConnectionsPerHost)
.append("peerNodeTotalConnectionsPerHost",
this.peerNodeTotalConnectionsPerHost)
.append("primeAwsReplicaConnections", this.primeAwsReplicaConnections)
.append("propertyResolver", this.propertyResolver)
.append("rateLimiterBurstSize", this.rateLimiterBurstSize)
.append("rateLimiterEnabled", this.rateLimiterEnabled)
.append("rateLimiterFullFetchAverageRate", this.rateLimiterFullFetchAverageRate)
.append("rateLimiterFullFetchAverageRate",
this.rateLimiterFullFetchAverageRate)
.append("rateLimiterPrivilegedClients", this.rateLimiterPrivilegedClients)
.append("rateLimiterRegistryFetchAverageRate", this.rateLimiterRegistryFetchAverageRate)
.append("rateLimiterThrottleStandardClients", this.rateLimiterThrottleStandardClients)
.append("rateLimiterRegistryFetchAverageRate",
this.rateLimiterRegistryFetchAverageRate)
.append("rateLimiterThrottleStandardClients",
this.rateLimiterThrottleStandardClients)
.append("registrySyncRetries", this.registrySyncRetries)
.append("registrySyncRetryWaitMs", this.registrySyncRetryWaitMs)
.append("remoteRegionAppWhitelist", this.remoteRegionAppWhitelist)
.append("remoteRegionConnectTimeoutMs", this.remoteRegionConnectTimeoutMs)
.append("remoteRegionConnectionIdleTimeoutSeconds", this.remoteRegionConnectionIdleTimeoutSeconds)
.append("remoteRegionFetchThreadPoolSize", this.remoteRegionFetchThreadPoolSize)
.append("remoteRegionConnectionIdleTimeoutSeconds",
this.remoteRegionConnectionIdleTimeoutSeconds)
.append("remoteRegionFetchThreadPoolSize",
this.remoteRegionFetchThreadPoolSize)
.append("remoteRegionReadTimeoutMs", this.remoteRegionReadTimeoutMs)
.append("remoteRegionRegistryFetchInterval", this.remoteRegionRegistryFetchInterval)
.append("remoteRegionRegistryFetchInterval",
this.remoteRegionRegistryFetchInterval)
.append("remoteRegionTotalConnections", this.remoteRegionTotalConnections)
.append("remoteRegionTotalConnectionsPerHost", this.remoteRegionTotalConnectionsPerHost)
.append("remoteRegionTotalConnectionsPerHost",
this.remoteRegionTotalConnectionsPerHost)
.append("remoteRegionTrustStore", this.remoteRegionTrustStore)
.append("remoteRegionTrustStorePassword", this.remoteRegionTrustStorePassword)
.append("remoteRegionTrustStorePassword",
this.remoteRegionTrustStorePassword)
.append("remoteRegionUrls", this.remoteRegionUrls)
.append("remoteRegionUrlsWithName", this.remoteRegionUrlsWithName)
.append("renewalPercentThreshold", this.renewalPercentThreshold)
.append("renewalThresholdUpdateIntervalMs", this.renewalThresholdUpdateIntervalMs)
.append("responseCacheAutoExpirationInSeconds", this.responseCacheAutoExpirationInSeconds)
.append("responseCacheUpdateIntervalMs", this.responseCacheUpdateIntervalMs)
.append("retentionTimeInMSInDeltaQueue", this.retentionTimeInMSInDeltaQueue)
.append("renewalThresholdUpdateIntervalMs",
this.renewalThresholdUpdateIntervalMs)
.append("responseCacheAutoExpirationInSeconds",
this.responseCacheAutoExpirationInSeconds)
.append("responseCacheUpdateIntervalMs",
this.responseCacheUpdateIntervalMs)
.append("retentionTimeInMSInDeltaQueue",
this.retentionTimeInMSInDeltaQueue)
.append("route53BindRebindRetries", this.route53BindRebindRetries)
.append("route53BindingRetryIntervalMs", this.route53BindingRetryIntervalMs)
.append("route53BindingRetryIntervalMs",
this.route53BindingRetryIntervalMs)
.append("route53DomainTTL", this.route53DomainTTL)
.append("syncWhenTimestampDiffers", this.syncWhenTimestampDiffers)
.append("useReadOnlyResponseCache", this.useReadOnlyResponseCache)
.append("waitTimeInMsWhenSyncEmpty", this.waitTimeInMsWhenSyncEmpty)
.append("xmlCodecName", this.xmlCodecName)
.append("initialCapacityOfResponseCache", this.initialCapacityOfResponseCache)
.append("expectedClientRenewalIntervalSeconds", this.expectedClientRenewalIntervalSeconds)
.append("useAwsAsgApi", this.useAwsAsgApi)
.append("myUrl", this.myUrl)
.append("initialCapacityOfResponseCache",
this.initialCapacityOfResponseCache)
.append("expectedClientRenewalIntervalSeconds",
this.expectedClientRenewalIntervalSeconds)
.append("useAwsAsgApi", this.useAwsAsgApi).append("myUrl", this.myUrl)
.toString();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,8 +18,10 @@ package org.springframework.cloud.netflix.eureka.server;
import javax.servlet.ServletContext;
import com.netflix.eureka.EurekaServerConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.eureka.server.event.EurekaRegistryAvailableEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaServerStartedEvent;
@@ -30,8 +32,6 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.context.ServletContextAware;
import com.netflix.eureka.EurekaServerConfig;
/**
* @author Dave Syer
*/
@@ -39,7 +39,8 @@ import com.netflix.eureka.EurekaServerConfig;
public class EurekaServerInitializerConfiguration
implements ServletContextAware, SmartLifecycle, Ordered {
private static final Log log = LogFactory.getLog(EurekaServerInitializerConfiguration.class);
private static final Log log = LogFactory
.getLog(EurekaServerInitializerConfiguration.class);
@Autowired
private EurekaServerConfig eurekaServerConfig;
@@ -68,7 +69,8 @@ public class EurekaServerInitializerConfiguration
public void run() {
try {
// TODO: is this class even needed now?
eurekaServerBootstrap.contextInitialized(EurekaServerInitializerConfiguration.this.servletContext);
eurekaServerBootstrap.contextInitialized(
EurekaServerInitializerConfiguration.this.servletContext);
log.info("Started Eureka Server");
publish(new EurekaRegistryAvailableEvent(getEurekaServerConfig()));
@@ -1,5 +1,5 @@
/*
* Copyright 2017 the original author or authors.
* Copyright 2017-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,7 +21,7 @@ import org.springframework.context.annotation.Configuration;
/**
* Responsible for adding in a marker bean to activate
* {@link EurekaServerAutoConfiguration}
* {@link EurekaServerAutoConfiguration}.
*
* @author Biju Kunjummen
*/
@@ -34,5 +34,7 @@ public class EurekaServerMarkerConfiguration {
}
class Marker {
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,25 +18,24 @@ package org.springframework.cloud.netflix.eureka.server;
import java.util.List;
import com.netflix.eureka.lease.Lease;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRegisteredEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRenewedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.netflix.appinfo.ApplicationInfoManager;
import com.netflix.appinfo.InstanceInfo;
import com.netflix.discovery.EurekaClient;
import com.netflix.discovery.EurekaClientConfig;
import com.netflix.discovery.shared.Application;
import com.netflix.eureka.EurekaServerConfig;
import com.netflix.eureka.lease.Lease;
import com.netflix.eureka.registry.PeerAwareInstanceRegistryImpl;
import com.netflix.eureka.resources.ServerCodecs;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceCanceledEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRegisteredEvent;
import org.springframework.cloud.netflix.eureka.server.event.EurekaInstanceRenewedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
/**
@@ -48,6 +47,7 @@ public class InstanceRegistry extends PeerAwareInstanceRegistryImpl
private static final Log log = LogFactory.getLog(InstanceRegistry.class);
private ApplicationContext ctxt;
private int defaultOpenForTrafficCount;
public InstanceRegistry(EurekaServerConfig serverConfig,
@@ -128,7 +128,8 @@ public class InstanceRegistry extends PeerAwareInstanceRegistryImpl
}
private void handleCancelation(String appName, String id, boolean isReplication) {
log("cancel " + appName + ", serverId " + id + ", isReplication " + isReplication);
log("cancel " + appName + ", serverId " + id + ", isReplication "
+ isReplication);
publishEvent(new EurekaInstanceCanceledEvent(this, appName, id, isReplication));
}
@@ -158,4 +159,5 @@ public class InstanceRegistry extends PeerAwareInstanceRegistryImpl
}
return leaseDuration;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2016 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -12,7 +12,6 @@
* 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 org.springframework.cloud.netflix.eureka.server;
@@ -29,19 +28,26 @@ import static org.springframework.cloud.netflix.eureka.server.InstanceRegistryPr
@ConfigurationProperties(PREFIX)
public class InstanceRegistryProperties {
/**
* Prefix for Eureka instance registry properties.
*/
public static final String PREFIX = "eureka.instance.registry";
/* Default number of expected client, defaults to 1.
* Setting expectedNumberOfClientsSendingRenews to non-zero to ensure that even an isolated
/*
* Default number of expected client, defaults to 1. Setting
* expectedNumberOfClientsSendingRenews to non-zero to ensure that even an isolated
* server can adjust its eviction policy to the number of registrations (when it's
* zero, even a successful registration won't reset the rate threshold in
* InstanceRegistry.register()).
*/
@Value("${eureka.server.expectedNumberOfRenewsPerMin:1}") // for backwards compatibility
@Value("${eureka.server.expectedNumberOfRenewsPerMin:1}") // for backwards
// compatibility
private int expectedNumberOfClientsSendingRenews = 1;
/** Value used in determining when leases are cancelled, default to 1 for standalone.
* Should be set to 0 for peer replicated eurekas */
/**
* Value used in determining when leases are cancelled, default to 1 for standalone.
* Should be set to 0 for peer replicated eurekas
*/
@Value("${eureka.server.defaultOpenForTrafficCount:1}") // for backwards compatibility
private int defaultOpenForTrafficCount = 1;
@@ -49,11 +55,13 @@ public class InstanceRegistryProperties {
return expectedNumberOfClientsSendingRenews;
}
public void setExpectedNumberOfClientsSendingRenews(int expectedNumberOfClientsSendingRenews) {
public void setExpectedNumberOfClientsSendingRenews(
int expectedNumberOfClientsSendingRenews) {
this.expectedNumberOfClientsSendingRenews = expectedNumberOfClientsSendingRenews;
}
@DeprecatedConfigurationProperty(replacement = PREFIX+".expected-number-of-clients-sending-renews")
@DeprecatedConfigurationProperty(replacement = PREFIX
+ ".expected-number-of-clients-sending-renews")
@Deprecated
public int getExpectedNumberOfRenewsPerMin() {
return getExpectedNumberOfClientsSendingRenews();
@@ -71,4 +79,5 @@ public class InstanceRegistryProperties {
public void setDefaultOpenForTrafficCount(int defaultOpenForTrafficCount) {
this.defaultOpenForTrafficCount = defaultOpenForTrafficCount;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,10 @@
package org.springframework.cloud.netflix.eureka.server.event;
import org.springframework.context.ApplicationEvent;
import java.util.Objects;
import org.springframework.context.ApplicationEvent;
/**
* @author Spencer Gibb
* @author Gregor Zurowski
@@ -67,12 +67,15 @@ public class EurekaInstanceCanceledEvent extends ApplicationEvent {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EurekaInstanceCanceledEvent that = (EurekaInstanceCanceledEvent) o;
return Objects.equals(appName, that.appName) &&
Objects.equals(serverId, that.serverId) &&
replication == replication;
return Objects.equals(appName, that.appName)
&& Objects.equals(serverId, that.serverId) && replication == replication;
}
@Override
@@ -82,10 +85,9 @@ public class EurekaInstanceCanceledEvent extends ApplicationEvent {
@Override
public String toString() {
return new StringBuilder("EurekaInstanceCanceledEvent{")
.append("appName='").append(appName).append("', ")
.append("serverId='").append(serverId).append("', ")
.append("replication=").append(replication).append("}")
return new StringBuilder("EurekaInstanceCanceledEvent{").append("appName='")
.append(appName).append("', ").append("serverId='").append(serverId)
.append("', ").append("replication=").append(replication).append("}")
.toString();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,11 @@
package org.springframework.cloud.netflix.eureka.server.event;
import org.springframework.context.ApplicationEvent;
import java.util.Objects;
import com.netflix.appinfo.InstanceInfo;
import java.util.Objects;
import org.springframework.context.ApplicationEvent;
/**
* @author Spencer Gibb
@@ -69,12 +69,15 @@ public class EurekaInstanceRegisteredEvent extends ApplicationEvent {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EurekaInstanceRegisteredEvent that = (EurekaInstanceRegisteredEvent) o;
return Objects.equals(instanceInfo, that.instanceInfo) &&
leaseDuration == leaseDuration &&
replication == replication;
return Objects.equals(instanceInfo, that.instanceInfo)
&& leaseDuration == leaseDuration && replication == replication;
}
@Override
@@ -84,10 +87,10 @@ public class EurekaInstanceRegisteredEvent extends ApplicationEvent {
@Override
public String toString() {
return new StringBuilder("EurekaInstanceRegisteredEvent{")
.append("instanceInfo=").append(instanceInfo).append(", ")
.append("leaseDuration=").append(leaseDuration).append(", ")
.append("replication=").append(replication).append("}")
.toString();
return new StringBuilder("EurekaInstanceRegisteredEvent{").append("instanceInfo=")
.append(instanceInfo).append(", ").append("leaseDuration=")
.append(leaseDuration).append(", ").append("replication=")
.append(replication).append("}").toString();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2015 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,11 +16,11 @@
package org.springframework.cloud.netflix.eureka.server.event;
import org.springframework.context.ApplicationEvent;
import java.util.Objects;
import com.netflix.appinfo.InstanceInfo;
import java.util.Objects;
import org.springframework.context.ApplicationEvent;
/**
* @author Spencer Gibb
@@ -80,13 +80,17 @@ public class EurekaInstanceRenewedEvent extends ApplicationEvent {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EurekaInstanceRenewedEvent that = (EurekaInstanceRenewedEvent) o;
return Objects.equals(appName, that.appName) &&
Objects.equals(serverId, that.serverId) &&
Objects.equals(instanceInfo, that.instanceInfo) &&
replication == that.replication;
return Objects.equals(appName, that.appName)
&& Objects.equals(serverId, that.serverId)
&& Objects.equals(instanceInfo, that.instanceInfo)
&& replication == that.replication;
}
@Override
@@ -96,12 +100,10 @@ public class EurekaInstanceRenewedEvent extends ApplicationEvent {
@Override
public String toString() {
return new StringBuilder("EurekaInstanceRenewedEvent{")
.append("appName='").append(appName).append("', ")
.append("serverId='").append(serverId).append("', ")
.append("instanceInfo=").append(instanceInfo).append(", ")
.append("replication=").append(replication).append("}")
.toString();
return new StringBuilder("EurekaInstanceRenewedEvent{").append("appName='")
.append(appName).append("', ").append("serverId='").append(serverId)
.append("', ").append("instanceInfo=").append(instanceInfo).append(", ")
.append("replication=").append(replication).append("}").toString();
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2013-2014 the original author or authors.
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,10 +16,10 @@
package org.springframework.cloud.netflix.eureka.server.event;
import org.springframework.context.ApplicationEvent;
import com.netflix.eureka.EurekaServerConfig;
import org.springframework.context.ApplicationEvent;
/**
* @author Dave Syer
*/
@@ -27,7 +27,7 @@ import com.netflix.eureka.EurekaServerConfig;
public class EurekaRegistryAvailableEvent extends ApplicationEvent {
/**
* @param eurekaServerConfig
* @param eurekaServerConfig {@link EurekaServerConfig} event source
*/
public EurekaRegistryAvailableEvent(EurekaServerConfig eurekaServerConfig) {
super(eurekaServerConfig);

Some files were not shown because too many files have changed in this diff Show More