io.fabric8.kubernetes.api.model.PodBuilder Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.PodBuilder. 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: ResourceIT.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void list() {
  Pod listPod1 = new PodBuilder()
    .withNewMetadata().withName("pod3").endMetadata()
    .withNewSpec()
    .addNewContainer().withName("nginx").withImage("nginx").endContainer()
    .endSpec()
    .build();
  client.resourceList(new PodListBuilder().withItems(listPod1).build())
    .inNamespace(currentNamespace)
    .apply();

  assertTrue(client.pods().inNamespace(currentNamespace).withName("pod3") != null);

  boolean bDeleted = client.resourceList(new PodListBuilder().withItems(listPod1).build())
    .inNamespace(currentNamespace)
    .delete();
  assertTrue(bDeleted);
}
 
Example #2
Source File: PodTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteMulti() {
  Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build();
  Pod pod2 = new PodBuilder().withNewMetadata().withName("pod2").withNamespace("ns1").and().build();
  Pod pod3 = new PodBuilder().withNewMetadata().withName("pod3").withNamespace("any").and().build();

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

  KubernetesClient client = server.getClient();

  Boolean deleted = client.pods().inAnyNamespace().delete(pod1, pod2);
  assertTrue(deleted);

  deleted = client.pods().inAnyNamespace().delete(pod3);
  assertFalse(deleted);
}
 
Example #3
Source File: LanderPodFactory.java    From data-highway with Apache License 2.0 6 votes vote down vote up
public Pod newInstance(LanderConfiguration config, List<String> args) {
  String truckParkName = podNameFactory.newName(config);
  log.info("Creating pod named: {}", truckParkName);
  Map<String, String> configMap = configMapSupplier.get().getData();
  return new PodBuilder()
      .withMetadata(new ObjectMetaBuilder()
          .withName(truckParkName)
          .withLabels(labels(config.getRoadName(), configMap))
          .withAnnotations(annotations(configMap))
          .build())
      .withSpec(new PodSpecBuilder()
          .withRestartPolicy(RESTART_POLICY_NEVER)
          .withContainers(container(config.getRoadName(), args, configMap, truckParkName))
          .build())
      .build();
}
 
Example #4
Source File: PropagationPolicyTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should delete a resource with specified PropagationPolicy")
void testDeleteResourceWithSpecifiedPropagationPolicy() throws InterruptedException {
  // Given
  Pod testPod = new PodBuilder().withNewMetadata().withName("testpod").endMetadata().build();
  server.expect().delete().withPath("/api/v1/namespaces/foo/pods/testpod")
    .andReturn(HttpURLConnection.HTTP_OK, testPod)
    .once();
  KubernetesClient client = server.getClient();

  // When
  Boolean isDeleted = client.resource(testPod).inNamespace("foo").withPropagationPolicy(DeletionPropagation.FOREGROUND).delete();

  // Then
  assertTrue(isDeleted);
  assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.FOREGROUND.toString(), server.getLastRequest());
}
 
Example #5
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void testWaitOnConditionDeleted() throws InterruptedException {
  Pod ready = new PodBuilder().withNewMetadata()
    .withName("pod1")
    .withResourceVersion("1")
    .withNamespace("test").and().withNewStatus()
    .addNewCondition()
    .withType("Ready")
    .withStatus("True")
    .endCondition()
    .endStatus()
    .build();

  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(1000).andEmit(new WatchEvent(ready, "DELETED"))
    .done()
    .once();

  KubernetesClient client = server.getClient();
  Pod p = client.pods().withName("pod1").waitUntilCondition(Objects::isNull,8, TimeUnit.SECONDS);
  assertNull(p);
}
 
Example #6
Source File: CacheTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void testCacheIndex() {
  Pod testPodObj = new PodBuilder().withNewMetadata().withName("test-pod").endMetadata().build();

  cache.add(testPodObj);
  cache.replace(Arrays.asList(testPodObj), "0");

  String index = mockIndexFunction(testPodObj).get(0);
  String key = mockKeyFunction(testPodObj);

  List indexedObjectList = cache.byIndex("mock", index);
  assertEquals(testPodObj, indexedObjectList.get(0));

  indexedObjectList = cache.index("mock", testPodObj);
  assertEquals(testPodObj, indexedObjectList.get(0));

  List<String> allExistingKeys = cache.listKeys();
  assertEquals(1, allExistingKeys.size());
  assertEquals(key, allExistingKeys.get(0));
}
 
