public String getCurrentHostname() { Matcher matcher = getHostnameComponents(); return String.format( POD_HOSTNAME_TEMPLATE, matcher.group("service"), Integer.valueOf(matcher.group("podId")), matcher.group("service"), matcher.group("namespace")); }
@Override default String localServer() { return String.format("%s:%s%s", KubernetesHostnames.INSTANCE.getCurrentHostname(), port(), path()); }
public List<String> getClusterMembers(int expectedClusterSize) { Matcher podTemplateMatcher = getHostnameComponents(); int ourPodId = Integer.parseInt(podTemplateMatcher.group("podId")); Preconditions.checkArgument(ourPodId < expectedClusterSize, "Current Pod ID %s indicates a cluster size greater than the expected %s.", ourPodId, expectedClusterSize); String serviceName = podTemplateMatcher.group("service"); String namespace = podTemplateMatcher.group("namespace"); return IntStream.range(0, expectedClusterSize) .mapToObj(podId -> getPodHostname(serviceName, podId, namespace)) .collect(Collectors.toList()); }
@Override default List<String> clusterMembers() { return KubernetesHostnames.INSTANCE.getClusterMembers(expectedClusterSize()) .stream() .map(hostname -> String.format("%s:%s%s", hostname, port(), path())) .collect(Collectors.toList()); }
@Test public void getClusterMembers_k8s() throws Exception { assertThat(K8S_INSTANCE.getClusterMembers(3)).containsOnly( "svc-47775-0.svc-47775.namespace", "svc-47775-1.svc-47775.namespace", "svc-47775-2.svc-47775.namespace"); }
@Test public void getCurrentHostname_k8s() throws Exception { assertThat(K8S_INSTANCE.getCurrentHostname()).isEqualTo("svc-47775-2.svc-47775.namespace"); }
@Test public void getClusterMembers_not_k8s() throws Exception { expectedException.expect(RuntimeException.class); expectedException.expectMessage("Not running in a k8s stateful set."); NON_K8S_INSTANCE.getClusterMembers(4); }
@Test public void getCurrentHostname_not_k8s() throws Exception { expectedException.expect(RuntimeException.class); expectedException.expectMessage("Not running in a k8s stateful set."); NON_K8S_INSTANCE.getCurrentHostname(); }
@Test public void getClusterMembers_k8s_incorrectCount() throws Exception { expectedException.expect(RuntimeException.class); expectedException.expectMessage("Current Pod ID 2 indicates a cluster size greater than the expected 2."); K8S_INSTANCE.getClusterMembers(2); }