Search in sources :

Example 1 with KubernetesClientTimeoutException

use of io.fabric8.kubernetes.client.KubernetesClientTimeoutException in project kubernetes-client by fabric8io.

the class BaseOperationTest method testWaitUntilFailureCompletion.

@Test
void testWaitUntilFailureCompletion() throws MalformedURLException, IOException {
    final AtomicInteger httpExecutionCounter = new AtomicInteger(0);
    HttpClient mockClient = newHttpClientWithSomeFailures(httpExecutionCounter, 2);
    CompletableFuture<List<Pod>> future = new CompletableFuture<>();
    BaseOperation<Pod, PodList, Resource<Pod>> baseOp = new BaseOperation(new OperationContext().withConfig(new ConfigBuilder().withMasterUrl("https://172.17.0.2:8443").build()).withPlural("pods").withName("test-pod").withHttpClient(mockClient)) {

        @Override
        public CompletableFuture<List<Pod>> informOnCondition(Predicate condition) {
            return future;
        }
    };
    baseOp.setType(Pod.class);
    // When
    try {
        baseOp.waitUntilCondition(Objects::isNull, 1, TimeUnit.MILLISECONDS);
        fail("should timeout");
    } catch (KubernetesClientTimeoutException e) {
    }
    // Then
    assertTrue(future.isCancelled());
}
Also used : OperationContext(io.fabric8.kubernetes.client.dsl.internal.OperationContext) PodOperationContext(io.fabric8.kubernetes.client.dsl.internal.PodOperationContext) PodList(io.fabric8.kubernetes.api.model.PodList) Pod(io.fabric8.kubernetes.api.model.Pod) Resource(io.fabric8.kubernetes.client.dsl.Resource) BaseOperation(io.fabric8.kubernetes.client.dsl.internal.BaseOperation) Predicate(java.util.function.Predicate) KubernetesClientTimeoutException(io.fabric8.kubernetes.client.KubernetesClientTimeoutException) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpClient(io.fabric8.kubernetes.client.http.HttpClient) Objects(java.util.Objects) ConfigBuilder(io.fabric8.kubernetes.client.ConfigBuilder) List(java.util.List) PodList(io.fabric8.kubernetes.api.model.PodList) Test(org.junit.jupiter.api.Test)

Example 2 with KubernetesClientTimeoutException

use of io.fabric8.kubernetes.client.KubernetesClientTimeoutException in project kubernetes-client by fabric8io.

the class ResourceListTest method testPartialSuccessfulWaitUntilCondition.

@Test
void testPartialSuccessfulWaitUntilCondition() {
    Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withResourceVersion("1").withNamespace("ns1").and().build();
    Pod noReady1 = createReadyFrom(pod1, "False");
    Pod pod2 = new PodBuilder().withNewMetadata().withName("pod2").withResourceVersion("1").withNamespace("ns1").and().build();
    Pod noReady2 = createReadyFrom(pod2, "False");
    Pod ready2 = createReadyFrom(pod2, "True");
    Predicate<HasMetadata> isReady = p -> "Pod".equals(p.getKind()) && ((Pod) p).getStatus().getConditions().stream().anyMatch(c -> "True".equals(c.getStatus()));
    // The pods are never ready if you request them directly.
    ResourceTest.list(server, noReady1);
    ResourceTest.list(server, noReady2);
    Status gone = new StatusBuilder().withCode(HTTP_GONE).build();
    // This pod has a non-retryable error.
    server.expect().get().withPath("/api/v1/namespaces/ns1/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&allowWatchBookmarks=true&watch=true").andUpgradeToWebSocket().open().waitFor(500).andEmit(new WatchEvent(gone, "ERROR")).done().once();
    // This pod succeeds.
    server.expect().get().withPath("/api/v1/namespaces/ns1/pods?fieldSelector=metadata.name%3Dpod2&resourceVersion=1&allowWatchBookmarks=true&watch=true").andUpgradeToWebSocket().open().waitFor(500).andEmit(new WatchEvent(ready2, "MODIFIED")).done().once();
    KubernetesList list = new KubernetesListBuilder().withItems(pod1, pod2).build();
    final ListVisitFromServerGetDeleteRecreateWaitApplicable<HasMetadata> ops = client.resourceList(list).inNamespace("ns1");
    KubernetesClientTimeoutException ex = assertThrows(KubernetesClientTimeoutException.class, () -> ops.waitUntilCondition(isReady, 5, SECONDS));
    assertThat(ex.getResourcesNotReady()).containsExactly(pod1);
}
Also used : Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) BeforeEach(org.junit.jupiter.api.BeforeEach) IntOrString(io.fabric8.kubernetes.api.model.IntOrString) StatusBuilder(io.fabric8.kubernetes.api.model.StatusBuilder) KubernetesClientTimeoutException(io.fabric8.kubernetes.client.KubernetesClientTimeoutException) HTTP_OK(java.net.HttpURLConnection.HTTP_OK) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) PodBuilder(io.fabric8.kubernetes.api.model.PodBuilder) EnableKubernetesMockClient(io.fabric8.kubernetes.client.server.mock.EnableKubernetesMockClient) NamespaceListVisitFromServerGetDeleteRecreateWaitApplicable(io.fabric8.kubernetes.client.dsl.NamespaceListVisitFromServerGetDeleteRecreateWaitApplicable) AssertionsForInterfaceTypes.assertThat(org.assertj.core.api.AssertionsForInterfaceTypes.assertThat) Status(io.fabric8.kubernetes.api.model.Status) Service(io.fabric8.kubernetes.api.model.Service) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) ListVisitFromServerGetDeleteRecreateWaitApplicable(io.fabric8.kubernetes.client.dsl.ListVisitFromServerGetDeleteRecreateWaitApplicable) ServiceBuilder(io.fabric8.kubernetes.api.model.ServiceBuilder) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList) KubernetesListBuilder(io.fabric8.kubernetes.api.model.KubernetesListBuilder) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Predicate(java.util.function.Predicate) Pod(io.fabric8.kubernetes.api.model.Pod) WatchEvent(io.fabric8.kubernetes.api.model.WatchEvent) HTTP_UNAVAILABLE(java.net.HttpURLConnection.HTTP_UNAVAILABLE) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) PodListBuilder(io.fabric8.kubernetes.api.model.PodListBuilder) ConfigMap(io.fabric8.kubernetes.api.model.ConfigMap) ConfigMapBuilder(io.fabric8.kubernetes.api.model.ConfigMapBuilder) Test(org.junit.jupiter.api.Test) List(java.util.List) KubernetesMockServer(io.fabric8.kubernetes.client.server.mock.KubernetesMockServer) HTTP_CONFLICT(java.net.HttpURLConnection.HTTP_CONFLICT) HTTP_CREATED(java.net.HttpURLConnection.HTTP_CREATED) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) KubernetesClient(io.fabric8.kubernetes.client.KubernetesClient) HTTP_GONE(java.net.HttpURLConnection.HTTP_GONE) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Status(io.fabric8.kubernetes.api.model.Status) KubernetesListBuilder(io.fabric8.kubernetes.api.model.KubernetesListBuilder) KubernetesClientTimeoutException(io.fabric8.kubernetes.client.KubernetesClientTimeoutException) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) Pod(io.fabric8.kubernetes.api.model.Pod) PodBuilder(io.fabric8.kubernetes.api.model.PodBuilder) StatusBuilder(io.fabric8.kubernetes.api.model.StatusBuilder) WatchEvent(io.fabric8.kubernetes.api.model.WatchEvent) KubernetesList(io.fabric8.kubernetes.api.model.KubernetesList) Test(org.junit.jupiter.api.Test)

