Move KubernetesDiscoveryProperties to record (#1096)

This commit is contained in:
erabii
2022-10-19 16:55:22 +03:00
committed by GitHub
parent 02b004b13a
commit 85d90ffada
25 changed files with 441 additions and 518 deletions

View File

@@ -94,11 +94,11 @@ public class KubernetesInformerDiscoveryClient implements DiscoveryClient, Initi
public List<ServiceInstance> getInstances(String serviceId) {
Assert.notNull(serviceId, "[Assertion failed] - the object argument must not be null");
if (!StringUtils.hasText(namespace) && !properties.isAllNamespaces()) {
if (!StringUtils.hasText(namespace) && !properties.allNamespaces()) {
log.warn("Namespace is null or empty, this may cause issues looking up services");
}
V1Service service = properties.isAllNamespaces() ? this.serviceLister.list().stream()
V1Service service = properties.allNamespaces() ? this.serviceLister.list().stream()
.filter(svc -> serviceId.equals(svc.getMetadata().getName())).findFirst().orElse(null)
: this.serviceLister.namespace(this.namespace).get(serviceId);
if (service == null || !matchServiceLabels(service)) {
@@ -107,20 +107,20 @@ public class KubernetesInformerDiscoveryClient implements DiscoveryClient, Initi
}
Map<String, String> svcMetadata = new HashMap<>();
if (this.properties.getMetadata() != null) {
if (this.properties.getMetadata().addLabels()) {
if (this.properties.metadata() != null) {
if (this.properties.metadata().addLabels()) {
if (service.getMetadata() != null && service.getMetadata().getLabels() != null) {
String labelPrefix = this.properties.getMetadata().labelsPrefix() != null
? this.properties.getMetadata().labelsPrefix() : "";
String labelPrefix = this.properties.metadata().labelsPrefix() != null
? this.properties.metadata().labelsPrefix() : "";
service.getMetadata().getLabels().entrySet().stream()
.filter(e -> e.getKey().startsWith(labelPrefix))
.forEach(e -> svcMetadata.put(e.getKey(), e.getValue()));
}
}
if (this.properties.getMetadata().addAnnotations()) {
if (this.properties.metadata().addAnnotations()) {
if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) {
String annotationPrefix = this.properties.getMetadata().annotationsPrefix() != null
? this.properties.getMetadata().annotationsPrefix() : "";
String annotationPrefix = this.properties.metadata().annotationsPrefix() != null
? this.properties.metadata().annotationsPrefix() : "";
service.getMetadata().getAnnotations().entrySet().stream()
.filter(e -> e.getKey().startsWith(annotationPrefix))
.forEach(e -> svcMetadata.put(e.getKey(), e.getValue()));
@@ -140,13 +140,13 @@ public class KubernetesInformerDiscoveryClient implements DiscoveryClient, Initi
discoveredPrimaryPortName = Optional
.ofNullable(service.getMetadata().getLabels().get(PRIMARY_PORT_NAME_LABEL_KEY));
}
final String primaryPortName = discoveredPrimaryPortName.orElse(this.properties.getPrimaryPortName());
final String primaryPortName = discoveredPrimaryPortName.orElse(this.properties.primaryPortName());
return ep.getSubsets().stream().filter(subset -> subset.getPorts() != null && subset.getPorts().size() > 0) // safeguard
.flatMap(subset -> {
Map<String, String> metadata = new HashMap<>(svcMetadata);
List<V1EndpointPort> endpointPorts = subset.getPorts();
if (this.properties.getMetadata() != null && this.properties.getMetadata().addPorts()) {
if (this.properties.metadata() != null && this.properties.metadata().addPorts()) {
endpointPorts.forEach(
p -> metadata.put(StringUtils.hasText(p.getName()) ? p.getName() : UNSET_PORT_NAME,
Integer.toString(p.getPort())));
@@ -155,7 +155,7 @@ public class KubernetesInformerDiscoveryClient implements DiscoveryClient, Initi
if (addresses == null) {
addresses = new ArrayList<>();
}
if (this.properties.isIncludeNotReadyAddresses()
if (this.properties.includeNotReadyAddresses()
&& !CollectionUtils.isEmpty(subset.getNotReadyAddresses())) {
addresses.addAll(subset.getNotReadyAddresses());
}
@@ -205,7 +205,7 @@ public class KubernetesInformerDiscoveryClient implements DiscoveryClient, Initi
@Override
public List<String> getServices() {
List<V1Service> services = this.properties.isAllNamespaces() ? this.serviceLister.list()
List<V1Service> services = this.properties.allNamespaces() ? this.serviceLister.list()
: this.serviceLister.namespace(this.namespace).list();
return services.stream().filter(this::matchServiceLabels).map(s -> s.getMetadata().getName())
.collect(Collectors.toList());
@@ -214,12 +214,11 @@ public class KubernetesInformerDiscoveryClient implements DiscoveryClient, Initi
@Override
public void afterPropertiesSet() throws Exception {
this.sharedInformerFactory.startAllRegisteredInformers();
if (!Wait.poll(Duration.ofSeconds(1), Duration.ofSeconds(this.properties.getCacheLoadingTimeoutSeconds()),
() -> {
log.info("Waiting for the cache of informers to be fully loaded..");
return this.informersReadyFunc.get();
})) {
if (this.properties.isWaitCacheReady()) {
if (!Wait.poll(Duration.ofSeconds(1), Duration.ofSeconds(this.properties.cacheLoadingTimeoutSeconds()), () -> {
log.info("Waiting for the cache of informers to be fully loaded..");
return this.informersReadyFunc.get();
})) {
if (this.properties.waitCacheReady()) {
throw new IllegalStateException(
"Timeout waiting for informers cache to be ready, is the kubernetes service up?");
}
@@ -235,8 +234,8 @@ public class KubernetesInformerDiscoveryClient implements DiscoveryClient, Initi
private boolean matchServiceLabels(V1Service service) {
if (log.isDebugEnabled()) {
log.debug("Kubernetes Service Label Properties:");
if (this.properties.getServiceLabels() != null) {
this.properties.getServiceLabels().forEach((key, value) -> log.debug(key + ":" + value));
if (this.properties.serviceLabels() != null) {
this.properties.serviceLabels().forEach((key, value) -> log.debug(key + ":" + value));
}
log.debug("Service " + service.getMetadata().getName() + " labels:");
if (service.getMetadata() != null && service.getMetadata().getLabels() != null) {
@@ -247,13 +246,13 @@ public class KubernetesInformerDiscoveryClient implements DiscoveryClient, Initi
if (service.getMetadata() == null) {
return false;
}
if (properties.getServiceLabels() == null || properties.getServiceLabels().isEmpty()) {
if (properties.serviceLabels() == null || properties.serviceLabels().isEmpty()) {
return true;
}
return properties.getServiceLabels().keySet().stream()
return properties.serviceLabels().keySet().stream()
.allMatch(k -> service.getMetadata().getLabels() != null
&& service.getMetadata().getLabels().containsKey(k)
&& service.getMetadata().getLabels().get(k).equals(properties.getServiceLabels().get(k)));
&& service.getMetadata().getLabels().get(k).equals(properties.serviceLabels().get(k)));
}
}

View File

@@ -18,6 +18,7 @@ package org.springframework.cloud.kubernetes.client.discovery;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import io.kubernetes.client.informer.SharedInformerFactory;
import io.kubernetes.client.informer.cache.Cache;
@@ -39,9 +40,6 @@ import org.springframework.cloud.kubernetes.commons.discovery.DefaultKubernetesS
import org.springframework.cloud.kubernetes.commons.discovery.KubernetesDiscoveryProperties;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class KubernetesInformerDiscoveryClientTests {
@@ -49,9 +47,6 @@ public class KubernetesInformerDiscoveryClientTests {
@Mock
private SharedInformerFactory sharedInformerFactory;
@Mock
private KubernetesDiscoveryProperties kubernetesDiscoveryProperties;
private static final V1Service testService1 = new V1Service()
.metadata(new V1ObjectMeta().name("test-svc-1").namespace("namespace1"))
.spec(new V1ServiceSpec().loadBalancerIP("1.1.1.1")).status(new V1ServiceStatus());
@@ -112,8 +107,8 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpointWithUnsetPortName);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(true);
when(kubernetesDiscoveryProperties.getMetadata()).thenReturn(KubernetesDiscoveryProperties.Metadata.DEFAULT);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, true,
true, 60, false, null, Set.of(), Map.of(), null, KubernetesDiscoveryProperties.Metadata.DEFAULT, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
@@ -129,15 +124,12 @@ public class KubernetesInformerDiscoveryClientTests {
public void testDiscoveryGetServicesAllNamespaceShouldWork() {
Lister<V1Service> serviceLister = setupServiceLister(testService1, testService2);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(true);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("",
sharedInformerFactory, serviceLister, null, null, null, kubernetesDiscoveryProperties);
sharedInformerFactory, serviceLister, null, null, null, KubernetesDiscoveryProperties.DEFAULT);
assertThat(discoveryClient.getServices().toArray()).containsOnly(testService1.getMetadata().getName(),
testService2.getMetadata().getName());
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
}
@Test
@@ -148,14 +140,14 @@ public class KubernetesInformerDiscoveryClientTests {
labels.put("k8s", "true");
labels.put("spring", "true");
when(kubernetesDiscoveryProperties.getServiceLabels()).thenReturn(labels);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, true,
true, 60, false, null, Set.of(), labels, null, null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("",
sharedInformerFactory, serviceLister, null, null, null, kubernetesDiscoveryProperties);
assertThat(discoveryClient.getServices().toArray()).containsOnly(testService3.getMetadata().getName());
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
}
@Test
@@ -167,8 +159,8 @@ public class KubernetesInformerDiscoveryClientTests {
labels.put("k8s", "true");
labels.put("spring", "true");
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(true);
when(kubernetesDiscoveryProperties.getServiceLabels()).thenReturn(labels);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, true,
true, 60, false, null, Set.of(), labels, null, null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
@@ -183,14 +175,11 @@ public class KubernetesInformerDiscoveryClientTests {
public void testDiscoveryGetServicesOneNamespaceShouldWork() {
Lister<V1Service> serviceLister = setupServiceLister(testService1, testService2);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, null, null, null, kubernetesDiscoveryProperties);
sharedInformerFactory, serviceLister, null, null, null, KubernetesDiscoveryProperties.DEFAULT);
assertThat(discoveryClient.getServices().toArray()).containsOnly(testService1.getMetadata().getName());
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
}
@Test
@@ -198,16 +187,14 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1, testService2);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpoints1);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(true);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, true,
true, 60, false, null, Set.of(), null, null, null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance("",
"test-svc-1", "2.2.2.2", 8080, new HashMap<>(), false, "namespace1", null));
verify(kubernetesDiscoveryProperties, times(2)).isAllNamespaces();
verify(kubernetesDiscoveryProperties, times(1)).getPrimaryPortName();
}
@Test
@@ -215,15 +202,14 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1, testService2);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpoints1);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, false,
true, 60, false, null, Set.of(), null, null, null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance("",
"test-svc-1", "2.2.2.2", 8080, new HashMap<>(), false, "namespace1", null));
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
verify(kubernetesDiscoveryProperties, times(1)).getPrimaryPortName();
}
@Test
@@ -231,15 +217,11 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpointWithoutReadyAddresses);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
sharedInformerFactory, serviceLister, endpointsLister, null, null,
KubernetesDiscoveryProperties.DEFAULT);
assertThat(discoveryClient.getInstances("test-svc-1")).isEmpty();
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
verify(kubernetesDiscoveryProperties, times(1)).getPrimaryPortName();
verify(kubernetesDiscoveryProperties, times(1)).isIncludeNotReadyAddresses();
}
@Test
@@ -247,17 +229,14 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpointWithoutReadyAddresses);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
when(kubernetesDiscoveryProperties.isIncludeNotReadyAddresses()).thenReturn(true);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, false,
true, 60, true, null, Set.of(), null, null, null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance("",
"test-svc-1", "2.2.2.2", 8080, new HashMap<>(), false, "namespace1", null));
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
verify(kubernetesDiscoveryProperties, times(1)).getPrimaryPortName();
verify(kubernetesDiscoveryProperties, times(1)).isIncludeNotReadyAddresses();
}
@Test
@@ -265,13 +244,11 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister();
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
sharedInformerFactory, serviceLister, endpointsLister, null, null,
KubernetesDiscoveryProperties.DEFAULT);
assertThat(discoveryClient.getInstances("test-svc-1")).isEmpty();
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
}
@Test
@@ -279,13 +256,11 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpointWithoutPorts);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
sharedInformerFactory, serviceLister, endpointsLister, null, null,
KubernetesDiscoveryProperties.DEFAULT);
assertThat(discoveryClient.getInstances("test-svc-1")).isEmpty();
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
}
@Test
@@ -295,17 +270,14 @@ public class KubernetesInformerDiscoveryClientTests {
.namespace("namespace1").putLabelsItem("primary-port-name", "https")));
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpointWithMultiplePorts);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, false,
true, 60, false, null, Set.of(), null, null, null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance("",
"test-svc-1", "1.1.1.1", 443, new HashMap<>(), false, "namespace1", null));
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
verify(kubernetesDiscoveryProperties, times(1)).getPrimaryPortName();
verify(kubernetesDiscoveryProperties, times(1)).isIncludeNotReadyAddresses();
// Reset metadata
testService1.metadata(oldMetadata);
}
@@ -317,16 +289,14 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(
testEndpointWithMultiplePortsWithoutSupportedPortNames);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, false,
true, 60, false, null, Set.of(), null, null, null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance("",
"test-svc-1", "1.1.1.1", 80, new HashMap<>(), false, "namespace1", null));
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
verify(kubernetesDiscoveryProperties, times(1)).getPrimaryPortName();
// Reset testService1 metadata
testService1.metadata(oldMetadata);
}
@@ -335,17 +305,14 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpointWithMultiplePorts);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
when(kubernetesDiscoveryProperties.getPrimaryPortName()).thenReturn("https");
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, false,
true, 60, false, null, Set.of(), null, "https", null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance("",
"test-svc-1", "1.1.1.1", 443, new HashMap<>(), false, "namespace1", null));
verify(kubernetesDiscoveryProperties, times(1)).getPrimaryPortName();
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
verify(kubernetesDiscoveryProperties, times(1)).isIncludeNotReadyAddresses();
}
@Test
@@ -354,16 +321,14 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(
testEndpointWithMultiplePortsWithoutSupportedPortNames);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
when(kubernetesDiscoveryProperties.getPrimaryPortName()).thenReturn("oops");
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, false,
true, 60, false, null, Set.of(), null, "oops", null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance("",
"test-svc-1", "1.1.1.1", 80, new HashMap<>(), false, "namespace1", null));
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
verify(kubernetesDiscoveryProperties, times(1)).getPrimaryPortName();
}
@Test
@@ -371,15 +336,14 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpointWithMultiplePorts);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, false,
true, 60, false, null, Set.of(), null, null, null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance("",
"test-svc-1", "1.1.1.1", 443, new HashMap<>(), false, "namespace1", null));
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
verify(kubernetesDiscoveryProperties, times(1)).getPrimaryPortName();
}
@Test
@@ -387,15 +351,14 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpointWithMultiplePortsWithoutHttps);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, false,
true, 60, false, null, Set.of(), null, null, null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance("",
"test-svc-1", "1.1.1.1", 80, new HashMap<>(), false, "namespace1", null));
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
verify(kubernetesDiscoveryProperties, times(1)).getPrimaryPortName();
}
@Test
@@ -404,15 +367,14 @@ public class KubernetesInformerDiscoveryClientTests {
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(
testEndpointWithMultiplePortsWithoutSupportedPortNames);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, false,
true, 60, false, null, Set.of(), null, null, null, 0);
KubernetesInformerDiscoveryClient discoveryClient = new KubernetesInformerDiscoveryClient("namespace1",
sharedInformerFactory, serviceLister, endpointsLister, null, null, kubernetesDiscoveryProperties);
assertThat(discoveryClient.getInstances("test-svc-1")).containsOnly(new DefaultKubernetesServiceInstance("",
"test-svc-1", "1.1.1.1", 80, new HashMap<>(), false, "namespace1", null));
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
verify(kubernetesDiscoveryProperties, times(1)).getPrimaryPortName();
}
private Lister<V1Service> setupServiceLister(V1Service... services) {

View File

@@ -17,6 +17,7 @@
package org.springframework.cloud.kubernetes.client.discovery.reactive;
import java.util.HashMap;
import java.util.Set;
import io.kubernetes.client.informer.SharedInformerFactory;
import io.kubernetes.client.informer.cache.Cache;
@@ -41,8 +42,6 @@ import org.springframework.cloud.kubernetes.commons.discovery.KubernetesDiscover
import org.springframework.mock.env.MockEnvironment;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
@@ -54,9 +53,6 @@ public class KubernetesInformerReactiveDiscoveryClientTests {
@Mock
private SharedInformerFactory sharedInformerFactory;
@Mock
private KubernetesDiscoveryProperties kubernetesDiscoveryProperties;
private static final V1Service testService1 = new V1Service()
.metadata(new V1ObjectMeta().name("test-svc-1").namespace("namespace1"))
.spec(new V1ServiceSpec().loadBalancerIP("1.1.1.1")).status(new V1ServiceStatus());
@@ -74,35 +70,29 @@ public class KubernetesInformerReactiveDiscoveryClientTests {
public void testDiscoveryGetServicesAllNamespaceShouldWork() {
Lister<V1Service> serviceLister = setupServiceLister(testService1, testService2);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(true);
KubernetesInformerReactiveDiscoveryClient discoveryClient = new KubernetesInformerReactiveDiscoveryClient(
new KubernetesNamespaceProvider(new MockEnvironment()), sharedInformerFactory, serviceLister, null,
null, null, kubernetesDiscoveryProperties);
null, null, KubernetesDiscoveryProperties.DEFAULT);
StepVerifier.create(discoveryClient.getServices())
.expectNext(testService1.getMetadata().getName(), testService2.getMetadata().getName()).expectComplete()
.verify();
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
}
@Test
public void testDiscoveryGetServicesOneNamespaceShouldWork() {
Lister<V1Service> serviceLister = setupServiceLister(testService1, testService2);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesNamespaceProvider kubernetesNamespaceProvider = mock(KubernetesNamespaceProvider.class);
when(kubernetesNamespaceProvider.getNamespace()).thenReturn("namespace1");
KubernetesInformerReactiveDiscoveryClient discoveryClient = new KubernetesInformerReactiveDiscoveryClient(
kubernetesNamespaceProvider, sharedInformerFactory, serviceLister, null, null, null,
kubernetesDiscoveryProperties);
KubernetesDiscoveryProperties.DEFAULT);
StepVerifier.create(discoveryClient.getServices()).expectNext(testService1.getMetadata().getName())
.expectComplete().verify();
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
}
@Test
@@ -110,7 +100,8 @@ public class KubernetesInformerReactiveDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1, testService2);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpoints1);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(true);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, true,
true, 60, false, null, Set.of(), null, null, null, 0);
KubernetesInformerReactiveDiscoveryClient discoveryClient = new KubernetesInformerReactiveDiscoveryClient(
new KubernetesNamespaceProvider(new MockEnvironment()), sharedInformerFactory, serviceLister,
@@ -121,7 +112,6 @@ public class KubernetesInformerReactiveDiscoveryClientTests {
"test-svc-1", "2.2.2.2", 8080, new HashMap<>(), false, "namespace1", null))
.expectComplete().verify();
verify(kubernetesDiscoveryProperties, times(2)).isAllNamespaces();
}
@Test
@@ -129,7 +119,9 @@ public class KubernetesInformerReactiveDiscoveryClientTests {
Lister<V1Service> serviceLister = setupServiceLister(testService1, testService2);
Lister<V1Endpoints> endpointsLister = setupEndpointsLister(testEndpoints1);
when(kubernetesDiscoveryProperties.isAllNamespaces()).thenReturn(false);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, false,
true, 60, false, null, Set.of(), null, null, null, 0);
KubernetesNamespaceProvider kubernetesNamespaceProvider = mock(KubernetesNamespaceProvider.class);
when(kubernetesNamespaceProvider.getNamespace()).thenReturn("namespace1");
KubernetesInformerReactiveDiscoveryClient discoveryClient = new KubernetesInformerReactiveDiscoveryClient(
@@ -141,7 +133,6 @@ public class KubernetesInformerReactiveDiscoveryClientTests {
"test-svc-1", "2.2.2.2", 8080, new HashMap<>(), false, "namespace1", null))
.expectComplete().verify();
verify(kubernetesDiscoveryProperties, times(1)).isAllNamespaces();
}
private Lister<V1Service> setupServiceLister(V1Service... services) {

View File

@@ -76,7 +76,7 @@ public class KubernetesClientServiceInstanceMapper implements KubernetesServiceI
private Map<String, String> getServiceMetadata(V1Service service) {
final Map<String, String> serviceMetadata = new HashMap<>();
KubernetesDiscoveryProperties.Metadata metadataProps = this.discoveryProperties.getMetadata();
KubernetesDiscoveryProperties.Metadata metadataProps = this.discoveryProperties.metadata();
if (metadataProps.addLabels()) {
Map<String, String> labelMetadata = KubernetesServiceInstanceMapper
.getMapWithPrefixedKeys(service.getMetadata().getLabels(), metadataProps.labelsPrefix());

View File

@@ -66,7 +66,7 @@ public class KubernetesClientServicesListSupplier extends KubernetesServicesList
List<ServiceInstance> result = new ArrayList<>();
List<V1Service> services = null;
try {
if (discoveryProperties.isAllNamespaces()) {
if (discoveryProperties.allNamespaces()) {
services = coreV1Api.listServiceForAllNamespaces(null, null, "metadata.name=" + this.getServiceId(),
null, null, null, null, null, null, null).getItems();
}

View File

@@ -41,9 +41,8 @@ class KubernetesClientServiceInstanceMapperTests {
@Test
void basicMap() {
KubernetesLoadBalancerProperties loadBalancerProperties = new KubernetesLoadBalancerProperties();
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties();
KubernetesClientServiceInstanceMapper mapper = new KubernetesClientServiceInstanceMapper(loadBalancerProperties,
kubernetesDiscoveryProperties);
KubernetesDiscoveryProperties.DEFAULT);
V1Service service = new V1ServiceBuilder()
.withMetadata(new V1ObjectMetaBuilder().withName("database").withUid("0").withResourceVersion("0")
@@ -66,9 +65,8 @@ class KubernetesClientServiceInstanceMapperTests {
void multiportMap() {
KubernetesLoadBalancerProperties loadBalancerProperties = new KubernetesLoadBalancerProperties();
loadBalancerProperties.setPortName("https");
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties();
KubernetesClientServiceInstanceMapper mapper = new KubernetesClientServiceInstanceMapper(loadBalancerProperties,
kubernetesDiscoveryProperties);
KubernetesDiscoveryProperties.DEFAULT);
V1Service service = new V1ServiceBuilder()
.withMetadata(new V1ObjectMetaBuilder().withName("database").withUid("0").withResourceVersion("0")

View File

@@ -20,6 +20,7 @@ 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;
@@ -116,12 +117,11 @@ class KubernetesClientServicesListSupplierTests {
env.setProperty(LoadBalancerClientFactory.PROPERTY_NAME, "service1");
KubernetesNamespaceProvider kubernetesNamespaceProvider = mock(KubernetesNamespaceProvider.class);
when(kubernetesNamespaceProvider.getNamespace()).thenReturn("default");
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties();
CoreV1Api coreV1Api = new CoreV1Api();
KubernetesClientServiceInstanceMapper mapper = new KubernetesClientServiceInstanceMapper(
new KubernetesLoadBalancerProperties(), kubernetesDiscoveryProperties);
new KubernetesLoadBalancerProperties(), KubernetesDiscoveryProperties.DEFAULT);
KubernetesClientServicesListSupplier listSupplier = new KubernetesClientServicesListSupplier(env, mapper,
kubernetesDiscoveryProperties, coreV1Api, kubernetesNamespaceProvider);
KubernetesDiscoveryProperties.DEFAULT, coreV1Api, kubernetesNamespaceProvider);
stubFor(get(urlMatching("^/api/v1/namespaces/default/services.*"))
.willReturn(aResponse().withStatus(200).withBody(new JSON().serialize(SERVICE_LIST))));
@@ -145,8 +145,8 @@ class KubernetesClientServicesListSupplierTests {
env.setProperty(LoadBalancerClientFactory.PROPERTY_NAME, "service1");
KubernetesNamespaceProvider kubernetesNamespaceProvider = mock(KubernetesNamespaceProvider.class);
when(kubernetesNamespaceProvider.getNamespace()).thenReturn("default");
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties();
kubernetesDiscoveryProperties.setAllNamespaces(true);
KubernetesDiscoveryProperties kubernetesDiscoveryProperties = new KubernetesDiscoveryProperties(true, true,
true, 60, false, null, Set.of(), Map.of(), null, KubernetesDiscoveryProperties.Metadata.DEFAULT, 0);
CoreV1Api coreV1Api = new CoreV1Api();
KubernetesClientServiceInstanceMapper mapper = new KubernetesClientServiceInstanceMapper(
new KubernetesLoadBalancerProperties(), kubernetesDiscoveryProperties);

View File

@@ -16,164 +16,49 @@
package org.springframework.cloud.kubernetes.commons.discovery;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.bind.DefaultValue;
import org.springframework.core.style.ToStringCreator;
import static org.springframework.cloud.client.discovery.DiscoveryClient.DEFAULT_ORDER;
/**
* @param enabled if kubernetes discovery is enabled
* @param allNamespaces if discover is enabled for all namespaces
* @param waitCacheReady wait for the discovery cache (service and endpoints) to be fully
* loaded, otherwise aborts the application on starting
* @param cacheLoadingTimeoutSeconds timeout for initializing discovery cache, will abort
* the application if exceeded.
* @param includeNotReadyAddresses include as discovered if endpoint addresses is not
* marked with 'ready' by kubernetes
* @param filter SpEL expression to filter services after they have been retrieved from
* the Kubernetes API server.
* @param knownSecurePorts set of known secure ports
* @param serviceLabels if set, then only the services matching these labels will be
* fetched from the Kubernetes API server.
* @param primaryPortName If set then the port with a given name is used as primary when
* multiple ports are defined for a service.
*/
// @formatter:off
@ConfigurationProperties("spring.cloud.kubernetes.discovery")
public class KubernetesDiscoveryProperties {
/** If Kubernetes Discovery is enabled. */
private boolean enabled = true;
/** If discovering all namespaces. */
private boolean allNamespaces = false;
/*
* If wait for the discovery cache (service and endpoints) to be fully loaded,
* otherwise aborts the application on starting.
*/
private boolean waitCacheReady = true;
public record KubernetesDiscoveryProperties(
@DefaultValue("true") boolean enabled, boolean allNamespaces,
@DefaultValue("true") boolean waitCacheReady,
@DefaultValue("60") long cacheLoadingTimeoutSeconds,
boolean includeNotReadyAddresses, String filter,
@DefaultValue({"443", "8443"}) Set<Integer> knownSecurePorts,
@DefaultValue Map<String, String> serviceLabels, String primaryPortName,
@DefaultValue Metadata metadata,
@DefaultValue("" + DEFAULT_ORDER) int order) {
// @formatter:on
/**
* Timeout for initializing discovery cache, will abort the application if exceeded.
**/
private long cacheLoadingTimeoutSeconds = 60;
/**
* If endpoint addresses not marked 'ready' by the k8s api server should be
* discovered.
* Default instance.
*/
private boolean includeNotReadyAddresses = false;
/**
* SpEL expression to filter services AFTER they have been retrieved from the
* Kubernetes API server.
*/
private String filter;
/** Set the port numbers that are considered secure and use HTTPS. */
private Set<Integer> knownSecurePorts = Stream.of(443, 8443).collect(Collectors.toCollection(HashSet::new));
/**
* If set, then only the services matching these labels will be fetched from the
* Kubernetes API server.
*/
private Map<String, String> serviceLabels = new HashMap<>();
/**
* If set then the port with a given name is used as primary when multiple ports are
* defined for a service.
*/
private String primaryPortName;
private Metadata metadata = Metadata.DEFAULT;
private int order = DEFAULT_ORDER;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getFilter() {
return this.filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
public Set<Integer> getKnownSecurePorts() {
return this.knownSecurePorts;
}
public void setKnownSecurePorts(Set<Integer> knownSecurePorts) {
this.knownSecurePorts = knownSecurePorts;
}
public Map<String, String> getServiceLabels() {
return this.serviceLabels;
}
public void setServiceLabels(Map<String, String> serviceLabels) {
this.serviceLabels = serviceLabels;
}
public String getPrimaryPortName() {
return primaryPortName;
}
public void setPrimaryPortName(String primaryPortName) {
this.primaryPortName = primaryPortName;
}
public Metadata getMetadata() {
return this.metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public boolean isAllNamespaces() {
return allNamespaces;
}
public void setAllNamespaces(boolean allNamespaces) {
this.allNamespaces = allNamespaces;
}
public boolean isIncludeNotReadyAddresses() {
return includeNotReadyAddresses;
}
public void setIncludeNotReadyAddresses(boolean includeNotReadyAddresses) {
this.includeNotReadyAddresses = includeNotReadyAddresses;
}
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
public boolean isWaitCacheReady() {
return waitCacheReady;
}
public void setWaitCacheReady(boolean waitCacheReady) {
this.waitCacheReady = waitCacheReady;
}
public long getCacheLoadingTimeoutSeconds() {
return cacheLoadingTimeoutSeconds;
}
public void setCacheLoadingTimeoutSeconds(long cacheLoadingTimeoutSeconds) {
this.cacheLoadingTimeoutSeconds = cacheLoadingTimeoutSeconds;
}
@Override
public String toString() {
return new ToStringCreator(this).append("enabled", this.enabled).append("filter", this.filter)
.append("knownSecurePorts", this.knownSecurePorts).append("serviceLabels", this.serviceLabels)
.append("metadata", this.metadata).toString();
}
public static final KubernetesDiscoveryProperties DEFAULT = new KubernetesDiscoveryProperties(true, false, true, 60,
false, null, Set.of(), Map.of(), null, KubernetesDiscoveryProperties.Metadata.DEFAULT, 0);
/**
* @param addLabels include labels as metadata

View File

@@ -48,9 +48,9 @@ class KubernetesDiscoveryPropertiesMetadataTests {
.run(context -> {
KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class);
assertThat(props).isNotNull();
assertThat(props.getMetadata().labelsPrefix()).isEqualTo("labelsPrefix");
assertThat(props.getMetadata().addPorts()).isTrue();
assertThat(props.getMetadata().portsPrefix()).isEqualTo("port.");
assertThat(props.metadata().labelsPrefix()).isEqualTo("labelsPrefix");
assertThat(props.metadata().addPorts()).isTrue();
assertThat(props.metadata().portsPrefix()).isEqualTo("port.");
});
}

View File

@@ -0,0 +1,102 @@
/*
* Copyright 2013-2022 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.commons.discovery;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.springframework.context.annotation.Configuration;
import static org.assertj.core.api.Assertions.assertThat;
/**
* @author wind57
*/
class KubernetesDiscoveryPropertiesTests {
@Test
void testBindingWhenNoPropertiesProvided() {
new ApplicationContextRunner().withUserConfiguration(KubernetesDiscoveryPropertiesMetadataTests.Config.class)
.run(context -> {
KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class);
assertThat(props).isNotNull();
assertThat(props.metadata().labelsPrefix()).isNull();
assertThat(props.metadata().addPorts()).isTrue();
assertThat(props.metadata().portsPrefix()).isEqualTo("port.");
assertThat(props.enabled()).isTrue();
assertThat(props.allNamespaces()).isFalse();
assertThat(props.waitCacheReady()).isTrue();
assertThat(props.cacheLoadingTimeoutSeconds()).isEqualTo(60);
assertThat(props.includeNotReadyAddresses()).isFalse();
assertThat(props.filter()).isNull();
assertThat(props.knownSecurePorts()).isEqualTo(Set.of(443, 8443));
assertThat(props.serviceLabels()).isEmpty();
assertThat(props.primaryPortName()).isNull();
assertThat(props.order()).isZero();
});
}
@Test
void testBindingWhenSomePropertiesProvided() {
new ApplicationContextRunner().withUserConfiguration(KubernetesDiscoveryPropertiesMetadataTests.Config.class)
.withPropertyValues("spring.cloud.kubernetes.discovery.filter=some-filter",
"spring.cloud.kubernetes.discovery.knownSecurePorts[0]=222",
"spring.cloud.kubernetes.discovery.metadata.labelsPrefix=labelsPrefix")
.run(context -> {
KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class);
assertThat(props).isNotNull();
assertThat(props.metadata().labelsPrefix()).isEqualTo("labelsPrefix");
assertThat(props.metadata().addPorts()).isTrue();
assertThat(props.metadata().portsPrefix()).isEqualTo("port.");
assertThat(props.enabled()).isTrue();
assertThat(props.allNamespaces()).isFalse();
assertThat(props.waitCacheReady()).isTrue();
assertThat(props.cacheLoadingTimeoutSeconds()).isEqualTo(60);
assertThat(props.includeNotReadyAddresses()).isFalse();
assertThat(props.filter()).isEqualTo("some-filter");
assertThat(props.knownSecurePorts()).isEqualTo(Set.of(222));
assertThat(props.serviceLabels()).isEmpty();
assertThat(props.primaryPortName()).isNull();
assertThat(props.order()).isZero();
});
}
// when we do not specify metadata, @DefaultValue is going to be picked up
@Test
void metadataSetToNotNull() {
new ApplicationContextRunner().withUserConfiguration(KubernetesDiscoveryPropertiesMetadataTests.Config.class)
.withPropertyValues("spring.cloud.kubernetes.discovery.filter=some-filter").run(context -> {
KubernetesDiscoveryProperties props = context.getBean(KubernetesDiscoveryProperties.class);
assertThat(props).isNotNull();
assertThat(props.metadata().labelsPrefix()).isNull();
assertThat(props.metadata().addPorts()).isTrue();
assertThat(props.metadata().portsPrefix()).isEqualTo("port.");
});
}
@Configuration
@EnableConfigurationProperties(KubernetesDiscoveryProperties.class)
static class Config {
}
}

View File

@@ -68,10 +68,10 @@ public class KubernetesCatalogWatch implements ApplicationEventPublisherAware {
// not all pods participate in the service discovery. only those that have
// endpoints.
List<Endpoints> endpoints = this.properties.isAllNamespaces()
? this.kubernetesClient.endpoints().inAnyNamespace().withLabels(properties.getServiceLabels())
.list().getItems()
: this.kubernetesClient.endpoints().withLabels(properties.getServiceLabels()).list().getItems();
List<Endpoints> endpoints = this.properties.allNamespaces()
? this.kubernetesClient.endpoints().inAnyNamespace().withLabels(properties.serviceLabels()).list()
.getItems()
: this.kubernetesClient.endpoints().withLabels(properties.serviceLabels()).list().getItems();
List<String> endpointsPodNames = endpoints.stream().map(Endpoints::getSubsets).filter(Objects::nonNull)
.flatMap(Collection::stream).map(EndpointSubset::getAddresses).filter(Objects::nonNull)
.flatMap(Collection::stream).map(EndpointAddress::getTargetRef).filter(Objects::nonNull)

View File

@@ -121,11 +121,11 @@ public class KubernetesDiscoveryClient implements DiscoveryClient {
}
public List<Endpoints> getEndPointsList(String serviceId) {
return this.properties.isAllNamespaces()
return this.properties.allNamespaces()
? this.client.endpoints().inAnyNamespace().withField("metadata.name", serviceId)
.withLabels(properties.getServiceLabels()).list().getItems()
: this.client.endpoints().withField("metadata.name", serviceId)
.withLabels(properties.getServiceLabels()).list().getItems();
.withLabels(properties.serviceLabels()).list().getItems()
: this.client.endpoints().withField("metadata.name", serviceId).withLabels(properties.serviceLabels())
.list().getItems();
}
private List<ServiceInstance> getNamespaceServiceInstances(EndpointSubsetNS es, String serviceId) {
@@ -135,9 +135,9 @@ public class KubernetesDiscoveryClient implements DiscoveryClient {
if (!subsets.isEmpty()) {
final Service service = this.client.services().inNamespace(namespace).withName(serviceId).get();
final Map<String, String> serviceMetadata = this.getServiceMetadata(service);
KubernetesDiscoveryProperties.Metadata metadataProps = this.properties.getMetadata();
KubernetesDiscoveryProperties.Metadata metadataProps = this.properties.metadata();
String primaryPortName = this.properties.getPrimaryPortName();
String primaryPortName = this.properties.primaryPortName();
Map<String, String> labels = service.getMetadata().getLabels();
if (labels != null && labels.containsKey(PRIMARY_PORT_NAME_LABEL_KEY)) {
primaryPortName = labels.get(PRIMARY_PORT_NAME_LABEL_KEY);
@@ -158,14 +158,13 @@ public class KubernetesDiscoveryClient implements DiscoveryClient {
endpointMetadata.putAll(portMetadata);
}
if (this.properties.isAllNamespaces()) {
if (this.properties.allNamespaces()) {
endpointMetadata.put(NAMESPACE_METADATA_KEY, namespace);
}
List<EndpointAddress> addresses = s.getAddresses();
if (this.properties.isIncludeNotReadyAddresses()
&& !CollectionUtils.isEmpty(s.getNotReadyAddresses())) {
if (this.properties.includeNotReadyAddresses() && !CollectionUtils.isEmpty(s.getNotReadyAddresses())) {
if (addresses == null) {
addresses = new ArrayList<>();
}
@@ -192,7 +191,7 @@ public class KubernetesDiscoveryClient implements DiscoveryClient {
private Map<String, String> getServiceMetadata(Service service) {
final Map<String, String> serviceMetadata = new HashMap<>();
KubernetesDiscoveryProperties.Metadata metadataProps = this.properties.getMetadata();
KubernetesDiscoveryProperties.Metadata metadataProps = this.properties.metadata();
if (metadataProps.addLabels()) {
Map<String, String> labelMetadata = getMapWithPrefixedKeys(service.getMetadata().getLabels(),
metadataProps.labelsPrefix());
@@ -279,7 +278,7 @@ public class KubernetesDiscoveryClient implements DiscoveryClient {
@Override
public List<String> getServices() {
String spelExpression = this.properties.getFilter();
String spelExpression = this.properties.filter();
Predicate<Service> filteredServices;
if (spelExpression == null || spelExpression.isEmpty()) {
filteredServices = (Service instance) -> true;
@@ -304,7 +303,7 @@ public class KubernetesDiscoveryClient implements DiscoveryClient {
@Override
public int getOrder() {
return this.properties.getOrder();
return this.properties.order();
}
}

View File

@@ -56,8 +56,8 @@ public class KubernetesDiscoveryClientAutoConfiguration {
@Bean
public KubernetesClientServicesFunction servicesFunction(KubernetesDiscoveryProperties properties) {
if (properties.getServiceLabels().isEmpty()) {
if (properties.isAllNamespaces()) {
if (properties.serviceLabels().isEmpty()) {
if (properties.allNamespaces()) {
return (client) -> client.services().inAnyNamespace();
}
else {
@@ -65,11 +65,11 @@ public class KubernetesDiscoveryClientAutoConfiguration {
}
}
else {
if (properties.isAllNamespaces()) {
return (client) -> client.services().inAnyNamespace().withLabels(properties.getServiceLabels());
if (properties.allNamespaces()) {
return (client) -> client.services().inAnyNamespace().withLabels(properties.serviceLabels());
}
else {
return (client) -> client.services().withLabels(properties.getServiceLabels());
return (client) -> client.services().withLabels(properties.serviceLabels());
}
}
}

View File

@@ -64,7 +64,7 @@ class ServicePortSecureResolver {
return true;
}
if (port != null && properties.getKnownSecurePorts().contains(port)) {
if (port != null && properties.knownSecurePorts().contains(port)) {
logEntry(serviceName, port, "port is known to be a https port");
return true;
}

View File

@@ -34,8 +34,8 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.cloud.client.discovery.event.HeartbeatEvent;
@@ -55,14 +55,10 @@ import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class KubernetesCatalogWatchTest {
@Mock
private KubernetesDiscoveryProperties properties;
private static final KubernetesClient CLIENT = Mockito.mock(KubernetesClient.class);
@Mock
private KubernetesClient kubernetesClient;
@Mock
private KubernetesDiscoveryProperties kubernetesDiscoveryProperties;
private final KubernetesCatalogWatch kubernetesCatalogWatch = new KubernetesCatalogWatch(CLIENT,
KubernetesDiscoveryProperties.DEFAULT);
@Mock
private ApplicationEventPublisher applicationEventPublisher;
@@ -73,12 +69,9 @@ public class KubernetesCatalogWatchTest {
@Captor
private ArgumentCaptor<HeartbeatEvent> heartbeatEventArgumentCaptor;
@InjectMocks
private KubernetesCatalogWatch underTest;
@Before
public void setUp() throws Exception {
this.underTest.setApplicationEventPublisher(this.applicationEventPublisher);
kubernetesCatalogWatch.setApplicationEventPublisher(this.applicationEventPublisher);
}
@Test
@@ -86,12 +79,12 @@ public class KubernetesCatalogWatchTest {
when(this.endpointsOperation.list())
.thenReturn(createSingleEndpointEndpointListByPodName("api-pod", "other-pod"))
.thenReturn(createSingleEndpointEndpointListByPodName("other-pod", "api-pod"));
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
// second execution on shuffleServices
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
@@ -101,14 +94,13 @@ public class KubernetesCatalogWatchTest {
when(this.endpointsOperation.list())
.thenReturn(createSingleEndpointEndpointListByPodName("api-pod", "other-pod"))
.thenReturn(createSingleEndpointEndpointListByPodName("other-pod", "api-pod"));
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace().withLabels(anyMap()))
.thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
// second execution on shuffleServices
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
@@ -118,12 +110,12 @@ public class KubernetesCatalogWatchTest {
when(this.endpointsOperation.list())
.thenReturn(createEndpointsListByServiceName("api-service", "other-service"))
.thenReturn(createEndpointsListByServiceName("other-service", "api-service"));
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
// second execution on shuffleServices
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
@@ -133,14 +125,13 @@ public class KubernetesCatalogWatchTest {
when(this.endpointsOperation.list())
.thenReturn(createEndpointsListByServiceName("api-service", "other-service"))
.thenReturn(createEndpointsListByServiceName("other-service", "api-service"));
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace().withLabels(anyMap()))
.thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
// second execution on shuffleServices
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
@@ -149,10 +140,10 @@ public class KubernetesCatalogWatchTest {
public void testEventBody() throws Exception {
when(this.endpointsOperation.list())
.thenReturn(createSingleEndpointEndpointListByPodName("api-pod", "other-pod"));
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(this.heartbeatEventArgumentCaptor.capture());
@@ -167,12 +158,11 @@ public class KubernetesCatalogWatchTest {
public void testEventBodyAllNamespaces() throws Exception {
when(this.endpointsOperation.list())
.thenReturn(createSingleEndpointEndpointListByPodName("api-pod", "other-pod"));
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace().withLabels(anyMap()))
.thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(this.heartbeatEventArgumentCaptor.capture());
@@ -189,12 +179,12 @@ public class KubernetesCatalogWatchTest {
EndpointsList endpoints = createSingleEndpointEndpointListWithoutSubsets();
when(this.endpointsOperation.list()).thenReturn(endpoints);
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
// second execution on shuffleServices
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
@@ -205,14 +195,13 @@ public class KubernetesCatalogWatchTest {
EndpointsList endpoints = createSingleEndpointEndpointListWithoutSubsets();
when(this.endpointsOperation.list()).thenReturn(endpoints);
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace().withLabels(anyMap()))
.thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
// second execution on shuffleServices
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
@@ -224,12 +213,12 @@ public class KubernetesCatalogWatchTest {
endpoints.getItems().get(0).getSubsets().get(0).setAddresses(null);
when(this.endpointsOperation.list()).thenReturn(endpoints);
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
// second execution on shuffleServices
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
@@ -241,14 +230,13 @@ public class KubernetesCatalogWatchTest {
endpoints.getItems().get(0).getSubsets().get(0).setAddresses(null);
when(this.endpointsOperation.list()).thenReturn(endpoints);
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace().withLabels(anyMap()))
.thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
// second execution on shuffleServices
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
@@ -260,12 +248,12 @@ public class KubernetesCatalogWatchTest {
endpoints.getItems().get(0).getSubsets().get(0).getAddresses().get(0).setTargetRef(null);
when(this.endpointsOperation.list()).thenReturn(endpoints);
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
// second execution on shuffleServices
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}
@@ -277,14 +265,13 @@ public class KubernetesCatalogWatchTest {
endpoints.getItems().get(0).getSubsets().get(0).getAddresses().get(0).setTargetRef(null);
when(this.endpointsOperation.list()).thenReturn(endpoints);
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(this.kubernetesClient.endpoints().inAnyNamespace().withLabels(anyMap()))
.thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints().inAnyNamespace().withLabels(anyMap())).thenReturn(this.endpointsOperation);
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
// second execution on shuffleServices
this.underTest.catalogServicesWatch();
kubernetesCatalogWatch.catalogServicesWatch();
verify(this.applicationEventPublisher).publishEvent(any(HeartbeatEvent.class));
}

View File

@@ -20,6 +20,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.fabric8.kubernetes.api.model.EndpointPort;
import io.fabric8.kubernetes.api.model.EndpointPortBuilder;
@@ -40,8 +41,8 @@ import io.fabric8.kubernetes.client.dsl.ServiceResource;
import org.assertj.core.util.Strings;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.cloud.client.ServiceInstance;
@@ -59,14 +60,7 @@ import static org.springframework.cloud.kubernetes.commons.discovery.KubernetesD
@RunWith(MockitoJUnitRunner.class)
public class KubernetesDiscoveryClientFilterMetadataTest {
@Mock
private KubernetesClient kubernetesClient;
@Mock
private KubernetesDiscoveryProperties properties;
@Mock
private ServicePortSecureResolver isServicePortSecureResolver;
private static final KubernetesClient CLIENT = Mockito.mock(KubernetesClient.class);
@Mock
private MixedOperation<Service, ServiceList, ServiceResource<Service>> serviceOperation;
@@ -77,21 +71,18 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
@Mock
private ServiceResource<Service> serviceResource;
@Mock
private Resource<Endpoints> endpointsResource;
@Mock
FilterWatchListDeletable<Endpoints, EndpointsList> filter;
@InjectMocks
private KubernetesDiscoveryClient underTest;
@Test
public void testAllExtraMetadataDisabled() {
final String serviceId = "s";
Metadata metadata = new Metadata(false, null, false, null, false, null);
when(this.properties.getMetadata()).thenReturn(metadata);
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false, null,
Set.of(), Map.of(), null, metadata, 0);
KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(CLIENT, properties, a -> null);
setupServiceWithLabelsAndAnnotationsAndPorts(serviceId, "ns", new HashMap<String, String>() {
{
@@ -108,7 +99,7 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
}
});
final List<ServiceInstance> instances = this.underTest.getInstances(serviceId);
final List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
assertThat(instances).hasSize(1);
assertThat(instances.get(0).getMetadata()).isEmpty();
}
@@ -118,7 +109,10 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
final String serviceId = "s";
Metadata metadata = new Metadata(true, null, false, null, false, null);
when(this.properties.getMetadata()).thenReturn(metadata);
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false, null,
Set.of(), Map.of(), null, metadata, 0);
KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(CLIENT, properties, a -> null);
setupServiceWithLabelsAndAnnotationsAndPorts(serviceId, "ns", new HashMap<String, String>() {
{
@@ -136,7 +130,7 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
}
});
final List<ServiceInstance> instances = this.underTest.getInstances(serviceId);
final List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
assertThat(instances).hasSize(1);
assertThat(instances.get(0).getMetadata()).containsOnly(entry("l1", "v1"), entry("l2", "v2"));
}
@@ -146,7 +140,10 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
final String serviceId = "s";
Metadata metadata = new Metadata(true, "l_", false, null, false, null);
when(this.properties.getMetadata()).thenReturn(metadata);
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false, null,
Set.of(), Map.of(), null, metadata, 0);
KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(CLIENT, properties, a -> null);
setupServiceWithLabelsAndAnnotationsAndPorts(serviceId, "ns", new HashMap<String, String>() {
{
@@ -164,7 +161,7 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
}
});
final List<ServiceInstance> instances = this.underTest.getInstances(serviceId);
final List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
assertThat(instances).hasSize(1);
assertThat(instances.get(0).getMetadata()).containsOnly(entry("l_l1", "v1"), entry("l_l2", "v2"));
}
@@ -174,7 +171,10 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
final String serviceId = "s";
Metadata metadata = new Metadata(false, null, true, null, false, null);
when(this.properties.getMetadata()).thenReturn(metadata);
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false, null,
Set.of(), Map.of(), null, metadata, 0);
KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(CLIENT, properties, a -> null);
setupServiceWithLabelsAndAnnotationsAndPorts(serviceId, "ns", new HashMap<String, String>() {
{
@@ -192,7 +192,7 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
}
});
final List<ServiceInstance> instances = this.underTest.getInstances(serviceId);
final List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
assertThat(instances).hasSize(1);
assertThat(instances.get(0).getMetadata()).containsOnly(entry("a1", "v1"), entry("a2", "v2"));
}
@@ -202,7 +202,10 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
final String serviceId = "s";
Metadata metadata = new Metadata(false, null, true, "a_", false, null);
when(this.properties.getMetadata()).thenReturn(metadata);
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false, null,
Set.of(), Map.of(), null, metadata, 0);
KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(CLIENT, properties, a -> null);
setupServiceWithLabelsAndAnnotationsAndPorts(serviceId, "ns", new HashMap<String, String>() {
{
@@ -220,7 +223,7 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
}
});
final List<ServiceInstance> instances = this.underTest.getInstances(serviceId);
final List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
assertThat(instances).hasSize(1);
assertThat(instances.get(0).getMetadata()).containsOnly(entry("a_a1", "v1"), entry("a_a2", "v2"));
}
@@ -230,7 +233,10 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
final String serviceId = "s";
Metadata metadata = new Metadata(false, null, false, null, true, null);
when(this.properties.getMetadata()).thenReturn(metadata);
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false, null,
Set.of(), Map.of(), null, metadata, 0);
KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(CLIENT, properties, a -> null);
setupServiceWithLabelsAndAnnotationsAndPorts(serviceId, "ns", new HashMap<String, String>() {
{
@@ -248,7 +254,7 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
}
});
final List<ServiceInstance> instances = this.underTest.getInstances(serviceId);
final List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
assertThat(instances).hasSize(1);
assertThat(instances.get(0).getMetadata()).containsOnly(entry("http", "80"));
}
@@ -258,7 +264,10 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
final String serviceId = "s";
Metadata metadata = new Metadata(false, null, false, null, true, "p_");
when(this.properties.getMetadata()).thenReturn(metadata);
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false, null,
Set.of(), Map.of(), null, metadata, 0);
KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(CLIENT, properties, a -> null);
setupServiceWithLabelsAndAnnotationsAndPorts(serviceId, "ns", new HashMap<String, String>() {
{
@@ -276,7 +285,7 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
}
});
final List<ServiceInstance> instances = this.underTest.getInstances(serviceId);
final List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
assertThat(instances).hasSize(1);
assertThat(instances.get(0).getMetadata()).containsOnly(entry("p_http", "80"));
}
@@ -286,7 +295,10 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
final String serviceId = "s";
Metadata metadata = new Metadata(true, "l_", true, "a_", true, "p_");
when(this.properties.getMetadata()).thenReturn(metadata);
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false, null,
Set.of(), Map.of(), null, metadata, 0);
KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(CLIENT, properties, a -> null);
setupServiceWithLabelsAndAnnotationsAndPorts(serviceId, "ns", new HashMap<String, String>() {
{
@@ -304,7 +316,7 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
}
});
final List<ServiceInstance> instances = this.underTest.getInstances(serviceId);
final List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);
assertThat(instances).hasSize(1);
assertThat(instances.get(0).getMetadata()).containsOnly(entry("a_a1", "an1"), entry("a_a2", "an2"),
entry("l_l1", "la1"), entry("p_http", "80"));
@@ -317,8 +329,8 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
.build();
when(this.serviceOperation.withName(serviceId)).thenReturn(this.serviceResource);
when(this.serviceResource.get()).thenReturn(service);
when(this.kubernetesClient.services()).thenReturn(this.serviceOperation);
when(this.kubernetesClient.services().inNamespace(anyString())).thenReturn(this.serviceOperation);
when(CLIENT.services()).thenReturn(this.serviceOperation);
when(CLIENT.services().inNamespace(anyString())).thenReturn(this.serviceOperation);
ObjectMeta objectMeta = new ObjectMeta();
objectMeta.setNamespace(namespace);
@@ -326,13 +338,13 @@ public class KubernetesDiscoveryClientFilterMetadataTest {
final Endpoints endpoints = new EndpointsBuilder().withMetadata(objectMeta).addNewSubset()
.addAllToPorts(getEndpointPorts(ports)).addNewAddress().endAddress().endSubset().build();
when(this.kubernetesClient.endpoints()).thenReturn(this.endpointsOperation);
when(CLIENT.endpoints()).thenReturn(this.endpointsOperation);
EndpointsList endpointsList = new EndpointsList(null, Collections.singletonList(endpoints), null, null);
when(filter.list()).thenReturn(endpointsList);
when(filter.withLabels(anyMap())).thenReturn(filter);
when(this.kubernetesClient.endpoints().withField(eq("metadata.name"), eq(serviceId))).thenReturn(filter);
when(CLIENT.endpoints().withField(eq("metadata.name"), eq(serviceId))).thenReturn(filter);
}

View File

@@ -19,6 +19,8 @@ package org.springframework.cloud.kubernetes.fabric8.discovery;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.fabric8.kubernetes.api.model.ObjectMeta;
import io.fabric8.kubernetes.api.model.Service;
@@ -26,7 +28,6 @@ import io.fabric8.kubernetes.api.model.ServiceList;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.MixedOperation;
import io.fabric8.kubernetes.client.dsl.ServiceResource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
@@ -43,22 +44,11 @@ public class KubernetesDiscoveryClientFilterTest {
@Mock
private KubernetesClient kubernetesClient;
@Mock
private KubernetesDiscoveryProperties properties;
private KubernetesClientServicesFunction kubernetesClientServicesFunction = KubernetesClient::services;
private final KubernetesClientServicesFunction kubernetesClientServicesFunction = KubernetesClient::services;
@Mock
private MixedOperation<Service, ServiceList, ServiceResource<Service>> serviceOperation;
private KubernetesDiscoveryClient underTest;
@Before
public void setUp() {
this.underTest = new KubernetesDiscoveryClient(this.kubernetesClient, this.properties,
this.kubernetesClientServicesFunction);
}
@Test
public void testFilteredServices() {
List<String> springBootServiceNames = Arrays.asList("serviceA", "serviceB");
@@ -76,11 +66,13 @@ public class KubernetesDiscoveryClientFilterTest {
when(this.serviceOperation.list()).thenReturn(serviceList);
when(this.kubernetesClient.services()).thenReturn(this.serviceOperation);
when(this.properties.getFilter()).thenReturn("metadata.additionalProperties['spring-boot']");
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false,
"metadata.additionalProperties['spring-boot']", Set.of(), Map.of(), null,
KubernetesDiscoveryProperties.Metadata.DEFAULT, 0);
KubernetesDiscoveryClient client = new KubernetesDiscoveryClient(this.kubernetesClient, properties,
this.kubernetesClientServicesFunction);
List<String> filteredServices = this.underTest.getServices();
System.out.println("Filtered Services: " + filteredServices);
List<String> filteredServices = client.getServices();
assertThat(filteredServices).isEqualTo(springBootServiceNames);
}
@@ -102,11 +94,13 @@ public class KubernetesDiscoveryClientFilterTest {
when(this.serviceOperation.list()).thenReturn(serviceList);
when(this.kubernetesClient.services()).thenReturn(this.serviceOperation);
when(this.properties.getFilter()).thenReturn("metadata.name.startsWith('service')");
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false,
"metadata.name.startsWith('service')", Set.of(), Map.of(), null,
KubernetesDiscoveryProperties.Metadata.DEFAULT, 0);
KubernetesDiscoveryClient client = new KubernetesDiscoveryClient(this.kubernetesClient, properties,
this.kubernetesClientServicesFunction);
List<String> filteredServices = this.underTest.getServices();
System.out.println("Filtered Services: " + filteredServices);
List<String> filteredServices = client.getServices();
assertThat(filteredServices).isEqualTo(springBootServiceNames);
}
@@ -121,9 +115,12 @@ public class KubernetesDiscoveryClientFilterTest {
when(this.serviceOperation.list()).thenReturn(serviceList);
when(this.kubernetesClient.services()).thenReturn(this.serviceOperation);
when(this.properties.getFilter()).thenReturn("");
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false, "",
Set.of(), Map.of(), null, KubernetesDiscoveryProperties.Metadata.DEFAULT, 0);
KubernetesDiscoveryClient client = new KubernetesDiscoveryClient(this.kubernetesClient, properties,
this.kubernetesClientServicesFunction);
List<String> filteredServices = this.underTest.getServices();
List<String> filteredServices = client.getServices();
System.out.println("Filtered Services: " + filteredServices);
assertThat(filteredServices).isEqualTo(springBootServiceNames);

View File

@@ -20,6 +20,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.fabric8.kubernetes.api.model.Endpoints;
import io.fabric8.kubernetes.api.model.EndpointsBuilder;
@@ -81,13 +82,9 @@ public class KubernetesDiscoveryClientTest {
mockClient.services().inNamespace("test").create(service);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
Metadata metadata = new Metadata(false, null, false, null, true, "port.");
properties.setServiceLabels(labels);
properties.setMetadata(metadata);
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services,
new ServicePortSecureResolver(KubernetesDiscoveryProperties.DEFAULT));
final List<ServiceInstance> instances = discoveryClient.getInstances("endpoint");
@@ -112,8 +109,8 @@ public class KubernetesDiscoveryClientTest {
mockClient.services().inNamespace("test").create(service);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
properties.setPrimaryPortName("http_tcp");
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, true, 60, false,
null, Set.of(), labels, "http_tcp", Metadata.DEFAULT, 0);
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
@@ -137,11 +134,9 @@ public class KubernetesDiscoveryClientTest {
mockClient.endpoints().inNamespace("test").create(endPoint);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
properties.setServiceLabels(labels);
final KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
final KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services,
new ServicePortSecureResolver(KubernetesDiscoveryProperties.DEFAULT));
final List<Endpoints> result_endpoints = discoveryClient.getEndPointsList("endpoint");
@@ -166,10 +161,9 @@ public class KubernetesDiscoveryClientTest {
mockClient.services().inNamespace("test").create(service);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
properties.setServiceLabels(labels);
Metadata metadata = new Metadata(false, null, false, null, true, "port.");
properties.setMetadata(metadata);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, true, 60, false,
null, Set.of(443, 8443), labels, null, metadata, 0);
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
@@ -195,14 +189,13 @@ public class KubernetesDiscoveryClientTest {
Service service3 = new ServiceBuilder().withNewMetadata().withName("s3").withNamespace("test").endMetadata()
.build();
mockClient.services().inNamespace("test").create(service1);
mockClient.services().inNamespace("test").create(service2);
mockClient.services().inNamespace("test").create(service3);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services,
new ServicePortSecureResolver(KubernetesDiscoveryProperties.DEFAULT));
final List<String> services = discoveryClient.getServices();
@@ -225,10 +218,10 @@ public class KubernetesDiscoveryClientTest {
mockClient.services().inNamespace("test").create(service1);
mockClient.services().inNamespace("test").create(service2);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient,
KubernetesDiscoveryProperties.DEFAULT,
client -> client.services().withLabels(Collections.singletonMap("label", "value")),
new ServicePortSecureResolver(properties));
new ServicePortSecureResolver(KubernetesDiscoveryProperties.DEFAULT));
final List<String> services = discoveryClient.getServices();
@@ -257,8 +250,8 @@ public class KubernetesDiscoveryClientTest {
mockClient.services().inNamespace("test").create(service1);
mockClient.services().inNamespace("test2").create(service2);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
properties.setAllNamespaces(true);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, true, 60, false,
null, Set.of(), Map.of(), null, Metadata.DEFAULT, 0);
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
@@ -283,10 +276,9 @@ public class KubernetesDiscoveryClientTest {
mockClient.endpoints().inNamespace("test").create(endPoint);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
final KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
final KubernetesDiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services,
new ServicePortSecureResolver(KubernetesDiscoveryProperties.DEFAULT));
final List<ServiceInstance> instances = discoveryClient.getInstances("endpoint1");
@@ -310,7 +302,8 @@ public class KubernetesDiscoveryClientTest {
mockClient.services().inNamespace("test").create(service);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, true, 60, false,
null, Set.of(443, 8443), Map.of(), null, Metadata.DEFAULT, 0);
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
@@ -340,7 +333,8 @@ public class KubernetesDiscoveryClientTest {
mockClient.services().inNamespace("test").create(service);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false,
null, Set.of(443, 8443), Map.of(), null, Metadata.DEFAULT, 0);
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
@@ -369,8 +363,8 @@ public class KubernetesDiscoveryClientTest {
mockClient.services().inNamespace("test").create(service);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
properties.setPrimaryPortName("oops");
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false,
null, Set.of(443, 8443), Map.of(), "oops", Metadata.DEFAULT, 0);
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
@@ -398,7 +392,8 @@ public class KubernetesDiscoveryClientTest {
mockClient.services().inNamespace("test").create(service);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, false, true, 60, false,
null, Set.of(443, 8443), Map.of(), null, Metadata.DEFAULT, 0);
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
@@ -427,10 +422,9 @@ public class KubernetesDiscoveryClientTest {
mockClient.services().inNamespace("test").create(service);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services,
new ServicePortSecureResolver(KubernetesDiscoveryProperties.DEFAULT));
final List<ServiceInstance> instances = discoveryClient.getInstances("endpoint5");
@@ -455,7 +449,8 @@ public class KubernetesDiscoveryClientTest {
mockClient.services().inNamespace("test").create(service);
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, true, 60, true,
null, Set.of(443, 8443), Map.of(), null, Metadata.DEFAULT, 0);
final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient, properties,
KubernetesClient::services, new ServicePortSecureResolver(properties));

View File

@@ -18,6 +18,7 @@ package org.springframework.cloud.kubernetes.fabric8.discovery;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.junit.Test;
@@ -49,8 +50,8 @@ public class ServicePortSecureResolverTest {
@Test
public void testPortNumbersOnly() {
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
properties.getKnownSecurePorts().add(12345);
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, true, 60, false, null,
Set.of(443, 8443, 12345), Map.of(), null, KubernetesDiscoveryProperties.Metadata.DEFAULT, 0);
ServicePortSecureResolver secureResolver = new ServicePortSecureResolver(properties);
@@ -65,7 +66,7 @@ public class ServicePortSecureResolverTest {
@Test
public void testLabelsAndAnnotations() {
ServicePortSecureResolver secureResolver = new ServicePortSecureResolver(new KubernetesDiscoveryProperties());
ServicePortSecureResolver secureResolver = new ServicePortSecureResolver(KubernetesDiscoveryProperties.DEFAULT);
assertThat(secureResolver.resolve(SECURED_TRUE)).isTrue();
assertThat(secureResolver.resolve(SECURED_1)).isTrue();

View File

@@ -19,6 +19,8 @@ package org.springframework.cloud.kubernetes.fabric8.discovery.reactive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.fabric8.kubernetes.api.model.Endpoints;
import io.fabric8.kubernetes.api.model.EndpointsBuilder;
@@ -63,9 +65,8 @@ class KubernetesReactiveDiscoveryClientTests {
@Test
public void verifyDefaults(@KubernetesExtension.Client KubernetesClient kubernetesClient) {
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, properties,
KubernetesClient::services);
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services);
assertThat(client.description()).isEqualTo("Kubernetes Reactive Discovery Client");
assertThat(client.getOrder()).isEqualTo(ReactiveDiscoveryClient.DEFAULT_ORDER);
}
@@ -88,10 +89,8 @@ class KubernetesReactiveDiscoveryClientTests {
}).endMetadata().endItem().addNewItem().withNewMetadata().withName("s3").endMetadata().endItem()
.build())
.once();
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, properties,
KubernetesClient::services);
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services);
Flux<String> services = client.getServices();
StepVerifier.create(services).expectNext("s1", "s2", "s3").expectComplete().verify();
}
@@ -103,9 +102,8 @@ class KubernetesReactiveDiscoveryClientTests {
kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services")
.andReturn(200, new ServiceListBuilder().build()).once();
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, properties,
KubernetesClient::services);
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services);
Flux<String> services = client.getServices();
StepVerifier.create(services).expectNextCount(0).expectComplete().verify();
}
@@ -118,9 +116,8 @@ class KubernetesReactiveDiscoveryClientTests {
.withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dnonexistent-service")
.andReturn(200, new EndpointsBuilder().build()).once();
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, properties,
KubernetesClient::services);
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services);
Flux<ServiceInstance> instances = client.getInstances("nonexistent-service");
StepVerifier.create(instances).expectNextCount(0).expectComplete().verify();
}
@@ -142,9 +139,8 @@ class KubernetesReactiveDiscoveryClientTests {
.withPath("/api/v1/namespaces/test/endpoints?fieldSelector=metadata.name%3Dexisting-service")
.andReturn(200, new EndpointsBuilder().build()).once();
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, properties,
KubernetesClient::services);
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services);
Flux<ServiceInstance> instances = client.getInstances("existing-service");
StepVerifier.create(instances).expectNextCount(0).expectComplete().verify();
}
@@ -180,11 +176,9 @@ class KubernetesReactiveDiscoveryClientTests {
kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services/existing-service")
.andReturn(200, services.getItems().get(0)).once();
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
Metadata metadata = new Metadata(false, null, false, null, true, "port.");
properties.setMetadata(metadata);
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, properties,
KubernetesClient::services);
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services);
Flux<ServiceInstance> instances = client.getInstances("existing-service");
StepVerifier.create(instances).expectNextCount(1).expectComplete().verify();
}
@@ -224,11 +218,9 @@ class KubernetesReactiveDiscoveryClientTests {
}).endMetadata().build())
.once();
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
Metadata metadata = new Metadata(true, "label.", true, "annotation.", true, "port.");
properties.setMetadata(metadata);
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, properties,
KubernetesClient::services);
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services);
Flux<ServiceInstance> instances = client.getInstances("existing-service");
StepVerifier.create(instances).expectNextCount(1).expectComplete().verify();
}
@@ -270,10 +262,8 @@ class KubernetesReactiveDiscoveryClientTests {
}).endMetadata().build())
.once();
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
properties.setPrimaryPortName("https_tcp");
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, properties,
KubernetesClient::services);
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient,
KubernetesDiscoveryProperties.DEFAULT, KubernetesClient::services);
Flux<ServiceInstance> instances = client.getInstances("existing-service");
StepVerifier.create(instances).expectNextCount(1).expectComplete().verify();
}
@@ -311,8 +301,8 @@ class KubernetesReactiveDiscoveryClientTests {
}).endMetadata().build())
.once();
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
properties.setAllNamespaces(true);
KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(true, true, true, 60, false, null,
Set.of(), Map.of(), "https_tcp", Metadata.DEFAULT, 0);
ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient(kubernetesClient, properties,
KubernetesClient::services);
Flux<ServiceInstance> instances = client.getInstances("existing-service");

