io.fabric8.kubernetes.client.internal.readiness.Readiness Java Examples

The following examples show how to use io.fabric8.kubernetes.client.internal.readiness.Readiness. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testWaitUntilExistsThenReady() throws InterruptedException {
  Pod pod1 = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().build();


  Pod noReady = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
        .withType("Ready")
        .withStatus("False")
      .endCondition()
    .endStatus()
    .build();

  Pod ready = new PodBuilder(pod1).withNewStatus()
      .addNewCondition()
        .withType("Ready")
        .withStatus("True")
      .endCondition()
    .endStatus()
    .build();

  // so that "waitUntilExists" actually has some waiting to do
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(404, "").times(2);
  // once so that "waitUntilExists" successfully ends
  // and again so that "periodicWatchUntilReady" successfully begins
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, noReady).times(2);

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(100).andEmit(new WatchEvent(ready, "MODIFIED"))
    .done()
    .always();

  KubernetesClient client = server.getClient();
  Pod p = client.pods().withName("pod1").waitUntilReady(5, TimeUnit.SECONDS);
  Assert.assertTrue(Readiness.isPodReady(p));
}
 
Example #2
Source File: DeploymentIT.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void waitTest() throws InterruptedException {
  // Wait for resources to get ready
  ReadyEntity<Deployment> deploymentReady = new ReadyEntity<>(Deployment.class, client, "deployment1", currentNamespace);
  await().atMost(30, TimeUnit.SECONDS).until(deploymentReady);
  Deployment deploymentOne = client.apps().deployments()
    .inNamespace(currentNamespace).withName("deployment1").get();
  assertTrue(Readiness.isDeploymentReady(deploymentOne));
}
 
Example #3
Source File: NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableListImpl.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean isReady() {
  for (final HasMetadata meta : acceptVisitors(get(), visitors)) {
    if (!Readiness.isReady(meta)) {
      return false;
    }
  }
  return true;
}
 
Example #4
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateAndWaitUntilReady() throws InterruptedException {
  Pod pod1 = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().build();


  Pod noReady = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("False")
    .endCondition()
    .endStatus()
    .build();

  Pod ready = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("True")
    .endCondition()
    .endStatus()
    .build();

  // once so that "waitUntilExists" successfully ends
  // and again so that "periodicWatchUntilReady" successfully begins
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, noReady).times(2);
  server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, noReady).once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(1000).andEmit(new WatchEvent(ready, "MODIFIED"))
    .done()
    .always();

  KubernetesClient client = server.getClient();
  Pod p = client.resource(noReady).createOrReplaceAnd().waitUntilReady(10, TimeUnit.SECONDS);
  Assert.assertTrue(Readiness.isPodReady(p));
}
 
Example #5
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void testSkipWatchIfAlreadyMatchingCondition() throws InterruptedException {
  Pod pod1 = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().build();


  Pod noReady = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("False")
    .endCondition()
    .endStatus()
    .build();

  Pod ready = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("True")
    .endCondition()
    .endStatus()
    .build();

  // once not ready, to begin watch
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, ready).once();

  KubernetesClient client = server.getClient();
  Pod p = client.resource(noReady).waitUntilReady(5, TimeUnit.SECONDS);
  Assert.assertTrue(Readiness.isPodReady(p));
}
 
Example #6
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testWaitUntilReady() throws InterruptedException {
  Pod pod1 = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().build();


  Pod noReady = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
        .withType("Ready")
        .withStatus("False")
      .endCondition()
    .endStatus()
    .build();

  Pod ready = new PodBuilder(pod1).withNewStatus()
      .addNewCondition()
        .withType("Ready")
        .withStatus("True")
      .endCondition()
    .endStatus()
    .build();

  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, noReady).once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(ready, "MODIFIED"))
    .done()
    .always();

  KubernetesClient client = server.getClient();
  Pod p = client.resource(noReady).waitUntilReady(5, TimeUnit.SECONDS);
  Assert.assertTrue(Readiness.isPodReady(p));
}
 
Example #7
Source File: AbtractReadyResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testWaitUntilReadyThrows(VertxTestContext context) {
    T resource = resource();

    // This test does not apply to the resource types without the Ready field
    if (!Readiness.isReadinessApplicable(resource.getClass()))  {
        context.completeNow();
    }

    RuntimeException ex = new RuntimeException("This is a test exception");

    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource());
    when(mockResource.isReady()).thenThrow(ex);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractReadyResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.readiness(NAMESPACE, RESOURCE_NAME, 20, 100)
        .onComplete(context.failing(e -> context.verify(() -> {
            assertThat(e, instanceOf(TimeoutException.class));
            async.flag();
        })));
}
 
