Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make profile specific paths optional #788

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@
@Ignore("update to stream 4.0.0 testing")
public class ConsulBinderApplicationTests {

/**
* wireMock.
*/
@Rule
public final WireMockRule wireMock = new WireMockRule(18500);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
*/
public class ConsulBinderConfigurationTests {

/**
* exception.
*/
@Rule
public ExpectedException exception = ExpectedException.none();

Expand All @@ -55,6 +58,9 @@ public void consulDisabledDisablesBinder() {

interface Events {

/**
* @return the channel
*/
// @Output
MessageChannel purchases();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ public boolean partitionStrategyInvoked() {

public static class StubPartitionSelectorStrategy implements PartitionSelectorStrategy {

/**
* invoked.
*/
public volatile boolean invoked = false;

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public class ConfigWatch implements ApplicationEventPublisherAware, SmartLifecyc

private final AtomicBoolean running = new AtomicBoolean(false);

private LinkedHashMap<String, Long> consulIndexes;
private final LinkedHashMap<String, Long> consulIndexes;

private ApplicationEventPublisher publisher;

Expand Down Expand Up @@ -150,41 +150,32 @@ public void watchConfigKeyValues() {

// use the consul ACL token if found
String aclToken = this.properties.getAclToken();
if (StringUtils.isEmpty(aclToken)) {
if (!StringUtils.hasLength(aclToken)) {
aclToken = null;
}

Response<List<GetValue>> response = this.consul.getKVValues(context, aclToken,
new QueryParams(this.properties.getWatch().getWaitTime(), currentIndex));

// if response.value == null, response was a 404, otherwise it was a
// 200, reducing churn if there wasn't anything
if (response.getValue() != null && !response.getValue().isEmpty()) {
Long newIndex = response.getConsulIndex();

if (newIndex != null && !newIndex.equals(currentIndex)) {
// don't publish the same index again, don't publish the first
// time (-1) so index can be primed
if (!this.consulIndexes.containsValue(newIndex) && !currentIndex.equals(-1L)) {
if (log.isTraceEnabled()) {
log.trace("Context " + context + " has new index " + newIndex);
}
RefreshEventData data = new RefreshEventData(context, currentIndex, newIndex);
this.publisher.publishEvent(new RefreshEvent(this, data, data.toString()));
}
else if (log.isTraceEnabled()) {
log.trace("Event for index already published for context " + context);
// if response.value == null, response was a 404, a key is deleted
Long newIndex = response.getConsulIndex();
if (newIndex != null && !newIndex.equals(currentIndex)) {
// don't publish the same index again, don't publish the first
// time (-1) so index can be primed
if (!this.consulIndexes.containsValue(newIndex) && !currentIndex.equals(-1L)) {
if (log.isTraceEnabled()) {
log.trace("Context " + context + " has new index " + newIndex);
}
this.consulIndexes.put(context, newIndex);
RefreshEventData data = new RefreshEventData(context, currentIndex, newIndex);
this.publisher.publishEvent(new RefreshEvent(this, data, data.toString()));
}
else if (log.isTraceEnabled()) {
log.trace("Same index for context " + context);
log.trace("Event for index already published for context " + context);
}
this.consulIndexes.put(context, newIndex);
}
else if (log.isTraceEnabled()) {
log.trace("No value for context " + context);
log.trace("Same index for context " + context);
}

}
catch (Exception e) {
// only fail fast on the initial query, otherwise just log the error
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ public class ConsulConfigProperties {
*/
private String name;

private boolean profileEnabled = true;

public ConsulConfigProperties() {
}

Expand Down Expand Up @@ -189,12 +191,21 @@ public void setName(String name) {
this.name = name;
}

public boolean isProfileEnabled() {
return profileEnabled;
}

public void setProfileEnabled(boolean profileEnabled) {
this.profileEnabled = profileEnabled;
}

@Override
public String toString() {
return new ToStringCreator(this).append("enabled", this.enabled).append("prefixes", this.prefixes)
.append("defaultContext", this.defaultContext).append("profileSeparator", this.profileSeparator)
.append("format", this.format).append("dataKey", this.dataKey).append("aclToken", this.aclToken)
.append("watch", this.watch).append("failFast", this.failFast).append("name", this.name).toString();
.append("watch", this.watch).append("failFast", this.failFast).append("name", this.name)
.append("profileEnabled", this.profileEnabled).toString();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,10 @@ public List<Context> generateAutomaticContexts(List<String> profiles, boolean re
for (String suffix : suffixes) {
contexts.add(new Context(defaultContext + suffix));
}
for (String suffix : suffixes) {
addProfiles(contexts, defaultContext, profiles, suffix);
if (properties.isProfileEnabled()) {
for (String suffix : suffixes) {
addProfiles(contexts, defaultContext, profiles, suffix);
}
}

// getName() defaults to ${spring.application.name} or application
Expand All @@ -75,8 +77,10 @@ public List<Context> generateAutomaticContexts(List<String> profiles, boolean re
for (String suffix : suffixes) {
contexts.add(new Context(baseContext + suffix));
}
for (String suffix : suffixes) {
addProfiles(contexts, baseContext, profiles, suffix);
if (properties.isProfileEnabled()) {
for (String suffix : suffixes) {
addProfiles(contexts, baseContext, profiles, suffix);
}
}
}
if (reverse) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.cloud.consul.config.ConsulConfigProperties.Format.FILES;
Expand All @@ -52,7 +51,7 @@ public class ConfigWatchTests {
private ConsulConfigProperties configProperties;

@Before
public void setUp() throws Exception {
public void setUp() {
this.configProperties = new ConsulConfigProperties();
}

Expand All @@ -62,6 +61,11 @@ public void watchPublishesEventWithAcl() {

setupWatch(eventPublisher, new GetValue(), "/app/", "2ee647bd-bd69-4118-9f34-b9a6e9e60746");

// there are two threads to publish events here in this UT, the unit test main
// thread and the thread started by
// config.start(). If you set a breakpoint or have a slow machine, you will see
// the test cases fail if we
// times(1) here. To work around this problem we use atLeastOnce() here.
verify(eventPublisher, atLeastOnce()).publishEvent(any(RefreshEvent.class));
}

Expand All @@ -71,16 +75,16 @@ public void watchPublishesEvent() {

setupWatch(eventPublisher, new GetValue(), "/app/");

verify(eventPublisher, times(1)).publishEvent(any(RefreshEvent.class));
verify(eventPublisher, atLeastOnce()).publishEvent(any(RefreshEvent.class));
}

@Test
public void watchWithNullValueDoesNotPublishEvent() {
public void watchForDeletedKeyPublishesEvent() {
ApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);

setupWatch(eventPublisher, null, "/app/");

verify(eventPublisher, never()).publishEvent(any(RefreshEvent.class));
verify(eventPublisher, atLeastOnce()).publishEvent(any(RefreshEvent.class));
}

@Test
Expand Down Expand Up @@ -135,11 +139,11 @@ public void firstCallDoesNotPublishEvent() {
Response<List<GetValue>> response = new Response<>(getValues, 1L, false, 1L);
when(consul.getKVValues(eq(context), anyString(), any(QueryParams.class))).thenReturn(response);

ConfigWatch watch = new ConfigWatch(this.configProperties, consul, new LinkedHashMap<String, Long>());
ConfigWatch watch = new ConfigWatch(this.configProperties, consul, new LinkedHashMap<>());
watch.setApplicationEventPublisher(eventPublisher);

watch.watchConfigKeyValues();
verify(eventPublisher, times(0)).publishEvent(any(RefreshEvent.class));
verify(eventPublisher, never()).publishEvent(any(RefreshEvent.class));
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -41,24 +41,54 @@
@DirtiesContext
public class ConsulPropertySourceLocatorFilesTests {

/**
* the prefix.
*/
public static final String PREFIX = "_propertySourceLocatorFilesTests_config__";

/**
* the ROOT.
*/
public static final String ROOT = PREFIX + UUID.randomUUID();

/**
* the spring app name.
*/
public static final String APP_NAME = "testFilesFormat";

/**
* the config file for the application in YAML.
*/
public static final String APPLICATION_YML = "/application.yml";

/**
* the dev profile config for the application in YAML.
*/
public static final String APPLICATION_DEV_YML = "/application-dev.yaml";

/**
* the config file in properties.
*/
public static final String APP_NAME_PROPS = "/" + APP_NAME + ".properties";

/**
* the dev profile config file in properties.
*/
public static final String APP_NAME_DEV_PROPS = "/" + APP_NAME + "-dev.properties";

/**
* the spring app context.
*/
private ConfigurableApplicationContext context;

/**
* the env.
*/
private ConfigurableEnvironment environment;

/**
* the consul client for test.
*/
private ConsulClient client;

@Before
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@
*/
public class ConsulPropertySourceLocatorRetryTests {

/**
* the output.
*/
@Rule
public OutputCaptureRule output = new OutputCaptureRule();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* 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
*
* https://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.consul.config;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

/**
* @author Daniel Wu In some cases the profile is not needed, we can cut 50% pressure to
* Consul in that case. This test case mainly focus on the behaviro of
* <code>spring.cloud.consul.config.profileEnabled</code>.
*/
public class ConsulPropertySourcesTests {

@Test
public void testProfileEnabledByDefault() {
List<String> profiles = new ArrayList<>();
profiles.add("default");
ConsulConfigProperties properties = new ConsulConfigProperties();
properties.setName("myapp");
ConsulPropertySources sources = new ConsulPropertySources(properties, mock(Log.class));
List<ConsulPropertySources.Context> contexts = sources.generateAutomaticContexts(profiles, false);
List<ConsulPropertySources.Context> expected = new ArrayList<>();
expected.add(new ConsulPropertySources.Context("config/application/"));
expected.add(new ConsulPropertySources.Context("config/application,default/"));
expected.add(new ConsulPropertySources.Context("config/myapp/"));
expected.add(new ConsulPropertySources.Context("config/myapp,default/"));
assertThat(contexts).usingRecursiveFieldByFieldElementComparatorOnFields("path").isEqualTo(expected);
}

@Test
public void testProfileDisabled() {
List<String> profiles = new ArrayList<>();
profiles.add("default");
ConsulConfigProperties properties = new ConsulConfigProperties();
properties.setName("myapp");
properties.setProfileEnabled(false);
ConsulPropertySources sources = new ConsulPropertySources(properties, mock(Log.class));
List<ConsulPropertySources.Context> contexts = sources.generateAutomaticContexts(profiles, false);
List<ConsulPropertySources.Context> expected = new ArrayList<>();
expected.add(new ConsulPropertySources.Context("config/application/"));
expected.add(new ConsulPropertySources.Context("config/myapp/"));
assertThat(contexts).usingRecursiveFieldByFieldElementComparatorOnFields("path").isEqualTo(expected);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ public class ConsulTestcontainers implements ApplicationContextInitializer<Confi

static final Logger logger = LoggerFactory.getLogger(ConsulTestcontainers.class);

/**
* the consul server.
*/
public static GenericContainer<?> consul = new GenericContainer<>("consul:1.7.2")
.withLogConsumer(new Slf4jLogConsumer(logger).withSeparateOutputStreams())
.waitingFor(Wait.forHttp("/v1/status/leader")).withExposedPorts(8500)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
import static org.mockito.Mockito.verify;

/**
* Test for ConsulHeartbeatTask
* Test for ConsulHeartbeatTask.
*
* @author Toshiaki Maki
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
@ContextConfiguration(initializers = ConsulTestcontainers.class)
public class ConsulAutoServiceRegistrationFailFastTests {

/**
* the exception.
*/
@Rule
public ExpectedException exception = ExpectedException.none();

Expand Down
Loading