Example 3 with KubernetesClientTimeoutException

use of io.fabric8.kubernetes.client.KubernetesClientTimeoutException in project kubernetes-client by fabric8io.

the class NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl method waitUntilCondition.

@Override
public List<HasMetadata> waitUntilCondition(Predicate<HasMetadata> condition, long amount, TimeUnit timeUnit) {
    List<? extends Resource<HasMetadata>> operations = getResources();
    if (operations.isEmpty()) {
        return Collections.emptyList();
    }
    // this strategy is very costly in terms of threads - by not exposing the underlying futures
    // we have to create a thread for each item that mostly waits
    final ExecutorService executor = Executors.newFixedThreadPool(operations.size(), Utils.daemonThreadFactory(this));
    try {
        List<HasMetadata> items = operations.stream().map(Resource::get).collect(Collectors.toList());
        final List<CompletableFuture<HasMetadata>> futures = new ArrayList<>(items.size());
        for (final Resource<HasMetadata> impl : operations) {
            futures.add(CompletableFuture.supplyAsync(() -> impl.waitUntilCondition(condition, amount, timeUnit)));
        }
        final List<HasMetadata> results = new ArrayList<>();
        final List<HasMetadata> itemsWithConditionNotMatched = new ArrayList<>();
        for (int i = 0; i < items.size(); i++) {
            final HasMetadata meta = items.get(i);
            try {
                CompletableFuture<HasMetadata> future = futures.get(i);
                // just get each result as the timeout is enforced below
                results.add(future.get());
            } catch (ExecutionException e) {
                itemsWithConditionNotMatched.add(meta);
                logAsNotReady(e.getCause(), meta);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw KubernetesClientException.launderThrowable(e);
            }
        }
        if (!itemsWithConditionNotMatched.isEmpty()) {
            throw new KubernetesClientTimeoutException(itemsWithConditionNotMatched, amount, timeUnit);
        }
        return results;
    } finally {
        executor.shutdownNow();
    }
}
Also used : HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata) ArrayList(java.util.ArrayList) KubernetesClientTimeoutException(io.fabric8.kubernetes.client.KubernetesClientTimeoutException) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutorService(java.util.concurrent.ExecutorService) ExecutionException(java.util.concurrent.ExecutionException)

Example 4 with KubernetesClientTimeoutException

use of io.fabric8.kubernetes.client.KubernetesClientTimeoutException in project styx by spotify.

the class MeteredFabric8KubernetesClientProxyTest method reportKubernetesClientTimeoutException.

