Initial commit

This commit is contained in:
spencergibb
2023-09-19 13:10:02 -04:00
parent 2e4d529f30
commit 8a57c69c88
1303 changed files with 8661 additions and 95772 deletions

View File

@@ -0,0 +1,113 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-kubernetes</artifactId>
<version>3.0.4-SNAPSHOT</version>
</parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-kubernetes-client-loadbalancer</artifactId>
<version>3.0.4-SNAPSHOT</version>
<description>Spring Cloud parent pom, managing plugins and dependencies for Spring
Cloud projects</description>
<url>https://cloud.spring.io/spring-cloud-kubernetes-client-loadbalancer</url>
<inceptionYear>2017</inceptionYear>
<organization>
<name>Pivotal Software, Inc.</name>
<url>https://www.spring.io</url>
</organization>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>https://www.apache.org/licenses/LICENSE-2.0.txt</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>dsyer</id>
<name>Dave Syer</name>
<email>dsyer at pivotal.io</email>
<organization>Pivotal Software, Inc.</organization>
<organizationUrl>https://www.spring.io</organizationUrl>
<roles>
<role>lead</role>
</roles>
</developer>
<developer>
<id>sgibb</id>
<name>Spencer Gibb</name>
<email>sgibb at pivotal.io</email>
<organization>Pivotal Software, Inc.</organization>
<organizationUrl>https://www.spring.io</organizationUrl>
<roles>
<role>lead</role>
</roles>
</developer>
<developer>
<id>mgrzejszczak</id>
<name>Marcin Grzejszczak</name>
<email>mgrzejszczak at pivotal.io</email>
<organization>Pivotal Software, Inc.</organization>
<organizationUrl>https://www.spring.io</organizationUrl>
<roles>
<role>developer</role>
</roles>
</developer>
<developer>
<id>rbaxter</id>
<name>Ryan Baxter</name>
<email>rbaxter at pivotal.io</email>
<organization>Pivotal Software, Inc.</organization>
<organizationUrl>https://www.spring.io</organizationUrl>
<roles>
<role>developer</role>
</roles>
</developer>
<developer>
<id>omaciaszeksharma</id>
<name>Olga Maciaszek-Sharma</name>
<email>omaciaszeksharma at pivotal.io</email>
<organization>Pivotal Software, Inc.</organization>
<organizationUrl>https://www.spring.io</organizationUrl>
<roles>
<role>developer</role>
</roles>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/spring-cloud/spring-cloud-kubernetes.git/spring-cloud-kubernetes-client-loadbalancer</connection>
<developerConnection>scm:git:ssh://git@github.com/spring-cloud/spring-cloud-kubernetes.git/spring-cloud-kubernetes-client-loadbalancer</developerConnection>
<url>https://github.com/spring-cloud/spring-cloud-kubernetes/spring-cloud-kubernetes-client-loadbalancer</url>
</scm>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>4.0.4-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-kubernetes-client-discovery</artifactId>
<version>3.0.4-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>3.0.7</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>3.0.7</version>
<scope>compile</scope>
<optional>true</optional>
</dependency>
</dependencies>
</project>

View File

@@ -1,62 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud-kubernetes</artifactId>
<groupId>org.springframework.cloud</groupId>
<version>3.1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>spring-cloud-kubernetes-client-loadbalancer</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-kubernetes-client-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8-standalone</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-kubernetes-test-support</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -1,45 +0,0 @@
/*
* Copyright 2013-2020 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;
import org.springframework.boot.autoconfigure.condition.ConditionalOnCloudPlatform;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.cloud.CloudPlatform;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.kubernetes.commons.discovery.KubernetesDiscoveryProperties;
import org.springframework.cloud.kubernetes.commons.loadbalancer.KubernetesLoadBalancerProperties;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Ryan Baxter
*/
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(KubernetesLoadBalancerProperties.class)
@ConditionalOnCloudPlatform(CloudPlatform.KUBERNETES)
@ConditionalOnProperty(value = "spring.cloud.kubernetes.loadbalancer.enabled", matchIfMissing = true)
@LoadBalancerClients(defaultConfiguration = KubernetesClientLoadBalancerClientConfiguration.class)
public class KubernetesClientLoadBalancerAutoConfiguration {
@Bean
KubernetesClientServiceInstanceMapper mapper(KubernetesLoadBalancerProperties properties,
KubernetesDiscoveryProperties discoveryProperties) {
return new KubernetesClientServiceInstanceMapper(properties, discoveryProperties);
}
}