Example #8
Source File: AbtractReadyResourceOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testWaitUntilReadyUnsuccessful(VertxTestContext context) {
    T resource = resource();

    // This test does not apply to the resource types without the Ready field
    if (!Readiness.isReadinessApplicable(resource.getClass()))  {
        context.completeNow();
    }

    Resource mockResource = mock(resourceType());
    when(mockResource.get()).thenReturn(resource);
    when(mockResource.isReady()).thenReturn(Boolean.FALSE);

    NonNamespaceOperation mockNameable = mock(NonNamespaceOperation.class);
    when(mockNameable.withName(matches(resource.getMetadata().getName()))).thenReturn(mockResource);

    MixedOperation mockCms = mock(MixedOperation.class);
    when(mockCms.inNamespace(matches(resource.getMetadata().getNamespace()))).thenReturn(mockNameable);

    C mockClient = mock(clientType());
    mocker(mockClient, mockCms);

    AbstractReadyResourceOperator<C, T, L, D, R> op = createResourceOperations(vertx, mockClient);

    Checkpoint async = context.checkpoint();
    op.readiness(NAMESPACE, RESOURCE_NAME, 20, 100)
        .onComplete(context.failing(e -> context.verify(() -> {
            assertThat(e, instanceOf(TimeoutException.class));
            verify(mockResource, atLeastOnce()).get();
            verify(mockResource, atLeastOnce()).isReady();
            async.flag();
        })));
}
 
Example #9
Source File: AbstractReadyResourceOperator.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
/**
 * Check if a resource is in the Ready state.
 *
 * @param namespace The namespace.
 * @param name The resource name.
 * @return Whether the resource in in the Ready state.
 */
public boolean isReady(String namespace, String name) {
    R resourceOp = operation().inNamespace(namespace).withName(name);
    T resource = resourceOp.get();
    if (resource != null)   {
        if (Readiness.isReadinessApplicable(resource.getClass())) {
            return Boolean.TRUE.equals(resourceOp.isReady());
        } else {
            return true;
        }
    } else {
        return false;
    }
}
 
Example #10
Source File: PodReadinessWatcher.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
@Override
public void eventReceived(Action action, Pod pod) {
	boolean currentState = Readiness.isPodReady(pod);
	if (this.previousState != currentState) {
		synchronized (this.lock) {
			if (this.previousState != currentState) {
				LOGGER.debug(
						"'{}' readiness status changed to '{}', triggering leadership update",
						this.podName, currentState);
				this.previousState = currentState;
				this.leadershipController.update();
			}
		}
	}
}
 
Example #11
Source File: PodUtils.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public static void waitForPodsReady(LabelSelector selector, int expectPods, boolean containers, Runnable onTimeout) {
    int[] counter = {0};

    TestUtils.waitFor("All pods matching " + selector + "to be ready",
        Constants.POLL_INTERVAL_FOR_RESOURCE_READINESS, Duration.ofMinutes(6).toMillis(),
        () -> {
            List<Pod> pods = kubeClient().listPods(selector);
            if (pods.isEmpty() && expectPods == 0) {
                LOGGER.debug("Expected pods are ready");
                return true;
            }
            if (pods.isEmpty()) {
                LOGGER.debug("Not ready (no pods matching {})", selector);
                return false;
            }
            if (pods.size() != expectPods) {
                LOGGER.debug("Expected pods not ready");
                return false;
            }
            for (Pod pod : pods) {
                if (!Readiness.isPodReady(pod)) {
                    LOGGER.debug("Not ready (at least 1 pod not ready: {})", pod.getMetadata().getName());
                    counter[0] = 0;
                    return false;
                } else {
                    if (containers) {
                        for (ContainerStatus cs : pod.getStatus().getContainerStatuses()) {
                            LOGGER.debug("Not ready (at least 1 container of pod {} not ready: {})", pod.getMetadata().getName(), cs.getName());
                            if (!Boolean.TRUE.equals(cs.getReady())) {
                                return false;
                            }
                        }
                    }
                }
            }
            LOGGER.debug("Pods {} are ready",
                pods.stream().map(p -> p.getMetadata().getName()).collect(Collectors.joining(", ")));
            // When pod is up, it will check that are rolled pods are stable for next 10 polls and then it return true
            return ++counter[0] > 10;
        }, onTimeout);
}
 