Example #7
Source File: NodeTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() {
 server.expect().withPath("/api/v1/nodes/node1").andReturn(200, new PodBuilder().build()).once();
 server.expect().withPath("/api/v1/nodes/node2").andReturn(200, new PodBuilder().build()).once();

  KubernetesClient client = server.getClient();

  Node node = client.nodes().withName("node1").get();
  assertNotNull(node);

  node = client.nodes().withName("node2").get();
  assertNotNull(node);

  node = client.nodes().withName("node3").get();
  assertNull(node);
}
 
Example #8
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testResourceReplaceFromLoad() throws Exception {
  server.expect().get().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(200, new PodBuilder().withNewMetadata().withResourceVersion("12345").and().build()).always();

  server.expect().put().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(200, new PodBuilder()
    .withNewMetadata().withResourceVersion("12345").and().build()).once();

  KubernetesClient client = server.getClient();
  List<HasMetadata> result = client.load(getClass().getResourceAsStream("/test-pod-create-from-load.yml")).createOrReplace();
  assertNotNull(result);
  assertEquals(1, result.size());
  Pod pod = (Pod) result.get(0);
  assertEquals("12345", pod.getMetadata().getResourceVersion());

  RecordedRequest request = server.getLastRequest();
  assertEquals("/api/v1/namespaces/test/pods/nginx", request.getPath());
  Pod requestPod = new ObjectMapper().readerFor(Pod.class).readValue(request.getBody().inputStream());
  assertEquals("nginx", requestPod.getMetadata().getName());
}
 
Example #9
Source File: PropagationPolicyTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should delete a resource list with PropagationPolicy=Background")
void testDeleteResourceList() throws InterruptedException {
  // Given
  Pod testPod = new PodBuilder().withNewMetadata().withName("testpod").endMetadata().build();
  server.expect().delete().withPath("/api/v1/namespaces/foo/pods/testpod")
    .andReturn(HttpURLConnection.HTTP_OK, testPod)
    .once();
  KubernetesClient client = server.getClient();

  // When
  Boolean isDeleted = client.resourceList(new KubernetesListBuilder().withItems(testPod).build()).inNamespace("foo").delete();

  // Then
  assertTrue(isDeleted);
  assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.BACKGROUND.toString(), server.getLastRequest());
}
 
Example #10
Source File: PVCSubPathHelper.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
/** Returns new instance of {@link Pod} with given name and command. */
private Pod newPod(String podName, String pvcName, String[] command) {
  final Container container =
      new ContainerBuilder()
          .withName(podName)
          .withImage(jobImage)
          .withImagePullPolicy(imagePullPolicy)
          .withCommand(command)
          .withVolumeMounts(newVolumeMount(pvcName, JOB_MOUNT_PATH, null))
          .withNewResources()
          .endResources()
          .build();
  Containers.addRamLimit(container, jobMemoryLimit);
  Containers.addRamRequest(container, jobMemoryLimit);
  return new PodBuilder()
      .withNewMetadata()
      .withName(podName)
      .endMetadata()
      .withNewSpec()
      .withContainers(container)
      .withVolumes(newVolume(pvcName, pvcName))
      .withRestartPolicy(POD_RESTART_POLICY)
      .endSpec()
      .build();
}
 
Example #11
Source File: ResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelete() {
  Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build();
  Pod pod2 = new PodBuilder().withNewMetadata().withName("pod2").withNamespace("ns1").and().build();
  Pod pod3 = new PodBuilder().withNewMetadata().withName("pod3").withNamespace("any").and().build();

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

  KubernetesClient client = server.getClient();
  Boolean deleted = client.resource(pod1).delete();
  assertTrue(deleted);
  deleted = client.resource(pod2).delete();
  assertTrue(deleted);

  deleted = client.resource(pod3).delete();
  assertFalse(deleted);
}
 