View File

@@ -1,43 +0,0 @@
/*
* Copyright 2013-2020 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;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.kubernetes.commons.KubernetesNamespaceProvider;
import org.springframework.cloud.kubernetes.commons.discovery.KubernetesDiscoveryProperties;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
/**
* @author Ryan Baxter
*/
public class KubernetesClientLoadBalancerClientConfiguration {
@Bean
@ConditionalOnProperty(name = "spring.cloud.kubernetes.loadbalancer.mode", havingValue = "SERVICE")
ServiceInstanceListSupplier kubernetesServicesListSupplier(Environment environment, CoreV1Api coreV1Api,
KubernetesClientServiceInstanceMapper mapper, KubernetesDiscoveryProperties discoveryProperties,
KubernetesNamespaceProvider kubernetesNamespaceProvider, ConfigurableApplicationContext context) {
return ServiceInstanceListSupplier.builder().withBase(new KubernetesClientServicesListSupplier(environment,
mapper, discoveryProperties, coreV1Api, kubernetesNamespaceProvider)).withCaching().build(context);
}
}

View File

@@ -1,94 +0,0 @@
/*
* Copyright 2013-2020 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;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1Service;
import io.kubernetes.client.openapi.models.V1ServicePort;
import org.springframework.cloud.kubernetes.commons.discovery.DefaultKubernetesServiceInstance;
import org.springframework.cloud.kubernetes.commons.discovery.KubernetesDiscoveryProperties;
import org.springframework.cloud.kubernetes.commons.discovery.KubernetesServiceInstance;
import org.springframework.cloud.kubernetes.commons.loadbalancer.KubernetesLoadBalancerProperties;
import org.springframework.cloud.kubernetes.commons.loadbalancer.KubernetesServiceInstanceMapper;
import org.springframework.util.StringUtils;
/**
* @author Ryan Baxter
*/
public class KubernetesClientServiceInstanceMapper implements KubernetesServiceInstanceMapper<V1Service> {
private KubernetesLoadBalancerProperties properties;
private KubernetesDiscoveryProperties discoveryProperties;
public KubernetesClientServiceInstanceMapper(KubernetesLoadBalancerProperties properties,
KubernetesDiscoveryProperties discoveryProperties) {
this.properties = properties;
this.discoveryProperties = discoveryProperties;
}
@Override
public KubernetesServiceInstance map(V1Service service) {
final V1ObjectMeta meta = service.getMetadata();
final List<V1ServicePort> ports = service.getSpec().getPorts();
V1ServicePort port = null;
if (ports.size() == 1) {
port = ports.get(0);
}
else if (ports.size() > 1 && StringUtils.hasText(this.properties.getPortName())) {
Optional<V1ServicePort> optPort = ports.stream()
.filter(it -> properties.getPortName().endsWith(it.getName())).findAny();
if (optPort.isPresent()) {
port = optPort.get();
}
}
if (port == null) {
return null;
}
final String host = KubernetesServiceInstanceMapper.createHost(service.getMetadata().getName(),
service.getMetadata().getNamespace(), properties.getClusterDomain());
final boolean secure = KubernetesServiceInstanceMapper.isSecure(service.getMetadata().getLabels(),
service.getMetadata().getAnnotations(), port.getName(), port.getPort());
return new DefaultKubernetesServiceInstance(meta.getUid(), meta.getName(), host, port.getPort(),
getServiceMetadata(service), secure);
}
private Map<String, String> getServiceMetadata(V1Service service) {
final Map<String, String> serviceMetadata = new HashMap<>();
KubernetesDiscoveryProperties.Metadata metadataProps = this.discoveryProperties.metadata();
if (metadataProps.addLabels()) {
Map<String, String> labelMetadata = KubernetesServiceInstanceMapper
.getMapWithPrefixedKeys(service.getMetadata().getLabels(), metadataProps.labelsPrefix());
serviceMetadata.putAll(labelMetadata);
}
if (metadataProps.addAnnotations()) {
Map<String, String> annotationMetadata = KubernetesServiceInstanceMapper
.getMapWithPrefixedKeys(service.getMetadata().getAnnotations(), metadataProps.annotationsPrefix());
serviceMetadata.putAll(annotationMetadata);
}
return serviceMetadata;
}
}

View File

