Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 20 additions & 9 deletions util/src/main/java/io/kubernetes/client/util/ResourceClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -534,15 +534,26 @@ public void waitUntilDeleted(Duration timeout)
Objects.requireNonNull(name, "Resource name must be specified");
final String ns = namespace;
final String resourceName = name;
WaitUtils.waitUntilDeleted(
() -> {
KubernetesApiResponse<ApiType> response = ns != null
? api.get(ns, resourceName)
: api.get(resourceName);
return response.isSuccess() ? response.getObject() : null;
},
timeout
);
try {
WaitUtils.waitUntilDeleted(
() -> {
KubernetesApiResponse<ApiType> response = ns != null
? api.get(ns, resourceName)
: api.get(resourceName);
try {
return response.throwsApiException().getObject();
} catch (ApiException e) {
throw new RuntimeException(e);
}
},
timeout
);
} catch (RuntimeException e) {
if (e.getCause() instanceof ApiException) {
throw (ApiException) e.getCause();
}
throw e;
}
}

/**
Expand Down
31 changes: 27 additions & 4 deletions util/src/main/java/io/kubernetes/client/util/WaitUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@
import io.kubernetes.client.util.generic.KubernetesApiResponse;

import java.time.Duration;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
Expand Down Expand Up @@ -171,14 +174,17 @@ public static <T extends KubernetesObject> T waitUntilCondition(
}

/**
* Waits until the resource is deleted (returns null or throws 404).
* Waits until the resource is deleted (returns null or throws an {@link ApiException} with
* HTTP status 404, directly or wrapped in another exception). Other supplier exceptions are
* surfaced immediately.
*
* @param <T> the resource type
* @param resourceSupplier supplier that fetches the current state of the resource
* @param timeout maximum time to wait
* @param pollInterval time between checks
* @throws TimeoutException if the resource is not deleted within the timeout
* @throws InterruptedException if the thread is interrupted
* @throws RuntimeException if the supplier fails with an exception other than HTTP 404
*/
public static <T extends KubernetesObject> void waitUntilDeleted(
Supplier<T> resourceSupplier,
Expand All @@ -200,8 +206,11 @@ public static <T extends KubernetesObject> void waitUntilDeleted(
future.complete(null);
}
} catch (Exception e) {
// Treat any exception as deleted (typically 404)
future.complete(null);
if (isNotFoundException(e)) {
future.complete(null);
} else {
future.completeExceptionally(e);
}
}
}, 0, pollInterval.toMillis(), TimeUnit.MILLISECONDS);

Expand All @@ -211,12 +220,26 @@ public static <T extends KubernetesObject> void waitUntilDeleted(
scheduledTask.cancel(true);
}
} catch (ExecutionException e) {
throw new RuntimeException("Unexpected error while waiting for deletion", e.getCause());
Throwable cause = e.getCause();
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
throw new RuntimeException("Unexpected error while waiting for deletion", cause);
} finally {
executor.shutdownNow();
}
}

private static boolean isNotFoundException(Throwable exception) {
Set<Throwable> visited = Collections.newSetFromMap(new IdentityHashMap<>());
for (Throwable cause = exception; cause != null && visited.add(cause); cause = cause.getCause()) {
if (cause instanceof ApiException && ((ApiException) cause).getCode() == 404) {
return true;
}
}
return false;
}

/**
* Waits until the resource is deleted with default poll interval.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
import io.kubernetes.client.openapi.models.V1PodSpec;
import io.kubernetes.client.openapi.models.V1PodStatus;
import io.kubernetes.client.openapi.models.V1Status;
import java.time.Duration;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -369,6 +370,31 @@ void get_serverError_throwsApiException() {
.isInstanceOf(ApiException.class);
}

@Test
void waitUntilDeleted_notFound_returns() throws Exception {
apiServer.stubFor(
get(urlPathEqualTo("/api/v1/namespaces/default/pods/missing"))
.willReturn(aResponse()
.withStatus(404)
.withBody("{\"kind\": \"Status\", \"code\": 404}")));

podClient.inNamespace("default").withName("missing").waitUntilDeleted(Duration.ofSeconds(2));
}

@Test
void waitUntilDeleted_serverError_throwsApiException() {
apiServer.stubFor(
get(urlPathEqualTo("/api/v1/namespaces/default/pods/error-pod"))
.willReturn(aResponse()
.withStatus(500)
.withBody("{\"message\": \"Internal Server Error\"}")));

assertThatThrownBy(() ->
podClient.inNamespace("default").withName("error-pod").waitUntilDeleted(Duration.ofSeconds(2)))
.isInstanceOf(ApiException.class)
.satisfies(e -> assertThat(((ApiException) e).getCode()).isEqualTo(500));
}

@Test
void create_conflict_throwsApiException() {
V1Pod pod = createPod("conflict-pod", "default");
Expand Down
51 changes: 45 additions & 6 deletions util/src/test/java/io/kubernetes/client/util/WaitUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.models.V1ObjectMeta;
import io.kubernetes.client.openapi.models.V1Pod;
import io.kubernetes.client.openapi.models.V1PodCondition;
Expand Down Expand Up @@ -163,19 +164,43 @@ void waitUntilDeleted_resourceGone_returns() throws Exception {
}

@Test
void waitUntilDeleted_supplierThrows_treatsAsDeleted() throws Exception {
void waitUntilDeleted_supplierThrowsNotFound_treatsAsDeleted() throws Exception {
AtomicInteger callCount = new AtomicInteger(0);

Supplier<V1Pod> supplier = () -> {
if (callCount.incrementAndGet() >= 2) {
throw new RuntimeException("Not found");
}
return createReadyPod();
callCount.incrementAndGet();
throw new RuntimeException(new ApiException(404, "Resource is gone"));
};

WaitUtils.waitUntilDeleted(supplier, Duration.ofSeconds(5), Duration.ofMillis(100));

assertThat(callCount.get()).isGreaterThanOrEqualTo(2);
assertThat(callCount.get()).isEqualTo(1);
}

@Test
void waitUntilDeleted_supplierThrowsNonNotFoundApiException_surfacesFailure() {
RuntimeException failure = new RuntimeException(new ApiException(503, "Server error"));

assertThatThrownBy(() -> WaitUtils.waitUntilDeleted(
() -> {
throw failure;
},
Duration.ofSeconds(5),
Duration.ofMillis(100)))
.isSameAs(failure);
}

@Test
void waitUntilDeleted_supplierThrowsArbitraryRuntimeException_surfacesFailure() {
IllegalStateException failure = new IllegalStateException("Not found");

assertThatThrownBy(() -> WaitUtils.waitUntilDeleted(
() -> {
throw failure;
},
Duration.ofSeconds(5),
Duration.ofMillis(100)))
.isSameAs(failure);
}

@Test
Expand All @@ -187,6 +212,20 @@ void waitUntilDeleted_notDeleted_timesOut() {
.isInstanceOf(TimeoutException.class);
}

@Test
void waitUntilDeleted_interrupted_throwsInterruptedException() {
Thread.currentThread().interrupt();
try {
assertThatThrownBy(() -> WaitUtils.waitUntilDeleted(
() -> createReadyPod(),
Duration.ofSeconds(5),
Duration.ofMillis(100)))
.isInstanceOf(InterruptedException.class);
} finally {
Thread.interrupted();
}
}

@Test
void waitUntilReadyAsync_returnsCompletableFuture() throws Exception {
V1Pod readyPod = createReadyPod();
Expand Down
Loading