Example #12
Source File: KubernetesDockerRunnerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTolerateCounterCapacityExceptionWhenEmittingEvents() throws Exception {
  // Change the pod status to terminated without notifying the runner through the pod watcher
  var terminatedPod = new PodBuilder(createdPod)
      .withStatus(terminated("Succeeded", 20, null))
      .build();
  when(k8sClient.getPod(POD_NAME)).thenReturn(Optional.of(terminatedPod));

  doThrow(new CounterCapacityException("foo!"))
      .when(stateManager).receive(any(), anyLong());

  verifyZeroInteractions(stateManager);

  // Poll for execution status
  var stateData = StateData.newBuilder().executionId(POD_NAME).build();
  var runState = RunState.create(WORKFLOW_INSTANCE, State.SUBMITTED, stateData);
  kdr.poll(runState);

  verify(stateManager).receive(any(), anyLong());
}
 
Example #13
Source File: PodSetControllerTest.java    From podsetoperatorinjava with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should create pods for with respect to a specified PodSet")
public void testReconcile() throws InterruptedException {
    // Given
    String testNamespace = "ns1";
    PodSet testPodSet = getPodSet("example-podset", testNamespace, "0800cff3-9d80-11ea-8973-0e13a02d8ebd");
    server.expect().post().withPath("/api/v1/namespaces/" + testNamespace + "/pods")
            .andReturn(HttpURLConnection.HTTP_CREATED, new PodBuilder().withNewMetadata().withName("pod1-clone").endMetadata().build())
            .times(testPodSet.getSpec().getReplicas());
    KubernetesClient client = server.getClient();

    SharedInformerFactory informerFactory = client.informers();
    MixedOperation<PodSet, PodSetList, DoneablePodSet, Resource<PodSet, DoneablePodSet>> podSetClient = client.customResources(podSetCustomResourceDefinition, PodSet.class, PodSetList.class, DoneablePodSet.class);
    SharedIndexInformer<Pod> podSharedIndexInformer = informerFactory.sharedIndexInformerFor(Pod.class, PodList.class, RESYNC_PERIOD_MILLIS);
    SharedIndexInformer<PodSet> podSetSharedIndexInformer = informerFactory.sharedIndexInformerForCustomResource(podSetCustomResourceDefinitionContext, PodSet.class, PodSetList.class, RESYNC_PERIOD_MILLIS);
    PodSetController podSetController = new PodSetController(client, podSetClient, podSharedIndexInformer, podSetSharedIndexInformer, testNamespace);

    // When
    podSetController.reconcile(testPodSet);

    // Then
    RecordedRequest recordedRequest = server.getLastRequest();
    assertEquals("POST", recordedRequest.getMethod());
    assertTrue(recordedRequest.getBody().readUtf8().contains(testPodSet.getMetadata().getName()));
}
 
Example #14
Source File: DefaultHostExternalServiceExposureStrategyTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
  Container container = new ContainerBuilder().withName("main").build();
  Pod pod =
      new PodBuilder()
          .withNewMetadata()
          .withName("pod")
          .endMetadata()
          .withNewSpec()
          .withContainers(container)
          .endSpec()
          .build();

  kubernetesEnvironment =
      KubernetesEnvironment.builder().setPods(ImmutableMap.of("pod", pod)).build();
  externalServerExposer =
      new ExternalServerExposer<>(
          new DefaultHostExternalServiceExposureStrategy(), emptyMap(), "%s");
}
 
Example #15
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testResourceCreateFromLoad() throws Exception {
  server.expect().get().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(404, new StatusBuilder().build()).always();

  server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, new PodBuilder()
    .withNewMetadata().withResourceVersion("12345").and().build()).once();

  KubernetesClient client = server.getClient();
  List<HasMetadata> result = client.load(getClass().getResourceAsStream("/test-pod-create-from-load.yml")).createOrReplace();
  assertNotNull(result);
  assertEquals(1, result.size());
  Pod pod = (Pod) result.get(0);
  assertEquals("12345", pod.getMetadata().getResourceVersion());

  RecordedRequest request = server.getMockServer().takeRequest();
  assertEquals("/api/v1/namespaces/test/pods/nginx", request.getPath());

  request = server.getMockServer().takeRequest();
  Pod requestPod = new ObjectMapper().readerFor(Pod.class).readValue(request.getBody().inputStream());
  assertEquals("nginx", requestPod.getMetadata().getName());
}
 