@@ -1,86 +0,0 @@
/*
* Copyright 2013-2020 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;
import java.util.ArrayList;
import java.util.List;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1Service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Flux;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.kubernetes.commons.KubernetesClientProperties;
import org.springframework.cloud.kubernetes.commons.KubernetesNamespaceProvider;
import org.springframework.cloud.kubernetes.commons.discovery.KubernetesDiscoveryProperties;
import org.springframework.cloud.kubernetes.commons.loadbalancer.KubernetesServiceInstanceMapper;
import org.springframework.cloud.kubernetes.commons.loadbalancer.KubernetesServicesListSupplier;
import org.springframework.core.env.Environment;
/**
* @author Ryan Baxter
*/
public class KubernetesClientServicesListSupplier extends KubernetesServicesListSupplier {
private static final Log LOG = LogFactory.getLog(KubernetesClientServicesListSupplier.class);
private CoreV1Api coreV1Api;
private KubernetesClientProperties kubernetesClientProperties;
private KubernetesNamespaceProvider kubernetesNamespaceProvider;
public KubernetesClientServicesListSupplier(Environment environment, KubernetesServiceInstanceMapper mapper,
KubernetesDiscoveryProperties discoveryProperties, CoreV1Api coreV1Api,
KubernetesNamespaceProvider kubernetesNamespaceProvider) {
super(environment, mapper, discoveryProperties);
this.coreV1Api = coreV1Api;
this.kubernetesNamespaceProvider = kubernetesNamespaceProvider;
}
private String getNamespace() {
return kubernetesNamespaceProvider != null ? kubernetesNamespaceProvider.getNamespace()
: kubernetesClientProperties.namespace();
}
@Override
public Flux<List<ServiceInstance>> get() {
LOG.info("Getting services with id " + this.getServiceId());
List<ServiceInstance> result = new ArrayList<>();
List<V1Service> services;
try {
if (discoveryProperties.allNamespaces()) {
services = coreV1Api.listServiceForAllNamespaces(null, null, "metadata.name=" + this.getServiceId(),
null, null, null, null, null, null, null).getItems();
}
else {
services = coreV1Api.listNamespacedService(getNamespace(), null, null, null,
"metadata.name=" + this.getServiceId(), null, null, null, null, null, null).getItems();
}
services.forEach(service -> result.add(mapper.map(service)));
}
catch (ApiException e) {
LOG.warn("Error retrieving service with name " + this.getServiceId(), e);
}
LOG.info("Returning services: " + result);
return Flux.defer(() -> Flux.just(result));
}
}

View File

@@ -1 +0,0 @@
org.springframework.cloud.kubernetes.client.loadbalancer.KubernetesClientLoadBalancerAutoConfiguration

View File

