Add namespace information to the service instance metadata when using all-namspaces=true

Fixes gh-503
This commit is contained in:
Michael Kreis
2020-07-06 11:49:45 +02:00
committed by spencergibb
parent 697a408841
commit cd8a507833
3 changed files with 22 additions and 0 deletions

View File

@@ -41,6 +41,7 @@ import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import static java.util.stream.Collectors.toMap;
import static org.springframework.cloud.kubernetes.discovery.KubernetesServiceInstance.NAMESPACE_METADATA_KEY;
/**
* Kubeneretes implementation of {@link DiscoveryClient}.
@@ -153,6 +154,10 @@ public class KubernetesDiscoveryClient implements DiscoveryClient {
endpointMetadata.putAll(portMetadata);
}
if (this.properties.isAllNamespaces()) {
endpointMetadata.put(NAMESPACE_METADATA_KEY, namespace);
}
List<EndpointAddress> addresses = s.getAddresses();
for (EndpointAddress endpointAddress : addresses) {
String instanceId = null;

View File

@@ -28,6 +28,11 @@ import org.springframework.cloud.client.ServiceInstance;
*/
public class KubernetesServiceInstance implements ServiceInstance {
/**
* Key of the namespace metadata.
*/
public static final String NAMESPACE_METADATA_KEY = "k8s_namespace";
private static final String HTTP_PREFIX = "http";
private static final String HTTPS_PREFIX = "https";
@@ -115,4 +120,8 @@ public class KubernetesServiceInstance implements ServiceInstance {
return URI.create(sb.toString());
}
public String getNamespace() {
return this.metadata != null ? this.metadata.get(NAMESPACE_METADATA_KEY) : null;
}
}

View File

@@ -377,6 +377,14 @@ public class KubernetesDiscoveryClientTest {
.hasSize(1);
assertThat(instances).filteredOn(s -> s.getHost().equals("ip2") && !s.isSecure())
.hasSize(1);
assertThat(instances)
.filteredOn(s -> s.getServiceId().contains("endpoint")
&& ((KubernetesServiceInstance) s).getNamespace().equals("test"))
.hasSize(1);
assertThat(instances)
.filteredOn(s -> s.getServiceId().contains("endpoint")
&& ((KubernetesServiceInstance) s).getNamespace().equals("test2"))
.hasSize(1);
assertThat(instances).filteredOn(s -> s.getInstanceId().equals("60")).hasSize(1);
assertThat(instances).filteredOn(s -> s.getInstanceId().equals("70")).hasSize(1);
}