Example #12
Source File: KubernetesExtension.java    From dekorate with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeAll(ExtensionContext context) throws Exception {
  KubernetesIntegrationTestConfig config = getKubernetesIntegrationTestConfig(context);
  KubernetesClient client = getKubernetesClient(context);
  KubernetesList list = getKubernetesResources(context);

  if (hasKubernetesConfig() && hasImageConfig()) {
    KubernetesConfig kubernetesConfig = getKubernetesConfig();
    ImageConfiguration imageConfig = getImageConfig().get();
    BuildService buildService = null;
    try {
      BuildServiceFactory buildServiceFactory = BuildServiceFactories.find(getProject(), imageConfig)
        .orElseThrow(() -> new IllegalStateException("No applicable BuildServiceFactory found."));
      buildService = buildServiceFactory.create(getProject(), imageConfig, list.getItems());
    } catch (Exception e) {
      throw DekorateException.launderThrowable("Failed to lookup BuildService.", e);
    }

    //
    // We use the isAutoPushEnabled flag of the @KubernetesApplication annotation and not @KubernetesIntegrationTest.
    // The reason is that the @KubernetesApplication.isAutoPushEnabled() affects the generated manifests (adds the registry).
    // and thus the tests MUST follow.
    if (imageConfig.isAutoPushEnabled()) {
      buildService.prepare();
      buildService.build();
      buildService.push();

    } else if (imageConfig.isAutoBuildEnabled()) {
      buildService.prepare();
      buildService.build();
    } else if (config.isBuildEnabled()) {
      buildService.prepare();
      buildService.build();
    }
  }
  
  if (config.isDeployEnabled()) {
    list.getItems().stream()
      .forEach(i -> {
        client.resourceList(i).createOrReplace();
        LOGGER.info("Created: " + i.getKind() + " name:" + i.getMetadata().getName() + ".");
      });

          List<HasMetadata> waitables = list.getItems().stream().filter(i->
                                                                  i instanceof Deployment ||
                                                                  i instanceof DeploymentConfig ||
                                                                  i instanceof Pod ||
                                                                  i instanceof ReplicaSet ||
                                                                  i instanceof ReplicationController).collect(Collectors.toList());
    long started = System.currentTimeMillis();
    LOGGER.info("Waiting until ready ("+config.getReadinessTimeout()+ " ms)...");
    waitUntilCondition(context, waitables, i -> Readiness.isReady(i), config.getReadinessTimeout(), TimeUnit.MILLISECONDS);
    long ended = System.currentTimeMillis();
    LOGGER.info("Waited: " +  (ended-started)+ " ms.");
    //Display the item status
    waitables.stream().map(r->client.resource(r).fromServer().get())
      .forEach(i -> {
        if (!Readiness.isReady(i)) {
          LOGGER.warning(i.getKind() + ":" + i.getMetadata().getName() + " not ready!");
        }
      });
  }
}
 
Example #13
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
void testRetryOnErrorEventDuringWaitReturnFromAPIIfMatch() throws InterruptedException {
  Pod pod1 = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().build();


  Pod noReady = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("False")
    .endCondition()
    .endStatus()
    .build();

  Pod ready = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("True")
    .endCondition()
    .endStatus()
    .build();

  Status status = new StatusBuilder()
    .withCode(HttpURLConnection.HTTP_FORBIDDEN)
    .build();

  // once not ready, to begin watch
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, noReady).once();
  // once ready, after watch fails
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, ready).once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(status, "ERROR"))
    .done()
    .once();

  KubernetesClient client = server.getClient();
  Pod p = client.resource(noReady).waitUntilReady(5, TimeUnit.SECONDS);
  Assert.assertTrue(Readiness.isPodReady(p));
}
 
Example #14
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
void testRetryOnErrorEventDuringWait() throws InterruptedException {
  Pod pod1 = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().build();

  Pod noReady = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("False")
    .endCondition()
    .endStatus()
    .build();

  Pod ready = new PodBuilder(pod1).withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("True")
    .endCondition()
    .endStatus()
    .build();

  Status status = new StatusBuilder()
    .withCode(HttpURLConnection.HTTP_FORBIDDEN)
    .build();

  // once not ready, to begin watch
  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, noReady).times(2);

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(status, "ERROR"))
    .done()
    .once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?fieldSelector=metadata.name%3Dpod1&resourceVersion=1&watch=true").andUpgradeToWebSocket()
    .open()
    .waitFor(500).andEmit(new WatchEvent(ready, "MODIFIED"))
    .done()
    .once();

  KubernetesClient client = server.getClient();
  Pod p = client.resource(noReady).waitUntilReady(5, TimeUnit.SECONDS);
  Assert.assertTrue(Readiness.isPodReady(p));
}
 
Example #15
Source File: DeploymentTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void uiShouldBeReady() {
    Assert.assertTrue(Readiness.isDeploymentConfigReady(ui));
}
 
