Skip to content
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 @@ -57,32 +57,34 @@ public KubernetesClientServicesListSupplier(Environment environment,

@Override
public Flux<List<ServiceInstance>> get() {
List<ServiceInstance> result = new ArrayList<>();
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we had our code as :

public Flux<List<ServiceInstance>> get() { 

      List<ServiceInstance> result = ....
      return Flux.just(result); 

}

and it changes to :

public Flux<List<ServiceInstance>> get() { 

      return Flux.defer(() -> {
                 List<ServiceInstance> result = ....
                 return Flux.just(result); 
      })
}

That is the actual fix.

String serviceName = getServiceId();
LOG.debug(() -> "serviceID : " + serviceName);

if (discoveryProperties.allNamespaces()) {
LOG.debug(() -> "discovering services in all namespaces");
List<V1Service> services = services(null, serviceName);
services.forEach(service -> addMappedService(mapper, result, service));
}
else if (!discoveryProperties.namespaces().isEmpty()) {
List<String> selectiveNamespaces = discoveryProperties.namespaces().stream().sorted().toList();
LOG.debug(() -> "discovering services in selective namespaces : " + selectiveNamespaces);
selectiveNamespaces.forEach(selectiveNamespace -> {
List<V1Service> services = services(selectiveNamespace, serviceName);
return Flux.defer(() -> {
List<ServiceInstance> result = new ArrayList<>();
String serviceName = getServiceId();
LOG.debug(() -> "serviceID : " + serviceName);

if (discoveryProperties.allNamespaces()) {
LOG.debug(() -> "discovering services in all namespaces");
List<V1Service> services = services(null, serviceName);
services.forEach(service -> addMappedService(mapper, result, service));
});
}
else {
String namespace = getApplicationNamespace(null, "loadbalancer-service", kubernetesNamespaceProvider);
LOG.debug(() -> "discovering services in namespace : " + namespace);
List<V1Service> services = services(namespace, serviceName);
services.forEach(service -> addMappedService(mapper, result, service));
}
}
else if (!discoveryProperties.namespaces().isEmpty()) {
List<String> selectiveNamespaces = discoveryProperties.namespaces().stream().sorted().toList();
LOG.debug(() -> "discovering services in selective namespaces : " + selectiveNamespaces);
selectiveNamespaces.forEach(selectiveNamespace -> {
List<V1Service> services = services(selectiveNamespace, serviceName);
services.forEach(service -> addMappedService(mapper, result, service));
});
}
else {
String namespace = getApplicationNamespace(null, "loadbalancer-service", kubernetesNamespaceProvider);
LOG.debug(() -> "discovering services in namespace : " + namespace);
List<V1Service> services = services(namespace, serviceName);
services.forEach(service -> addMappedService(mapper, result, service));
}

LOG.debug(() -> "found services : " + result);
return Flux.just(result);
LOG.debug(() -> "found services : " + result);
return Flux.just(result);
});
}

private void addMappedService(KubernetesServiceInstanceMapper<V1Service> mapper, List<ServiceInstance> services,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2013-present 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.kubernetes.client.loadbalancer.it;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

public static void main(String[] args) {
SpringApplication.run(App.class);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright 2013-present 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.kubernetes.client.loadbalancer.it;

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.client.WebClient;

@TestConfiguration
public class LoadBalancerConfiguration {

@Bean
@LoadBalanced
WebClient.Builder client() {
return WebClient.builder();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -25,20 +25,16 @@
import io.kubernetes.client.openapi.models.V1Endpoints;
import io.kubernetes.client.openapi.models.V1EndpointsBuilder;
import io.kubernetes.client.openapi.models.V1EndpointsList;
import io.kubernetes.client.openapi.models.V1EndpointsListBuilder;
import io.kubernetes.client.openapi.models.V1ListMetaBuilder;
import io.kubernetes.client.openapi.models.V1ObjectMetaBuilder;
import io.kubernetes.client.openapi.models.V1Service;
import io.kubernetes.client.openapi.models.V1ServiceBuilder;
import io.kubernetes.client.openapi.models.V1ServiceList;
import io.kubernetes.client.openapi.models.V1ServiceListBuilder;
import io.kubernetes.client.openapi.models.V1ServicePortBuilder;
import io.kubernetes.client.openapi.models.V1ServiceSpecBuilder;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.client.WebClient;

/**
* @author wind57
*/
Expand Down Expand Up @@ -142,24 +138,26 @@ public static void endpointsInNamespaceServiceMode(WireMockServer server, V1Endp
.willReturn(WireMock.aResponse().withBody(new JSON().serialize(endpointsList)).withStatus(200)));
}

@TestConfiguration
public static class LoadBalancerConfiguration {
public static void mockWatchers(WireMockServer wireMockServer) {
V1Service serviceA = Util.service("a", "service-a", 8888);

@Bean
@LoadBalanced
WebClient.Builder client() {
return WebClient.builder();
}
V1ServiceList serviceListA = new V1ServiceListBuilder()
.withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build())
.endMetadata()
.withItems(serviceA)
.build();

}
servicesInNamespaceServiceMode(wireMockServer, serviceListA, "a", "service-a");

@SpringBootApplication
public static class Configuration {
V1Endpoints endpointsA = Util.endpoints("a", "service-a", 8888, "127.0.0.1");

public static void main(String[] args) {
SpringApplication.run(Configuration.class);
}
V1EndpointsList endpointsListA = new V1EndpointsListBuilder()
.withNewMetadataLike(new V1ListMetaBuilder().withResourceVersion("0").build())
.endMetadata()
.withItems(endpointsA)
.build();

Util.endpointsInNamespaceServiceMode(wireMockServer, endpointsListA, "a", "service-a");
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
/*
* Copyright 2013-present 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.kubernetes.client.loadbalancer.it.mode.cache;

import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.util.ClientBuilder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import reactor.core.publisher.Mono;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.client.loadbalancer.reactive.ReactiveLoadBalancer;
import org.springframework.cloud.kubernetes.client.KubernetesClientUtils;
import org.springframework.cloud.kubernetes.client.loadbalancer.it.App;
import org.springframework.cloud.kubernetes.client.loadbalancer.it.Util;
import org.springframework.cloud.kubernetes.commons.loadbalancer.KubernetesServiceInstanceMapper;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.test.annotation.DirtiesContext;

import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mockStatic;

/**
* @author wind57
*/
@SpringBootTest(properties = { "spring.cloud.kubernetes.loadbalancer.mode=SERVICE",
"spring.main.cloud-platform=KUBERNETES", "spring.cloud.kubernetes.discovery.all-namespaces=false",
"spring.cloud.kubernetes.client.namespace=a", "spring.cloud.loadbalancer.cache.enabled=false" },
classes = App.class)
@DirtiesContext
class CacheDisabledTest {

private static final int SERVICE_PORT = 8888;

private static WireMockServer wireMockServer;

private static WireMockServer serviceAMockServer;

private static MockedStatic<KubernetesClientUtils> clientUtils;

@SuppressWarnings("rawtypes")
private static final MockedStatic<KubernetesServiceInstanceMapper> MOCKED_STATIC = Mockito
.mockStatic(KubernetesServiceInstanceMapper.class);

@Autowired
private LoadBalancerClientFactory loadBalancerClientFactory;

@BeforeAll
static void beforeAll() {

wireMockServer = new WireMockServer(options().dynamicPort());
wireMockServer.start();
WireMock.configureFor("localhost", wireMockServer.port());

Util.mockWatchers(wireMockServer);

serviceAMockServer = new WireMockServer(SERVICE_PORT);
serviceAMockServer.start();
WireMock.configureFor("localhost", SERVICE_PORT);

// we mock host creation so that it becomes something like : localhost:8888
// then wiremock can catch this request, and we can assert for the result
MOCKED_STATIC.when(() -> KubernetesServiceInstanceMapper.createHost("my-service", "a", "cluster.local"))
.thenReturn("localhost");

ApiClient client = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()).build();
// we need to not mock 'getApplicationNamespace'
clientUtils = mockStatic(KubernetesClientUtils.class, Mockito.CALLS_REAL_METHODS);
clientUtils.when(KubernetesClientUtils::kubernetesApiClient).thenReturn(client);
}

@AfterAll
static void afterAll() {
wireMockServer.stop();
serviceAMockServer.stop();
MOCKED_STATIC.close();
clientUtils.close();
}

/**
* <pre>
* - we disable caching via 'spring.cloud.loadbalancer.cache.enabled=false'
* - as such, two calls to : loadBalancer.choose() will both execute
* on the delegate itself, which we assert via 'wireMockServer.verify'
* </pre>
*/
@Test
void test() {

ReactiveLoadBalancer<ServiceInstance> loadBalancer = loadBalancerClientFactory.getInstance("service-a");
Response<ServiceInstance> firstResponse = Mono.from(loadBalancer.choose()).block();
assertThat(firstResponse.hasServer()).isTrue();

Response<ServiceInstance> secondResponse = Mono.from(loadBalancer.choose()).block();
assertThat(secondResponse.hasServer()).isTrue();

// called two times
wireMockServer.verify(WireMock.exactly(2), WireMock.getRequestedFor(
WireMock.urlEqualTo("/api/v1/namespaces/a/services?fieldSelector=metadata.name%3D" + "service-a")));

}

}
Loading
Loading