Skip to content

Commit

Permalink
refactor: global namespace setting
Browse files Browse the repository at this point in the history
Signed-off-by: Marc Nuri <[email protected]>
  • Loading branch information
manusa committed May 4, 2022
1 parent 23f11ce commit a0c8467
Show file tree
Hide file tree
Showing 14 changed files with 94 additions and 93 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
import java.util.stream.Collectors;

import io.fabric8.kubernetes.api.model.HTTPHeader;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.utils.ApiVersionUtil;
import org.eclipse.jkube.kit.common.KitLogger;

Expand Down Expand Up @@ -756,17 +757,12 @@ public static boolean isExposeService(Service service) {
return expose != null && expose.equalsIgnoreCase("true");
}

public static String getServiceExposeUrl(KubernetesClient kubernetes, String namespace, Collection<HasMetadata> resources, long serviceUrlWaitTimeSeconds, String exposeServiceAnnotationKey) throws InterruptedException {
public static String getServiceExposeUrl(NamespacedKubernetesClient kubernetes, Collection<HasMetadata> resources, long serviceUrlWaitTimeSeconds, String exposeServiceAnnotationKey) throws InterruptedException {
for (HasMetadata entity : resources) {
if (entity instanceof Service) {
Service service = (Service) entity;
String name = KubernetesHelper.getName(service);
final Resource<Service> serviceResource;
if (namespace != null) {
serviceResource = kubernetes.services().inNamespace(namespace).withName(name);
} else {
serviceResource = kubernetes.services().withName(name);
}
final Resource<Service> serviceResource = kubernetes.services().withName(name);
String url = pollServiceForExposeUrl(serviceUrlWaitTimeSeconds, service, serviceResource, exposeServiceAnnotationKey);

// let's not wait for other services
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import io.fabric8.kubernetes.api.model.KubernetesListBuilder;
import io.fabric8.kubernetes.api.model.LabelSelector;
import io.fabric8.kubernetes.api.model.batch.v1.JobBuilder;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import org.eclipse.jkube.kit.common.KitLogger;

import io.fabric8.kubernetes.api.model.ConfigMapBuilder;
Expand All @@ -49,7 +50,6 @@
import io.fabric8.kubernetes.api.model.apps.DeploymentBuilder;
import io.fabric8.kubernetes.api.model.apps.ReplicaSetBuilder;
import io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.dsl.Resource;
import io.fabric8.openshift.api.model.DeploymentConfigBuilder;
import io.fabric8.openshift.api.model.Template;
Expand Down Expand Up @@ -285,13 +285,13 @@ public void testConvertToEnvVarList() {
}

@Test
public void testGetServiceExposeUrlReturnsUrlFromAnnotation(@Mocked KubernetesClient kubernetesClient, @Mocked Resource<Service> svcResource) throws InterruptedException {
public void testGetServiceExposeUrlReturnsUrlFromAnnotation(@Mocked NamespacedKubernetesClient kubernetesClient, @Mocked Resource<Service> svcResource) throws InterruptedException {
// Given
Service svc = new ServiceBuilder().withNewMetadata().withName("svc1").endMetadata().build();
Set<HasMetadata> entities = new HashSet<>();
entities.add(svc);
new Expectations() {{
kubernetesClient.services().inNamespace("ns1").withName("svc1");
kubernetesClient.services().withName("svc1");
result = svcResource;
svcResource.get();
result = new ServiceBuilder()
Expand All @@ -303,26 +303,26 @@ public void testGetServiceExposeUrlReturnsUrlFromAnnotation(@Mocked KubernetesCl
}};

// When
String result = KubernetesHelper.getServiceExposeUrl(kubernetesClient, "ns1", entities, 3, "exposeUrl");
String result = KubernetesHelper.getServiceExposeUrl(kubernetesClient, entities, 3, "exposeUrl");

// Then
assertEquals("http://example.com", result);
new Verifications() {{
kubernetesClient.services().inNamespace("ns1").withName("svc1");
kubernetesClient.services().withName("svc1");
times = 1;
svcResource.get();
times = 1;
}};
}

@Test
public void testGetServiceExposeUrlReturnsNull(@Mocked KubernetesClient kubernetesClient, @Mocked Resource<Service> svcResource) throws InterruptedException {
public void testGetServiceExposeUrlReturnsNull(@Mocked NamespacedKubernetesClient kubernetesClient, @Mocked Resource<Service> svcResource) throws InterruptedException {
// Given
Service svc = new ServiceBuilder().withNewMetadata().withName("svc1").endMetadata().build();
Set<HasMetadata> entities = new HashSet<>();
entities.add(svc);
new Expectations() {{
kubernetesClient.services().inNamespace("ns1").withName("svc1");
kubernetesClient.services().withName("svc1");
result = svcResource;
svcResource.get();
result = new ServiceBuilder()
Expand All @@ -333,12 +333,12 @@ public void testGetServiceExposeUrlReturnsNull(@Mocked KubernetesClient kubernet
}};

// When
String result = KubernetesHelper.getServiceExposeUrl(kubernetesClient, "ns1", entities, 1, "exposeUrl");
String result = KubernetesHelper.getServiceExposeUrl(kubernetesClient, entities, 1, "exposeUrl");

// Then
assertNull(result);
new Verifications() {{
kubernetesClient.services().inNamespace("ns1").withName("svc1");
kubernetesClient.services().withName("svc1");
times = 1;
svcResource.get();
times = 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import java.util.stream.Collectors;

import io.fabric8.kubernetes.api.model.GenericKubernetesResource;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.dsl.base.PatchContext;
import io.fabric8.kubernetes.client.dsl.base.PatchType;
import org.eclipse.jkube.kit.common.KitLogger;
Expand Down Expand Up @@ -142,7 +143,8 @@ public void apply(Object dto, String sourceName) {
}

public boolean isAlreadyApplied(HasMetadata resource) {
return kubernetesClient.resource(resource).inNamespace(namespace).fromServer().get() != null;
return kubernetesClient.resource(resource)
.inNamespace(applicableNamespace(resource, namespace, fallbackNamespace)).fromServer().get() != null;
}

/**
Expand Down Expand Up @@ -1351,7 +1353,9 @@ public void applyEntities(String fileName, Collection<HasMetadata> entities, Kit
}

private void logExposeServiceUrl(Collection<HasMetadata> entities, KitLogger serviceLogger, long serviceUrlWaitTimeSeconds) throws InterruptedException {
String url = KubernetesHelper.getServiceExposeUrl(kubernetesClient, namespace, entities, serviceUrlWaitTimeSeconds, JKubeAnnotations.SERVICE_EXPOSE_URL.value());
String url = KubernetesHelper.getServiceExposeUrl(
kubernetesClient.adapt(NamespacedKubernetesClient.class).inNamespace(applicableNamespace(null, namespace, fallbackNamespace)),
entities, serviceUrlWaitTimeSeconds, JKubeAnnotations.SERVICE_EXPOSE_URL.value());
if (url != null) {
serviceLogger.info("ExposeController Service URL: %s", url);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.function.Consumer;
import java.util.function.Predicate;

import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.dsl.PodResource;
import org.eclipse.jkube.kit.common.DebugConstants;
import org.eclipse.jkube.kit.common.KitLogger;
Expand Down Expand Up @@ -77,6 +78,12 @@ public void debug(
log.error("Unable to proceed with Debug. No application resource found running in the cluster");
return;
}
final NamespacedKubernetesClient nsClient;
if (namespace != null) {
nsClient = kubernetesClient.adapt(NamespacedKubernetesClient.class).inNamespace(namespace);
} else {
nsClient = kubernetesClient.adapt(NamespacedKubernetesClient.class);
}
LabelSelector firstSelector = null;
for (HasMetadata entity : entities) {
if (firstSelector == null) {
Expand All @@ -88,7 +95,7 @@ public void debug(
log.error("Debug is not applicable for the currently generated resources");
return;
}
startPortForward(firstSelector, namespace, debugSuspend, localDebugPort, podWaitLog);
startPortForward(nsClient, firstSelector, debugSuspend, localDebugPort, podWaitLog);
}

/**
Expand All @@ -112,12 +119,12 @@ private boolean isDebugApplicable(Collection<HasMetadata> entities) {
}

private void startPortForward(
LabelSelector firstSelector, String namespace, boolean debugSuspend, String localDebugPort, KitLogger podWaitLog
NamespacedKubernetesClient nsClient, LabelSelector firstSelector, boolean debugSuspend, String localDebugPort, KitLogger podWaitLog
) {
if (firstSelector != null) {
Map<String, String> envVars = initDebugEnvVarsMap(debugSuspend);
String podName = waitForRunningPodWithEnvVar(namespace, firstSelector, envVars, podWaitLog);
portForwardService.startPortForward(podName, namespace, portToInt(debugPortInContainer, "containerDebugPort"), portToInt(localDebugPort, "localDebugPort"));
String podName = waitForRunningPodWithEnvVar(nsClient, firstSelector, envVars, podWaitLog);
portForwardService.startPortForward(nsClient, podName, portToInt(debugPortInContainer, "containerDebugPort"), portToInt(localDebugPort, "localDebugPort"));
}
}

Expand Down Expand Up @@ -202,9 +209,9 @@ private void enableDebugging(DeploymentConfig entity, String fileName, boolean d
.ifPresent(applyEntity(entity, fileName));
}

private String waitForRunningPodWithEnvVar(final String namespace, LabelSelector selector, final Map<String, String> envVars, KitLogger podWaitLog) {
private String waitForRunningPodWithEnvVar(NamespacedKubernetesClient nsClient, LabelSelector selector, final Map<String, String> envVars, KitLogger podWaitLog) {
// wait for the newest pod to be ready with the given env var
FilterWatchListDeletable<Pod, PodList, PodResource> pods = withSelector(kubernetesClient.pods().inNamespace(namespace), selector, log);
FilterWatchListDeletable<Pod, PodList, PodResource> pods = withSelector(nsClient.pods(), selector, log);
PodList list = pods.list();
if (list != null) {
Pod latestPod = KubernetesHelper.getNewestPod(list.getItems());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ private void initClusterAccessAndLazyBuilders() {
});
portForwardService = new LazyBuilder<>(() -> {
validateIfConnectedToCluster();
return new PortForwardService(client, log);
return new PortForwardService(log);
});
debugService = new LazyBuilder<>(() -> {
validateIfConnectedToCluster();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.dsl.PodResource;
import org.eclipse.jkube.kit.common.KitLogger;
import org.eclipse.jkube.kit.common.util.KubernetesHelper;
Expand All @@ -30,7 +31,6 @@
import io.fabric8.kubernetes.api.model.LabelSelector;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodList;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.LocalPortForward;
import io.fabric8.kubernetes.client.Watch;
import io.fabric8.kubernetes.client.Watcher;
Expand All @@ -47,11 +47,8 @@ public class PortForwardService {

private final KitLogger log;

private final KubernetesClient kubernetes;

public PortForwardService(KubernetesClient kubernetes, KitLogger log) {
public PortForwardService(KitLogger log) {
this.log = Objects.requireNonNull(log, "log");
this.kubernetes = Objects.requireNonNull(kubernetes, "kubernetes");
}

/**
Expand All @@ -63,7 +60,7 @@ public PortForwardService(KubernetesClient kubernetes, KitLogger log) {
* @param localPort port at remote machine outside Kubernetes Cluster
* @return {@link Closeable} Closeable
*/
public Closeable forwardPortAsync(final LabelSelector podSelector, String namespace, final int containerPort, final int localPort) {
public Closeable forwardPortAsync(NamespacedKubernetesClient kubernetes, final LabelSelector podSelector, final int containerPort, final int localPort) {

final Lock monitor = new ReentrantLock(true);
final Condition podChanged = monitor.newCondition();
Expand Down Expand Up @@ -96,7 +93,7 @@ public void run() {

if (nextPod != null) {
log.info("Starting port-forward to pod %s", KubernetesHelper.getName(nextPod));
currentPortForward = forwardPortAsync(KubernetesHelper.getName(nextPod), KubernetesHelper.getNamespace(nextPod), containerPort, localPort);
currentPortForward = forwardPortAsync(kubernetes, KubernetesHelper.getName(nextPod), containerPort, localPort);
} else {
log.info("Waiting for a pod to become ready before starting port-forward");
}
Expand Down Expand Up @@ -126,10 +123,10 @@ public void run() {
};

// Switching forward to the current pod if present
Pod newPod = getNewestPod(namespace, podSelector);
Pod newPod = getNewestPod(kubernetes, podSelector);
nextForwardedPod[0] = newPod;

final Watch watch = KubernetesHelper.withSelector(kubernetes.pods().inNamespace(namespace), podSelector, log).watch(new Watcher<Pod>() {
final Watch watch = KubernetesHelper.withSelector(kubernetes.pods(), podSelector, log).watch(new Watcher<Pod>() {

@Override
public void eventReceived(Action action, Pod pod) {
Expand Down Expand Up @@ -196,9 +193,9 @@ private boolean podEquals(Pod pod1, Pod pod2) {
return KubernetesHelper.getName(pod1).equals(KubernetesHelper.getName(pod2));
}

private Pod getNewestPod(String namespace, LabelSelector selector) {
private Pod getNewestPod(NamespacedKubernetesClient kubernetes, LabelSelector selector) {
FilterWatchListDeletable<Pod, PodList, PodResource> pods =
KubernetesHelper.withSelector(kubernetes.pods().inNamespace(namespace), selector, log);
KubernetesHelper.withSelector(kubernetes.pods(), selector, log);

PodList list = pods.list();
if (list != null) {
Expand All @@ -223,18 +220,18 @@ private Pod getNewestPod(List<Pod> items) {
}

// Visible for test
LocalPortForward forwardPortAsync(String podName, String namespace, int containerPort, int localPort) {
return kubernetes.pods().inNamespace(namespace).withName(podName).portForward(containerPort, localPort);
static LocalPortForward forwardPortAsync(NamespacedKubernetesClient kubernetes, String podName, int containerPort, int localPort) {
return kubernetes.pods().withName(podName).portForward(containerPort, localPort);
}

void startPortForward(String pod, String namespace, int containerPort, int localPort) {
void startPortForward(NamespacedKubernetesClient kubernetes, String pod, int containerPort, int localPort) {
log.info("Starting port forwarding to port %s on pod %s", localPort, pod);
LocalPortForward localPortForward = forwardPortAsync(pod, namespace, containerPort, localPort);
LocalPortForward localPortForward = forwardPortAsync(kubernetes, pod, containerPort, localPort);
log.info("Port Forwarding started");
log.info("Now you can start a Remote debug session by using localhost and the debug port %s",
localPort);
log.info("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=%s", localPort);
new PortForwardTask(kubernetes, pod, namespace, localPortForward, log).run();
new PortForwardTask(kubernetes, pod, localPortForward, log).run();
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
*/
package org.eclipse.jkube.kit.config.service.portforward;

import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.LocalPortForward;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.Watch;
import lombok.AllArgsConstructor;
import org.eclipse.jkube.kit.common.KitLogger;
Expand All @@ -25,9 +25,8 @@

@AllArgsConstructor
public class PortForwardTask implements Runnable, AutoCloseable {
private final KubernetesClient kubernetesClient;
private final NamespacedKubernetesClient kubernetesClient;
private final String podName;
private final String namespace;
private final LocalPortForward localPortForward;
private final KitLogger logger;
private final CountDownLatch podAvailableLatch = new CountDownLatch(1);
Expand All @@ -42,7 +41,7 @@ public void run() {
}
}));
try(
Watch ignore = kubernetesClient.pods().inNamespace(namespace)
Watch ignore = kubernetesClient.pods()
.watch(new PortForwardMonitor(logger, podName, podAvailableLatch))
) {
podAvailableLatch.await();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import io.fabric8.kubernetes.api.model.ReplicationController;
import io.fabric8.kubernetes.api.model.ReplicationControllerBuilder;
import io.fabric8.kubernetes.api.model.ReplicationControllerSpecBuilder;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.openshift.api.model.DeploymentConfig;
import io.fabric8.openshift.api.model.DeploymentConfigBuilder;
import io.fabric8.openshift.api.model.DeploymentConfigSpecBuilder;
Expand All @@ -43,7 +44,6 @@
import io.fabric8.kubernetes.api.model.apps.ReplicaSet;
import io.fabric8.kubernetes.api.model.apps.ReplicaSetBuilder;
import io.fabric8.kubernetes.api.model.apps.ReplicaSetSpecBuilder;
import io.fabric8.kubernetes.client.KubernetesClient;
import mockit.Mocked;
import org.assertj.core.groups.Tuple;
import org.eclipse.jkube.kit.config.service.portforward.PortForwardPodWatcher;
Expand All @@ -60,7 +60,7 @@ public class DebugServiceTest {
private KitLogger logger;

@Mocked
private KubernetesClient kubernetesClient;
private NamespacedKubernetesClient kubernetesClient;

@Mocked
private PortForwardService portForwardService;
Expand Down Expand Up @@ -227,7 +227,7 @@ private void verifyDebugCompletedSuccessfully(Deployment deployment, int localDe
new Verifications() {{
logger.info("No Active debug pod with provided selector and environment variables found! Waiting for pod to be ready...");
times = 1;
portForwardService.startPortForward(anyString, "namespace", 5005, localDebugPort);
portForwardService.startPortForward(kubernetesClient, anyString, 5005, localDebugPort);
times = 1;
}};
// @formatter:on
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,24 @@
*/
package org.eclipse.jkube.kit.config.service;

import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import mockit.Mocked;
import mockit.Verifications;
import org.eclipse.jkube.kit.common.KitLogger;
import org.junit.Test;

public class PortForwardServicePortOrderTest {
@Mocked
private KubernetesClient kubernetesClient;

@Mocked
private KitLogger logger;
private NamespacedKubernetesClient kubernetesClient;

@Test
public void testPortsSpecifiedInCorrectOrderPortForward() {
// Given
PortForwardService portForwardService = new PortForwardService(kubernetesClient, logger);

// When
portForwardService.forwardPortAsync("foo-pod", "foo-ns", 8080, 312323);
PortForwardService.forwardPortAsync(kubernetesClient, "foo-pod", 8080, 312323);

// Then
new Verifications() {{
kubernetesClient.pods().inNamespace("foo-ns").withName("foo-pod").portForward(8080, 312323);
kubernetesClient.pods().withName("foo-pod").portForward(8080, 312323);
times = 1;
}};
}
}
}
Loading

0 comments on commit a0c8467

Please sign in to comment.