@@ -1,113 +0,0 @@
/*
* Copyright 2013-2020 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;
import java.io.IOException;
import java.util.Collections;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.util.ClientBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerRequest;
import org.springframework.cloud.kubernetes.client.discovery.KubernetesInformerDiscoveryClient;
import org.springframework.cloud.kubernetes.commons.KubernetesNamespaceProvider;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.http.client.MockClientHttpResponse;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Ryan Baxter
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = KubernetesClientLoadBalancerPodModeTests.App.class)
public class KubernetesClientLoadBalancerPodModeTests {
@Autowired
private RestTemplate restTemplate;
@Test
public void testLoadBalancer() {
String resp = restTemplate.getForObject("http://servicea-wiremock", String.class);
assertThat(resp).isEqualTo("hello");
}
@SpringBootApplication
static class App {
@Bean
public ApiClient apiClient() {
return new ClientBuilder().build();
}
@Bean
public BlockingLoadBalancerClient blockingLoadBalancerClient() {
BlockingLoadBalancerClient client = mock(BlockingLoadBalancerClient.class);
try {
ClientHttpResponse response = new MockClientHttpResponse("hello".getBytes(), HttpStatus.OK);
when(client.execute(eq("servicea-wiremock"), any(LoadBalancerRequest.class))).thenReturn(response);
when(client.execute(eq("servicea-wiremock"), any(ServiceInstance.class),
any(LoadBalancerRequest.class))).thenReturn(response);
}
catch (IOException e) {
e.printStackTrace();
}
return client;
}
@Bean
public KubernetesNamespaceProvider kubernetesNamespaceProvider() {
KubernetesNamespaceProvider provider = mock(KubernetesNamespaceProvider.class);
when(provider.getNamespace()).thenReturn("test");
return provider;
}
@Bean
public KubernetesInformerDiscoveryClient kubernetesInformerDiscoveryClient() {
KubernetesInformerDiscoveryClient client = mock(KubernetesInformerDiscoveryClient.class);
ServiceInstance instance = new DefaultServiceInstance("servicea-wiremock1", "servicea-wiremock", "fake",
8888, false);
given(client.getInstances(eq("servicea-wiremock"))).willReturn(Collections.singletonList(instance));
return client;
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplateBuilder().build();
}
}
}

View File

@@ -1,148 +0,0 @@
/*
* Copyright 2013-2020 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;
import java.io.IOException;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1ObjectMetaBuilder;
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 io.kubernetes.client.util.ClientBuilder;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.client.loadbalancer.LoadBalancerRequest;
import org.springframework.cloud.kubernetes.client.discovery.KubernetesInformerDiscoveryClient;
import org.springframework.cloud.kubernetes.commons.KubernetesNamespaceProvider;
import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.http.client.MockClientHttpResponse;
import org.springframework.web.client.RestTemplate;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Ryan Baxter
*/
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = KubernetesClientLoadBalancerServiceModeTests.App.class,
properties = { "spring.cloud.kubernetes.loadbalancer.mode=SERVICE" })
public class KubernetesClientLoadBalancerServiceModeTests {
private static final V1ServiceList SERVICE_LIST = new V1ServiceListBuilder()
.addToItems(
new V1ServiceBuilder()
.withMetadata(new V1ObjectMetaBuilder().withName("servicea-wiremock")
.withNamespace("default").withResourceVersion("1").addToLabels("beta", "true")
.addToAnnotations("org.springframework.cloud", "true").withUid("0").build())
.withSpec(new V1ServiceSpecBuilder().withClusterIP("10.96.0.1").withSessionAffinity("None")
.withType("ClusterIP")
.addToPorts(new V1ServicePortBuilder().withPort(80).withName("http")
.withProtocol("TCP").withNewTargetPort(8080).build())
.build())
.build())
.build();
@Autowired
private RestTemplate restTemplate;
@Test
public void testLoadBalancer() {
String resp = restTemplate.getForObject("http://servicea-wiremock", String.class);
assertThat(resp).isEqualTo("hello");
}
@SpringBootApplication
static class App {
@Bean
public ApiClient apiClient() {
return new ClientBuilder().build();
}
@Bean
public CoreV1Api coreV1Api() {
CoreV1Api coreV1Api = mock(CoreV1Api.class);
try {
when(coreV1Api.listNamespacedService(eq("default"), eq(null), eq(null), eq(null),
eq("metadata.name=servicea-wiremock"), eq(null), eq(null), eq(null), eq(null), eq(null),
eq(null))).thenReturn(SERVICE_LIST);
}
catch (ApiException e) {
e.printStackTrace();
}
return coreV1Api;
}
@Bean
public BlockingLoadBalancerClient blockingLoadBalancerClient() {
BlockingLoadBalancerClient client = mock(BlockingLoadBalancerClient.class);
try {
ClientHttpResponse response = new MockClientHttpResponse("hello".getBytes(), HttpStatus.OK);
when(client.execute(eq("servicea-wiremock"), any(LoadBalancerRequest.class))).thenReturn(response);
when(client.execute(eq("servicea-wiremock"), any(ServiceInstance.class),
any(LoadBalancerRequest.class))).thenReturn(response);
}
catch (IOException e) {
e.printStackTrace();
}
return client;
}
@Bean
public KubernetesInformerDiscoveryClient kubernetesInformerDiscoveryClient() {
// Mock this so the real implementation does not try to connect to the K8S API
// Server
KubernetesInformerDiscoveryClient client = mock(KubernetesInformerDiscoveryClient.class);
Mockito.when(client.getOrder()).thenReturn(0);
return client;
}
@Bean
public KubernetesNamespaceProvider kubernetesNamespaceProvider() {
KubernetesNamespaceProvider provider = mock(KubernetesNamespaceProvider.class);
when(provider.getNamespace()).thenReturn("test");
return provider;
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplateBuilder().build();
}
}
}

View File