Example #16
Source File: MultiHostExternalServiceExposureStrategyTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
  Container container = new ContainerBuilder().withName("main").build();
  Pod pod =
      new PodBuilder()
          .withNewMetadata()
          .withName("pod")
          .endMetadata()
          .withNewSpec()
          .withContainers(container)
          .endSpec()
          .build();

  kubernetesEnvironment =
      KubernetesEnvironment.builder().setPods(ImmutableMap.of("pod", pod)).build();
  externalServerExposer =
      new ExternalServerExposer<>(
          new MultiHostExternalServiceExposureStrategy(DOMAIN, MULTI_HOST_STRATEGY),
          emptyMap(),
          "%s");
}
 
Example #17
Source File: OpenShiftEnvironmentFactoryTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void addPodsWhenRecipeContainsThem() throws Exception {
  // given
  Pod pod =
      new PodBuilder()
          .withNewMetadata()
          .withName("pod")
          .endMetadata()
          .withSpec(new PodSpec())
          .build();
  when(k8sRecipeParser.parse(any(InternalRecipe.class))).thenReturn(singletonList(pod));

  // when
  KubernetesEnvironment osEnv = osEnvFactory.doCreate(internalRecipe, emptyMap(), emptyList());

  // then
  assertEquals(osEnv.getPodsCopy().size(), 1);
  assertEquals(osEnv.getPodsCopy().get("pod"), pod);

  assertEquals(osEnv.getPodsData().size(), 1);
  assertEquals(osEnv.getPodsData().get("pod").getMetadata(), pod.getMetadata());
  assertEquals(osEnv.getPodsData().get("pod").getSpec(), pod.getSpec());
}
 
Example #18
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateFromLoad() throws Exception {
  server.expect().get().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(404, new StatusBuilder().build()).always();

  server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, new PodBuilder()
    .withNewMetadata().withResourceVersion("12345").and().build()).once();

  KubernetesClient client = server.getClient();
  Pod pod = client.pods().load(getClass().getResourceAsStream("/test-pod-create-from-load.yml")).createOrReplace();
  assertNotNull(pod);
  assertEquals("12345", pod.getMetadata().getResourceVersion());

  RecordedRequest request = server.getLastRequest();
  Pod requestPod = new ObjectMapper().readerFor(Pod.class).readValue(request.getBody().inputStream());
  assertEquals("nginx", requestPod.getMetadata().getName());
}
 
Example #19
Source File: ResourceListTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testDelete() {
  Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build();
  Pod pod2 = new PodBuilder().withNewMetadata().withName("pod2").withNamespace("ns1").and().build();
  Pod pod3 = new PodBuilder().withNewMetadata().withName("pod3").withNamespace("any").and().build();


  server.expect().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(200, pod1).times(2);
  server.expect().withPath("/api/v1/namespaces/ns1/pods/pod2").andReturn(200, pod2).times(2);
  server.expect().withPath("/api/v1/namespaces/any/pods/pod3").andReturn(200, pod3).times(1);

  KubernetesClient client = server.getClient();

  //First time all items should be deleted.
  Boolean deleted = client.resourceList(new PodListBuilder().withItems(pod1, pod2, pod3).build()).delete();
  assertTrue(deleted);

  //Now we expect pod3 to fail.
  deleted = client.resourceList(new PodListBuilder().withItems(pod1, pod2, pod3).build()).delete();
  assertFalse(deleted);
}
 
Example #20
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testReplaceFromLoad() throws Exception {
  server.expect().get().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(200, new PodBuilder().build()).always();

  server.expect().put().withPath("/api/v1/namespaces/test/pods/nginx").andReturn(200, new PodBuilder()
    .withNewMetadata().withResourceVersion("12345").and().build()).once();

  KubernetesClient client = server.getClient();
  Pod pod = client.pods().load(getClass().getResourceAsStream("/test-pod-create-from-load.yml")).createOrReplace();
  assertNotNull(pod);
  assertEquals("12345", pod.getMetadata().getResourceVersion());


  RecordedRequest request = server.getLastRequest();
  assertEquals("/api/v1/namespaces/test/pods/nginx", request.getPath());
  Pod requestPod = new ObjectMapper().readerFor(Pod.class).readValue(request.getBody().inputStream());
  assertEquals("nginx", requestPod.getMetadata().getName());
}
 