View File

@@ -77,7 +77,7 @@ public class Fabric8ServiceInstanceMapper implements KubernetesServiceInstanceMa
private Map<String, String> getServiceMetadata(Service service) {
final Map<String, String> serviceMetadata = new HashMap<>();
KubernetesDiscoveryProperties.Metadata metadataProps = this.discoveryProperties.getMetadata();
KubernetesDiscoveryProperties.Metadata metadataProps = this.discoveryProperties.metadata();
if (metadataProps.addLabels()) {
Map<String, String> labelMetadata = KubernetesServiceInstanceMapper
.getMapWithPrefixedKeys(service.getMetadata().getLabels(), metadataProps.labelsPrefix());

View File

@@ -49,7 +49,7 @@ public class Fabric8ServicesListSupplier extends KubernetesServicesListSupplier
@Override
public Flux<List<ServiceInstance>> get() {
List<ServiceInstance> result = new ArrayList<>();
if (discoveryProperties.isAllNamespaces()) {
if (discoveryProperties.allNamespaces()) {
List<Service> services = this.kubernetesClient.services().inAnyNamespace()
.withField("metadata.name", this.getServiceId()).list().getItems();
services.forEach(service -> result.add(mapper.map(service)));

View File

@@ -20,6 +20,7 @@ import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.kubernetes.commons.discovery.KubernetesDiscoveryProperties;
import org.springframework.context.ConfigurableApplicationContext;
@@ -70,9 +71,13 @@ class Fabric8LoadBalancerAutoConfigurationTests {
}
private void setup(String... env) {
this.context = new SpringApplicationBuilder(Fabric8LoadBalancerAutoConfiguration.class,
KubernetesDiscoveryProperties.class).web(org.springframework.boot.WebApplicationType.NONE)
.properties(env).run();
this.context = new SpringApplicationBuilder(Fabric8LoadBalancerAutoConfiguration.class, Config.class)
.web(org.springframework.boot.WebApplicationType.NONE).properties(env).run();
}
@EnableConfigurationProperties(KubernetesDiscoveryProperties.class)
static class Config {
}
}

View File

@@ -21,6 +21,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceBuilder;
@@ -38,10 +39,9 @@ class Fabric8ServiceInstanceMapperTests {
@Test
public void testMapperSimple() {
KubernetesLoadBalancerProperties properties = new KubernetesLoadBalancerProperties();
KubernetesDiscoveryProperties discoveryProperties = new KubernetesDiscoveryProperties();
Service service = buildService("test", "abc", 8080, null, new HashMap<>());
KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties, discoveryProperties)
.map(service);
KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties,
KubernetesDiscoveryProperties.DEFAULT).map(service);
Assertions.assertNotNull(instance);
Assertions.assertEquals("test", instance.getServiceId());
Assertions.assertEquals("abc", instance.getInstanceId());
@@ -51,13 +51,12 @@ class Fabric8ServiceInstanceMapperTests {
void testMapperMultiplePorts() {
KubernetesLoadBalancerProperties properties = new KubernetesLoadBalancerProperties();
properties.setPortName("http");
KubernetesDiscoveryProperties discoveryProperties = new KubernetesDiscoveryProperties();
List<ServicePort> ports = new ArrayList<>();
ports.add(new ServicePortBuilder().withPort(8080).withName("web").build());
ports.add(new ServicePortBuilder().withPort(9000).withName("http").build());
Service service = buildService("test", "abc", ports, new HashMap<>());
KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties, discoveryProperties)
.map(service);
KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties,
KubernetesDiscoveryProperties.DEFAULT).map(service);
Assertions.assertNotNull(instance);
Assertions.assertEquals("test", instance.getServiceId());
Assertions.assertEquals("abc", instance.getInstanceId());
@@ -67,10 +66,9 @@ class Fabric8ServiceInstanceMapperTests {
@Test
void testMapperSecure() {
KubernetesLoadBalancerProperties properties = new KubernetesLoadBalancerProperties();
KubernetesDiscoveryProperties discoveryProperties = new KubernetesDiscoveryProperties();
Service service = buildService("test", "abc", 443, null, new HashMap<>());
KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties, discoveryProperties)
.map(service);
KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties,
KubernetesDiscoveryProperties.DEFAULT).map(service);
Assertions.assertNotNull(instance);
Assertions.assertEquals("test", instance.getServiceId());
Assertions.assertEquals("abc", instance.getInstanceId());
@@ -80,7 +78,8 @@ class Fabric8ServiceInstanceMapperTests {
@Test
void testMapperSecureNullLabelsAndAnnotations() {
KubernetesLoadBalancerProperties properties = new KubernetesLoadBalancerProperties();
KubernetesDiscoveryProperties discoveryProperties = new KubernetesDiscoveryProperties();
KubernetesDiscoveryProperties discoveryProperties = new KubernetesDiscoveryProperties(true, true, true, 60,
false, null, Set.of(), Map.of(), null, KubernetesDiscoveryProperties.Metadata.DEFAULT, 0);
List<ServicePort> ports = new ArrayList<>();
ports.add(new ServicePortBuilder().withPort(443).build());
Service service = buildService("test", "abc", ports, null, null);
@@ -95,13 +94,12 @@ class Fabric8ServiceInstanceMapperTests {
@Test
void testMapperSecureWithLabels() {
KubernetesLoadBalancerProperties properties = new KubernetesLoadBalancerProperties();
KubernetesDiscoveryProperties discoveryProperties = new KubernetesDiscoveryProperties();
HashMap<String, String> labels = new HashMap<>();
labels.put("secured", "true");
labels.put("label1", "123");
Service service = buildService("test", "abc", 8080, null, labels);
KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties, discoveryProperties)
.map(service);
KubernetesServiceInstance instance = new Fabric8ServiceInstanceMapper(properties,
KubernetesDiscoveryProperties.DEFAULT).map(service);
Assertions.assertNotNull(instance);
Assertions.assertEquals("test", instance.getServiceId());
Assertions.assertEquals("abc", instance.getInstanceId());

View File

@@ -17,6 +17,8 @@
package org.springframework.cloud.kubernetes.fabric8.loadbalancer;
import java.util.List;
import java.util.Map;
import java.util.Set;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceBuilder;
@@ -76,7 +78,7 @@ class KubernetesServiceListSupplierTests {
when(this.namespaceOperation.withName("test-service")).thenReturn(this.serviceResource);
when(this.serviceResource.get()).thenReturn(buildService("test-service", 8080));
KubernetesServicesListSupplier supplier = new Fabric8ServicesListSupplier(environment, client, mapper,
new KubernetesDiscoveryProperties());
KubernetesDiscoveryProperties.DEFAULT);
List<ServiceInstance> instances = supplier.get().blockFirst();
assert instances != null;
Assertions.assertEquals(1, instances.size());
@@ -93,8 +95,8 @@ class KubernetesServiceListSupplierTests {
ServiceList serviceList = new ServiceList();
serviceList.getItems().add(buildService("test-service", 8080));
when(this.multiDeletable.list()).thenReturn(serviceList);
KubernetesDiscoveryProperties discoveryProperties = new KubernetesDiscoveryProperties();
discoveryProperties.setAllNamespaces(true);
KubernetesDiscoveryProperties discoveryProperties = new KubernetesDiscoveryProperties(true, true, true, 60,
false, null, Set.of(), Map.of(), null, KubernetesDiscoveryProperties.Metadata.DEFAULT, 0);
KubernetesServicesListSupplier supplier = new Fabric8ServicesListSupplier(environment, client, mapper,
discoveryProperties);
List<ServiceInstance> instances = supplier.get().blockFirst();