Example #16
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean isReady() {
  T i = get();
  return i instanceof HasMetadata && Readiness.isReady((HasMetadata)i);
}
 
Example #17
Source File: BaseOperation.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public T waitUntilReady(long amount, TimeUnit timeUnit) throws InterruptedException {
  return waitUntilCondition(resource -> Objects.nonNull(resource) && Readiness.isReady(resource), amount, timeUnit);
}
 
Example #18
Source File: NamespaceVisitFromServerGetWatchDeleteRecreateWaitApplicableImpl.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean isReady() {
  return Readiness.isReady(get());
}
 
Example #19
Source File: DeploymentTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void restShouldBeReady() {
    Assert.assertTrue(Readiness.isDeploymentConfigReady(rest));
}
 
Example #20
Source File: PodIT.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
public void evict() throws InterruptedException {
  String pdbScope = pod1.getMetadata().getLabels().get("pdb-scope");
  assertNotNull("pdb-scope label is null. is pod1 misconfigured?", pdbScope);

  PodDisruptionBudget pdb = new PodDisruptionBudgetBuilder()
    .withNewMetadata()
    .withName("test-pdb")
    .endMetadata()
    .withSpec(
      new PodDisruptionBudgetSpecBuilder()
        .withMinAvailable(new IntOrString(1))
        .withNewSelector()
        .addToMatchLabels("pdb-scope", pdbScope)
        .endSelector()
        .build()
    )
    .build();

  Pod pod2 = new PodBuilder()
    .withNewMetadata()
    .withName("pod2")
    .addToLabels("pdb-scope", pdbScope)
    .endMetadata()
    .withSpec(pod1.getSpec())
    .build();

  Pod pod3 = new PodBuilder()
    .withNewMetadata()
    .withName("pod3")
    .addToLabels("pdb-scope", pdbScope)
    .endMetadata()
    .withSpec(pod1.getSpec())
    .build();

  client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName())
    .waitUntilReady(30, TimeUnit.SECONDS);

  client.pods().inNamespace(currentNamespace).createOrReplace(pod2);
  client.pods().inNamespace(currentNamespace).withName(pod2.getMetadata().getName())
    .waitUntilReady(30, TimeUnit.SECONDS);

  client.policy().podDisruptionBudget().inNamespace(currentNamespace).createOrReplace(pdb);

  assertTrue(client.pods().inNamespace(currentNamespace).withName(pod2.getMetadata().getName()).evict());
  // cant evict because only one left
  assertFalse(client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName()).evict());
  // ensure it really is still up
  assertTrue(Readiness.isReady(client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName()).fromServer().get()));

  // create another pod to satisfy PDB
  client.pods().inNamespace(currentNamespace).createOrReplace(pod3);
  client.pods().inNamespace(currentNamespace).withName(pod3.getMetadata().getName())
    .waitUntilReady(30, TimeUnit.SECONDS);

  // can now evict
  assertTrue(client.pods().inNamespace(currentNamespace).withName(pod1.getMetadata().getName()).evict());
}
 
Example #21
Source File: MetricsCollector.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    LOGGER.debug("Collecting metrics for active integration pods.");
    try {
        List<Pod> integrationPodList = kubernetes.pods().withLabel("integration").list().getItems();
        Set<String> livePods = new HashSet<>();
        for (Pod pod : integrationPodList) {
            livePods.add(pod.getMetadata().getName());
        }

        integrationPodList
            .stream()
            .filter(p -> Readiness.isReady(p))
            .forEach(p ->
                executor.execute(new PodMetricsReader(
                        kubernetes,
                        p.getMetadata().getName(),
                        p.getMetadata().getAnnotations().get("syndesis.io/integration-name"),
                        p.getMetadata().getLabels().get("syndesis.io/integration-id"),
                        p.getMetadata().getLabels().get("syndesis.io/deployment-version"),
                        rmh))
        );

        Set<String> activeIntegrationIds = dataManager.fetchIds(Integration.class);
        for (String integrationId : activeIntegrationIds) {
            LOGGER.debug("Computing metrics for IntegrationId: {}",integrationId);

            Map<String,RawMetrics> rawMetrics = rmh.getRawMetrics(integrationId);
            IntegrationMetricsSummary imSummary = imh.compute(
                            integrationId,
                            rawMetrics,
                            livePods);
            imh.persist(imSummary);
            rmh.curate(integrationId, rawMetrics, livePods);
        }

        rmh.curate(activeIntegrationIds);
        imh.curate(activeIntegrationIds);

    } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") Exception ex) {
        LOGGER.error("Error while iterating integration pods.", ex);
    }

}