Example #21
Source File: KubernetesDockerRunnerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPollPodStatusAndEmitEvents() throws Exception {

  // Change the pod status to terminated without notifying the runner through the pod watcher
  final Pod terminatedPod = new PodBuilder(createdPod)
      .withStatus(terminated("Succeeded", 20, null))
      .build();
  when(k8sClient.getPod(POD_NAME)).thenReturn(Optional.of(terminatedPod));

  // Poll for execution status
  var stateData = StateData.newBuilder().executionId(POD_NAME).build();
  var runState = RunState.create(WORKFLOW_INSTANCE, State.SUBMITTED, stateData);
  kdr.poll(runState);

  // Verify that the runner found out that the pod is terminated and emits events
  verify(stateManager, atLeastOnce()).receive(
      Event.started(WORKFLOW_INSTANCE),
      -1);
  verify(stateManager, atLeastOnce()).receive(
      Event.terminate(WORKFLOW_INSTANCE, Optional.of(20)),
      0);
}
 
Example #22
Source File: WaitUntilReadyExample.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) throws IOException, InterruptedException {
  try (final KubernetesClient client = new DefaultKubernetesClient()) {
    Pod pod = new PodBuilder()
      .withNewMetadata().withName("myapp-pod").withLabels(Collections.singletonMap("app", "myapp-pod")).endMetadata()
      .withNewSpec()
      .addNewContainer()
      .withName("myapp-container")
      .withImage("busybox:1.28")
      .withCommand("sh", "-c", "echo 'The app is running!'; sleep 10")
      .endContainer()
      .addNewInitContainer()
      .withName("init-myservice")
      .withImage("busybox:1.28")
      .withCommand("sh", "-c", "echo 'inititalizing...'; sleep 5")
      .endInitContainer()
      .endSpec()
      .build();

    String namespace = "default";
    pod = client.pods().inNamespace(namespace).create(pod);
    log("Pod created, waiting for it to get ready");
    client.resource(pod).inNamespace(namespace).waitUntilReady(10, TimeUnit.SECONDS);
    log("Pod is ready now.");
    client.pods().inNamespace(namespace).withName(pod.getMetadata().getName()).watchLog(System.out);
    client.resource(pod).inNamespace(namespace).delete();
  }
  System.exit(0);
}
 
Example #23
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 #24
Source File: ResourceListTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateOrReplace() {
  Pod pod1 = new PodBuilder().withNewMetadata().withName("pod1").withNamespace("test").and().build();

  server.expect().get().withPath("/api/v1/namespaces/test/pods/pod1").andReturn(404, "").once();
  server.expect().post().withPath("/api/v1/namespaces/test/pods").andReturn(201, pod1).once();

  KubernetesClient client = server.getClient();
  List<HasMetadata> response = client.resourceList(new PodListBuilder().addToItems(pod1).build()).createOrReplace();
  assertTrue(response.contains(pod1));
}
 
Example #25
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 #26
Source File: KubernetesComponentIntegrityValidatorTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(
    expectedExceptions = DevfileFormatException.class,
    expectedExceptionsMessageRegExp =
        "Failed to validate content reference of component 'ref' of type 'kubernetes': Component 'ref' of type 'kubernetes' contains an entry point that doesn't match any container.")
public void shouldThrowExceptionOnEntrypointNotMatchingAnyContainer() throws Exception {
  // given
  when(kubernetesRecipeParser.parse(any(String.class)))
      .thenReturn(
          Collections.singletonList(
              new PodBuilder()
                  .withNewSpec()
                  .addNewContainer()
                  .withName("container")
                  .endContainer()
                  .endSpec()
                  .build()));

  ComponentImpl component = new ComponentImpl();
  component.setType(KUBERNETES_COMPONENT_TYPE);
  component.setReferenceContent("content");
  component.setReference("ref");

  EntrypointImpl entrypoint = new EntrypointImpl();
  entrypoint.setContainerName("not that container");
  component.setEntrypoints(Collections.singletonList(entrypoint));

  // when
  validator.validateComponent(component, __ -> "");

  // then exception is thrown
}
 