@Test
public void reportKubernetesClientTimeoutException() {
    doThrow(new KubernetesClientTimeoutException(List.of(), 10L, TimeUnit.SECONDS)).when(fabric8KubernetesClient).listPods();
    try {
        proxy.listPods();
        fail("Expected exception");
    } catch (Exception ignored) {
    }
    verify(stats).recordKubernetesOperationError("listPods", "kubernetes-client-timeout", 0);
}
Also used : KubernetesClientTimeoutException(io.fabric8.kubernetes.client.KubernetesClientTimeoutException) KubernetesClientException(io.fabric8.kubernetes.client.KubernetesClientException) KubernetesClientTimeoutException(io.fabric8.kubernetes.client.KubernetesClientTimeoutException) ExpectedException(org.junit.rules.ExpectedException) Test(org.junit.Test)

Example 5 with KubernetesClientTimeoutException

use of io.fabric8.kubernetes.client.KubernetesClientTimeoutException in project strimzi-kafka-operator by strimzi.

the class MockBuilder method nameScopedMocks.

/**
 * Mock operations on the given {@code resource} which are scoped to accessing the given {@code resourceName}.
 * For example the methods accessible from
 * {@code client.configMaps().inNamespace(ns).withName(resourceName)...}
 *
 * @param resourceName The resource name
 * @param resource The (mocked) resource
 */
@SuppressWarnings("unchecked")
protected void nameScopedMocks(String resourceName, R resource) {
    mockGet(resourceName, resource);
    mockWatch(resourceName, resource);
    mockCreate(resourceName, resource);
    mockSetStatus(resourceName, resource);
    when(resource.createOrReplace(any())).thenAnswer(i -> {
        T resource2 = i.getArgument(0);
        if (db.containsKey(resourceName)) {
            return resource.patch(resource2);
        } else {
            return doCreate(resourceName, resource2);
        }
    });
    when(resource.withGracePeriod(anyLong())).thenReturn(resource);
    mockWithPropagationPolicy(resource);
    mockPatch(resourceName, resource);
    when(resource.edit()).thenAnswer(i -> {
        T t = resource.get();
        Function f = i.getArgument(0);
        return doPatch(t.getMetadata().getName(), resource, (T) f.apply(t));
    });
    when(resource.edit(any(UnaryOperator.class))).thenAnswer(i -> {
        T t = resource.get();
        Function f = i.getArgument(0);
        return doPatch(t.getMetadata().getName(), resource, (T) f.apply(t));
    });
    mockDelete(resourceName, resource);
    mockIsReady(resourceName, resource);
    try {
        when(resource.waitUntilCondition(any(), anyLong(), any())).thenAnswer(i -> {
            Predicate<T> p = i.getArgument(0);
            T t = resource.get();
            boolean done = p.test(t);
            long argument = i.getArgument(1);
            TimeUnit tu = i.getArgument(2);
            long deadline = System.currentTimeMillis() + tu.toMillis(argument);
            while (!done) {
                Thread.sleep(1_000);
                if (System.currentTimeMillis() > deadline) {
                    throw new TimeoutException();
                }
                t = resource.get();
                done = p.test(t);
            }
            return t;
        });
    } catch (KubernetesClientTimeoutException e) {
        throw new RuntimeException(e);
    }
}
Also used : KubernetesClientTimeoutException(io.fabric8.kubernetes.client.KubernetesClientTimeoutException) Function(java.util.function.Function) TimeUnit(java.util.concurrent.TimeUnit) UnaryOperator(java.util.function.UnaryOperator) KubernetesClientTimeoutException(io.fabric8.kubernetes.client.KubernetesClientTimeoutException) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

KubernetesClientTimeoutException (io.fabric8.kubernetes.client.KubernetesClientTimeoutException)9 Pod (io.fabric8.kubernetes.api.model.Pod)4 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)3 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)3 List (java.util.List)3 Predicate (java.util.function.Predicate)3 ConfigMap (io.fabric8.kubernetes.api.model.ConfigMap)2 ConfigMapBuilder (io.fabric8.kubernetes.api.model.ConfigMapBuilder)2 IntOrString (io.fabric8.kubernetes.api.model.IntOrString)2 KubernetesList (io.fabric8.kubernetes.api.model.KubernetesList)2 KubernetesListBuilder (io.fabric8.kubernetes.api.model.KubernetesListBuilder)2 PodBuilder (io.fabric8.kubernetes.api.model.PodBuilder)2 PodListBuilder (io.fabric8.kubernetes.api.model.PodListBuilder)2 Service (io.fabric8.kubernetes.api.model.Service)2 ServiceBuilder (io.fabric8.kubernetes.api.model.ServiceBuilder)2 Status (io.fabric8.kubernetes.api.model.Status)2 StatusBuilder (io.fabric8.kubernetes.api.model.StatusBuilder)2 WatchEvent (io.fabric8.kubernetes.api.model.WatchEvent)2 KubernetesClient (io.fabric8.kubernetes.client.KubernetesClient)2 ListVisitFromServerGetDeleteRecreateWaitApplicable (io.fabric8.kubernetes.client.dsl.ListVisitFromServerGetDeleteRecreateWaitApplicable)2