@@ -1,86 +0,0 @@
/*
* Copyright 2013-2020 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;
import java.util.HashMap;
import java.util.Map;
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.V1ServicePortBuilder;
import io.kubernetes.client.openapi.models.V1ServiceSpecBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.cloud.kubernetes.commons.discovery.DefaultKubernetesServiceInstance;
import org.springframework.cloud.kubernetes.commons.discovery.KubernetesDiscoveryProperties;
import org.springframework.cloud.kubernetes.commons.discovery.KubernetesServiceInstance;
import org.springframework.cloud.kubernetes.commons.loadbalancer.KubernetesLoadBalancerProperties;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author Ryan Baxter
*/
class KubernetesClientServiceInstanceMapperTests {
@Test
void basicMap() {
KubernetesLoadBalancerProperties loadBalancerProperties = new KubernetesLoadBalancerProperties();
KubernetesClientServiceInstanceMapper mapper = new KubernetesClientServiceInstanceMapper(loadBalancerProperties,
KubernetesDiscoveryProperties.DEFAULT);
V1Service service = new V1ServiceBuilder()
.withMetadata(new V1ObjectMetaBuilder().withName("database").withUid("0").withResourceVersion("0")
.withNamespace("default").addToAnnotations("org.springframework.cloud", "true")
.addToLabels("beta", "true").build())
.withSpec(new V1ServiceSpecBuilder()
.addToPorts(new V1ServicePortBuilder().withPort(80).withName("http").build()).build())
.build();
KubernetesServiceInstance serviceInstance = mapper.map(service);
Map<String, String> metadata = new HashMap<>();
metadata.put("org.springframework.cloud", "true");
metadata.put("beta", "true");
DefaultKubernetesServiceInstance result = new DefaultKubernetesServiceInstance("0", "database",
"database.default.svc.cluster.local", 80, metadata, false);
assertThat(serviceInstance).isEqualTo(result);
}
@Test
void multiportMap() {
KubernetesLoadBalancerProperties loadBalancerProperties = new KubernetesLoadBalancerProperties();
loadBalancerProperties.setPortName("https");
KubernetesClientServiceInstanceMapper mapper = new KubernetesClientServiceInstanceMapper(loadBalancerProperties,
KubernetesDiscoveryProperties.DEFAULT);
V1Service service = new V1ServiceBuilder()
.withMetadata(new V1ObjectMetaBuilder().withName("database").withUid("0").withResourceVersion("0")
.withNamespace("default").build())
.withSpec(new V1ServiceSpecBuilder()
.addToPorts(new V1ServicePortBuilder().withPort(80).withName("http").build(),
new V1ServicePortBuilder().withPort(443).withName("https").build())
.build())
.build();
KubernetesServiceInstance serviceInstance = mapper.map(service);
DefaultKubernetesServiceInstance result = new DefaultKubernetesServiceInstance("0", "database",
"database.default.svc.cluster.local", 443, new HashMap(), true);
assertThat(serviceInstance).isEqualTo(result);
}
}

View File