Example #27
Source File: KubernetesComponentIntegrityValidatorTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void shouldApplyEntrypoint() throws Exception {
  // given
  when(kubernetesRecipeParser.parse(any(String.class)))
      .thenReturn(
          Arrays.asList(
              new PodBuilder()
                  .withNewSpec()
                  .addNewContainer()
                  .withName("container_a")
                  .endContainer()
                  .endSpec()
                  .build(),
              new PodBuilder()
                  .withNewSpec()
                  .addNewContainer()
                  .withName("container_b")
                  .endContainer()
                  .endSpec()
                  .build()));

  ComponentImpl component = new ComponentImpl();
  component.setType(KUBERNETES_COMPONENT_TYPE);
  component.setReferenceContent("content");
  component.setReference("ref");

  EntrypointImpl entrypoint = new EntrypointImpl();
  entrypoint.setContainerName("container_a");
  component.setEntrypoints(Collections.singletonList(entrypoint));

  // when
  validator.validateComponent(component, __ -> "");

  // then no exception is thrown
}
 
Example #28
Source File: KubernetesComponentIntegrityValidatorTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
@Test(
    expectedExceptions = DevfileFormatException.class,
    expectedExceptionsMessageRegExp =
        "Failed to validate content reference of component 'ref' of type 'kubernetes': The selector of the component 'ref' of type 'kubernetes' filters out all objects from the list.")
public void shouldThrowExceptionOnSelectorFilteringOutEverything() throws Exception {
  // given
  when(kubernetesRecipeParser.parse(any(String.class)))
      .thenReturn(
          Collections.singletonList(
              new PodBuilder()
                  .withNewMetadata()
                  .addToLabels("app", "test")
                  .endMetadata()
                  .build()));

  Map<String, String> selector = new HashMap<>();
  selector.put("app", "a different value");

  ComponentImpl component = new ComponentImpl();
  component.setType(KUBERNETES_COMPONENT_TYPE);
  component.setReference("ref");
  component.setSelector(selector);
  component.setReferenceContent("content");

  // when
  validator.validateComponent(component, __ -> "");

  // then exception is thrown
}
 
Example #29
Source File: KubernetesInternalRuntimeTest.java    From che with Eclipse Public License 2.0 5 votes vote down vote up
private static Pod mockPod(List<Container> containers) {
  final Pod pod =
      new PodBuilder()
          .withNewMetadata()
          .withName(WORKSPACE_POD_NAME)
          .withLabels(
              ImmutableMap.of(
                  POD_SELECTOR, WORKSPACE_POD_NAME, CHE_ORIGINAL_NAME_LABEL, WORKSPACE_POD_NAME))
          .endMetadata()
          .withNewSpec()
          .withContainers(containers)
          .endSpec()
          .build();
  return pod;
}
 
Example #30
Source File: PodPriorityExample.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) throws InterruptedException {
  String master = "https://192.168.99.100:8443/";
  if (args.length == 1) {
    master = args[0];
  }

  log("Using master with url ", master);
  Config config = new ConfigBuilder().withMasterUrl(master).build();
  try (final KubernetesClient client = new DefaultKubernetesClient(config)) {
    PriorityClass priorityClass = new PriorityClassBuilder()
      .withNewMetadata().withName("high-priority").endMetadata()
      .withValue(new Integer(100000))
      .withGlobalDefault(false)
      .withDescription("This priority class should be used for XYZ service pods only.")
      .build();
    client.scheduling().priorityClass().create(priorityClass);

    client.pods().inNamespace("default").create(new PodBuilder()
      .withNewMetadata().withName("nginx").withLabels(Collections.singletonMap("env", "test")).endMetadata()
      .withNewSpec()
      .addToContainers(new ContainerBuilder().withName("nginx").withImage("nginx").withImagePullPolicy("IfNotPresent").build())
      .withPriorityClassName("high-priority")
      .endSpec()
      .build()
    );
  } catch (KubernetesClientException e) {
    e.printStackTrace();
    log("Could not create resource", e.getMessage());
  }
}