@@ -1,176 +0,0 @@
/*
* Copyright 2013-2020 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;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import io.kubernetes.client.openapi.ApiClient;
import io.kubernetes.client.openapi.Configuration;
import io.kubernetes.client.openapi.JSON;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.V1ObjectMetaBuilder;
import io.kubernetes.client.openapi.models.V1ServiceBuilder;
import io.kubernetes.client.openapi.models.V1ServiceList;
import io.kubernetes.client.openapi.models.V1ServicePortBuilder;
import io.kubernetes.client.openapi.models.V1ServiceSpecBuilder;
import io.kubernetes.client.util.ClientBuilder;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.test.StepVerifier;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.kubernetes.commons.KubernetesNamespaceProvider;
import org.springframework.cloud.kubernetes.commons.discovery.DefaultKubernetesServiceInstance;
import org.springframework.cloud.kubernetes.commons.discovery.KubernetesDiscoveryProperties;
import org.springframework.cloud.kubernetes.commons.loadbalancer.KubernetesLoadBalancerProperties;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.mock.env.MockEnvironment;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Ryan Baxter
*/
class KubernetesClientServicesListSupplierTests {
private static final V1ServiceList SERVICE_LIST = new V1ServiceList().addItemsItem(new V1ServiceBuilder()
.withMetadata(new V1ObjectMetaBuilder().withName("service1").withNamespace("default")
.withResourceVersion("1").addToLabels("beta", "true")
.addToAnnotations("org.springframework.cloud", "true").withUid("0").build())
.withSpec(new V1ServiceSpecBuilder()
.addToPorts(new V1ServicePortBuilder().withPort(80).withName("http").build()).build())
.build());
private static final V1ServiceList SERVICE_LIST_ALL_NAMESPACE = new V1ServiceList()
.addItemsItem(new V1ServiceBuilder()
.withMetadata(new V1ObjectMetaBuilder().withName("service1").withNamespace("default")
.withResourceVersion("1").addToLabels("beta", "true")
.addToAnnotations("org.springframework.cloud", "true").withUid("0").build())
.withSpec(new V1ServiceSpecBuilder()
.addToPorts(new V1ServicePortBuilder().withPort(80).withName("http").build()).build())
.build())
.addItemsItem(new V1ServiceBuilder()
.withMetadata(new V1ObjectMetaBuilder().withName("service1").withNamespace("test")
.withResourceVersion("1").withUid("1").build())
.withSpec(new V1ServiceSpecBuilder()
.addToPorts(new V1ServicePortBuilder().withPort(80).withName("http").build(),
new V1ServicePortBuilder().withPort(443).withName("https").build())
.build())
.build());
private static WireMockServer wireMockServer;
@BeforeAll
public static void setup() {
wireMockServer = new WireMockServer(options().dynamicPort());
wireMockServer.start();
WireMock.configureFor("localhost", wireMockServer.port());
ApiClient client = new ClientBuilder().setBasePath("http://localhost:" + wireMockServer.port()).build();
client.setDebugging(true);
Configuration.setDefaultApiClient(client);
}
@AfterAll
public static void after() {
wireMockServer.stop();
}
@AfterEach
public void afterEach() {
WireMock.reset();
}
@Test
void getList() {
MockEnvironment env = new MockEnvironment();
env.setProperty(LoadBalancerClientFactory.PROPERTY_NAME, "service1");
KubernetesNamespaceProvider kubernetesNamespaceProvider = mock(KubernetesNamespaceProvider.class);
when(kubernetesNamespaceProvider.getNamespace()).thenReturn("default");
CoreV1Api coreV1Api = new CoreV1Api();
KubernetesClientServiceInstanceMapper mapper = new KubernetesClientServiceInstanceMapper(
new KubernetesLoadBalancerProperties(), KubernetesDiscoveryProperties.DEFAULT);
KubernetesClientServicesListSupplier listSupplier = new KubernetesClientServicesListSupplier(env, mapper,
KubernetesDiscoveryProperties.DEFAULT, coreV1Api, kubernetesNamespaceProvider);
stubFor(get(urlMatching("^/api/v1/namespaces/default/services.*"))
.willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(SERVICE_LIST))));
Flux<List<ServiceInstance>> instances = listSupplier.get();
Map<String, String> metadata = new HashMap<>();
metadata.put("org.springframework.cloud", "true");
metadata.put("beta", "true");
DefaultKubernetesServiceInstance service1 = new DefaultKubernetesServiceInstance("0", "service1",
"service1.default.svc.cluster.local", 80, metadata, false);
List<ServiceInstance> services = new ArrayList<>();
services.add(service1);
StepVerifier.create(instances).expectNext(services).verifyComplete();
}
@Test
void getListAllNamespaces() {
MockEnvironment env = new MockEnvironment();
env.setProperty(LoadBalancerClientFactory.PROPERTY_NAME, "service1");
KubernetesNamespaceProvider kubernetesNamespaceProvider = mock(KubernetesNamespaceProvider.class);
when(kubernetesNamespaceProvider.getNamespace()).thenReturn("default");
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, true,
Set.of(), true, 60, false, null, Set.of(), Map.of(), null,
KubernetesDiscoveryProperties.Metadata.DEFAULT, 0, false);
CoreV1Api coreV1Api = new CoreV1Api();
KubernetesClientServiceInstanceMapper mapper = new KubernetesClientServiceInstanceMapper(
new KubernetesLoadBalancerProperties(), kubernetesDiscoveryProperties);
KubernetesClientServicesListSupplier listSupplier = new KubernetesClientServicesListSupplier(env, mapper,
kubernetesDiscoveryProperties, coreV1Api, kubernetesNamespaceProvider);
stubFor(get(urlMatching("^/api/v1/services.*"))
.willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(SERVICE_LIST_ALL_NAMESPACE))));
Flux<List<ServiceInstance>> instances = listSupplier.get();
Map<String, String> metadata = new HashMap<>();
metadata.put("org.springframework.cloud", "true");
metadata.put("beta", "true");
DefaultKubernetesServiceInstance service1 = new DefaultKubernetesServiceInstance("0", "service1",
"service1.default.svc.cluster.local", 80, metadata, false);
DefaultKubernetesServiceInstance service2 = new DefaultKubernetesServiceInstance("1", "service1",
"service1.test.svc.cluster.local", 80, new HashMap<>(), false);
List<ServiceInstance> services = new ArrayList<>();
services.add(service1);
services.add(service2);
StepVerifier.create(instances).expectNext(services).verifyComplete();
}
}