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

The following examples show how to use io.fabric8.kubernetes.api.model.PodList. 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: ReplicaSetRollingUpdater.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
protected PodList listSelectedPods(ReplicaSet obj) {
  FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podLister = pods().inNamespace(namespace);
  if (obj.getSpec().getSelector().getMatchLabels() != null) {
    podLister.withLabels(obj.getSpec().getSelector().getMatchLabels());
  }
  if (obj.getSpec().getSelector().getMatchExpressions() != null) {
    for (LabelSelectorRequirement req : obj.getSpec().getSelector().getMatchExpressions()) {
      switch (req.getOperator()) {
        case "In":
          podLister.withLabelIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "NotIn":
          podLister.withLabelNotIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "DoesNotExist":
          podLister.withoutLabel(req.getKey());
          break;
        case "Exists":
          podLister.withLabel(req.getKey());
          break;
      }
    }
  }
  return podLister.list();
}
 
Example #2
Source File: LabelTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void testWithoutLabel() {
  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=" + Utils.toUrlEncoded("!foo"))
    .andReturn(200, new PodListBuilder().withItems(pod2).build())
    .once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=" + Utils.toUrlEncoded("!app"))
    .andReturn(200, new PodListBuilder().withItems(pod1).build())
    .once();

  KubernetesClient client = server.getClient();
  PodList list = client.pods().inNamespace("test").withoutLabel("foo").list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());

  list = client.pods().inNamespace("test").withoutLabel("app").list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());
}
 
Example #3
Source File: Diagnostics.java    From dekorate with Apache License 2.0 6 votes vote down vote up
public <T extends HasMetadata> void display(T resource) {
 logger.info("Diagnostics for kind: [" + resource.getKind() + "] with name : [" + resource.getMetadata().getName() + "].");
  try {
    PodList podList = pods.list(resource);
    if (podList == null) {
      return;
    }
    for (Pod pod : podList.getItems()) {
      // That should only happen in tests.
      if (pod.getSpec() == null || pod.getSpec().getContainers() == null) {
        continue;
      }

      events(pod);
      for (Container container : pod.getSpec().getContainers()) {
        log(pod, container);
      }
    }
  } catch (Throwable t) {
    // ignore
  }
}
 
Example #4
Source File: LabelTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void testLabelsIn() {
  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=foo%20in%20%28bar%29")
    .andReturn(200, new PodListBuilder().withItems(pod1).build())
    .once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=app%20in%20%28nginx%29")
    .andReturn(200, new PodListBuilder().withItems(pod2).build())
    .once();

  KubernetesClient client = server.getClient();
  Map<String, String> filterLabels = new HashMap<>();

  PodList list = client.pods().inNamespace("test").withLabelIn("foo", "bar").list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());

  filterLabels.put("app", "nginx");
  list = client.pods().inNamespace("test").withLabelIn("app", "nginx").list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());
}
 
Example #5
Source File: LabelTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void testLabelsNotIn() {
  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=foo%20notin%20%28bar%29")
    .andReturn(200, new PodListBuilder().withItems(pod2).build())
    .once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=app%20notin%20%28nginx%29")
    .andReturn(200, new PodListBuilder().withItems(pod1).build())
    .once();

  KubernetesClient client = server.getClient();
  Map<String, String> filterLabels = new HashMap<>();

  PodList list = client.pods().inNamespace("test").withLabelNotIn("foo", "bar").list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());

  filterLabels.put("app", "nginx");
  list = client.pods().inNamespace("test").withLabelNotIn("app", "nginx").list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());

}
 
Example #6
Source File: LabelTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void testWithLabel() {
  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=foo")
    .andReturn(200, new PodListBuilder().withItems(pod1).build())
    .once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=app")
    .andReturn(200, new PodListBuilder().withItems(pod2).build())
    .once();

  KubernetesClient client = server.getClient();
  PodList list = client.pods().inNamespace("test").withLabel("foo").list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());

  list = client.pods().inNamespace("test").withLabel("app").list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());
}
 
Example #7
Source File: JobOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private List<PodResource<Pod, DoneablePod>> doGetLog(boolean isPretty) {
  List<PodResource<Pod, DoneablePod>> pods = new ArrayList<>();
  Job job = fromServer().get();
  String jobUid = job.getMetadata().getUid();

  PodOperationsImpl podOperations = new PodOperationsImpl(new PodOperationContext(context.getClient(),
    context.getConfig(), context.getPlural(), context.getNamespace(), context.getName(), null,
    "v1", context.getCascading(), context.getItem(), context.getLabels(), context.getLabelsNot(),
    context.getLabelsIn(), context.getLabelsNotIn(), context.getFields(), context.getFieldsNot(), context.getResourceVersion(),
    context.getReloadingFromServer(), context.getGracePeriodSeconds(), context.getPropagationPolicy(),
    context.getWatchRetryInitialBackoffMillis(), context.getWatchRetryBackoffMultiplier(), null, null, null, null, null,
    null, null, null, null, false, false, false, null, null,
    null, isPretty, null, null, null, null, null));
  PodList jobPodList = podOperations.withLabel("controller-uid", jobUid).list();

  for (Pod pod : jobPodList.getItems()) {
    OwnerReference ownerReference = KubernetesResourceUtil.getControllerUid(pod);
    if (ownerReference != null && ownerReference.getUid().equals(jobUid)) {
      pods.add(podOperations.withName(pod.getMetadata().getName()));
    }
  }
  return pods;
}
 
Example #8
Source File: ReplicaSetOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private List<PodResource<Pod, DoneablePod>> doGetLog(boolean isPretty) {
  List<PodResource<Pod, DoneablePod>> pods = new ArrayList<>();
  ReplicaSet replicaSet = fromServer().get();
  String rcUid = replicaSet.getMetadata().getUid();

  PodOperationsImpl podOperations = new PodOperationsImpl(new PodOperationContext(context.getClient(),
    context.getConfig(), context.getPlural(), context.getNamespace(), context.getName(), null,
    "v1", context.getCascading(), context.getItem(), context.getLabels(), context.getLabelsNot(),
    context.getLabelsIn(), context.getLabelsNotIn(), context.getFields(), context.getFieldsNot(), context.getResourceVersion(),
    context.getReloadingFromServer(), context.getGracePeriodSeconds(), context.getPropagationPolicy(),
    context.getWatchRetryInitialBackoffMillis(), context.getWatchRetryBackoffMultiplier(), null, null, null, null, null,
    null, null, null, null, false, false, false, null, null,
    null, isPretty, null, null, null, null, null));
  PodList jobPodList = podOperations.withLabels(replicaSet.getMetadata().getLabels()).list();

  for (Pod pod : jobPodList.getItems()) {
    OwnerReference ownerReference = KubernetesResourceUtil.getControllerUid(pod);
    if (ownerReference != null && ownerReference.getUid().equals(rcUid)) {
      pods.add(podOperations.withName(pod.getMetadata().getName()));
    }
  }
  return pods;
}
 
Example #9
Source File: PodTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testListWithFields() {
 server.expect().withPath("/api/v1/namespaces/test/pods?fieldSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2,key3!=value3,key3!=value4")).andReturn(200, new PodListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();
  PodList podList = client.pods()
    .withField("key1", "value1")
    .withField("key2","value2")
    .withoutField("key3","value3")
    .withoutField("key3", "value4")
    .list();


  assertNotNull(podList);
  assertEquals(2, podList.getItems().size());
}
 
Example #10
Source File: StatefulSetOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private List<PodResource<Pod, DoneablePod>> doGetLog(boolean isPretty) {
  List<PodResource<Pod, DoneablePod>> pods = new ArrayList<>();
  StatefulSet statefulSet = fromServer().get();
  String rcUid = statefulSet.getMetadata().getUid();

  PodOperationsImpl podOperations = new PodOperationsImpl(new PodOperationContext(context.getClient(),
    context.getConfig(), context.getPlural(), context.getNamespace(), context.getName(), null,
    "v1", context.getCascading(), context.getItem(), context.getLabels(), context.getLabelsNot(),
    context.getLabelsIn(), context.getLabelsNotIn(), context.getFields(), context.getFieldsNot(), context.getResourceVersion(),
    context.getReloadingFromServer(), context.getGracePeriodSeconds(), context.getPropagationPolicy(),
    context.getWatchRetryInitialBackoffMillis(), context.getWatchRetryBackoffMultiplier(), null, null, null, null, null,
    null, null, null, null, false, false, false, null, null,
    null, isPretty, null, null, null, null, null));
  PodList jobPodList = podOperations.withLabels(statefulSet.getSpec().getTemplate().getMetadata().getLabels()).list();

  for (Pod pod : jobPodList.getItems()) {
    OwnerReference ownerReference = KubernetesResourceUtil.getControllerUid(pod);
    if (ownerReference != null && ownerReference.getUid().equals(rcUid)) {
      pods.add(podOperations.withName(pod.getMetadata().getName()));
    }
  }
  return pods;
}
 
Example #11
Source File: KubernetesClusterTest.java    From kubernetes-elastic-agents with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateKubernetesClusterObject() throws Exception {
    final KubernetesClient kubernetesClient = mock(KubernetesClient.class);

    NodeOperationsImpl nodes = mock(NodeOperationsImpl.class);
    PodOperationsImpl pods = mock(PodOperationsImpl.class);

    when(nodes.list()).thenReturn(new NodeList());
    when(kubernetesClient.nodes()).thenReturn(nodes);

    when(pods.withLabel(Constants.CREATED_BY_LABEL_KEY, Constants.PLUGIN_ID)).thenReturn(pods);
    when(pods.list()).thenReturn(new PodList());
    when(kubernetesClient.pods()).thenReturn(pods);

    final KubernetesCluster cluster = new KubernetesCluster(kubernetesClient);

    verify(kubernetesClient, times(1)).nodes();
    verify(kubernetesClient, times(1)).pods();
}
 
Example #12
Source File: ShouldAssignWorkRequestExecutorTest.java    From kubernetes-elastic-agents with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    initMocks(this);
    when(factory.client(any())).thenReturn(mockedClient);
    when(mockedClient.pods()).thenReturn(mockedOperation);

    final PodList podList = mock(PodList.class);
    when(mockedOperation.list()).thenReturn(podList);
    when(podList.getItems()).thenReturn(Collections.emptyList());

    when(mockedOperation.create(any(Pod.class))).thenAnswer(new Answer<Pod>() {
        @Override
        public Pod answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            return (Pod) args[0];
        }
    });

    agentInstances = new KubernetesAgentInstances(factory);
    properties.put("foo", "bar");
    properties.put("Image", "gocdcontrib/ubuntu-docker-elastic-agent");
    instance = agentInstances.create(new CreateAgentRequest(UUID.randomUUID().toString(), properties, environment, new JobIdentifier(100L)), createClusterProfileProperties(), pluginRequest, consoleLogAppender);
}
 
Example #13
Source File: ServerPingRequestExecutorTest.java    From kubernetes-elastic-agents with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    initMocks(this);
    when(factory.client(any())).thenReturn(mockedClient);
    when(mockedClient.pods()).thenReturn(mockedOperation);
    when(mockedOperation.create(any(Pod.class))).thenAnswer(new Answer<Pod>() {
        @Override
        public Pod answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            return (Pod) args[0];
        }
    });

    when(mockedOperation.withName(anyString())).thenReturn(podResource);
    when(podResource.get()).thenReturn(mockedPod);

    objectMetadata = new ObjectMeta();
    objectMetadata.setCreationTimestamp(getSimpleDateFormat().format(new Date()));

    when(mockedPod.getMetadata()).thenReturn(objectMetadata);

    final PodList podList = mock(PodList.class);
    when(mockedOperation.list()).thenReturn(podList);
    when(podList.getItems()).thenReturn(Collections.emptyList());
}
 
Example #14
Source File: KubernetesHandler.java    From apollo with Apache License 2.0 6 votes vote down vote up
public Optional<String> getServiceLatestCreatedPodName(Service service, Optional<String> groupName) {
    PodList podList = kubernetesClient
            .pods()
            .inNamespace(environment.getKubernetesNamespace())
            .withLabel(ApolloToKubernetes.getApolloDeploymentUniqueIdentifierKey(),
                    ApolloToKubernetes.getApolloPodUniqueIdentifier(environment, service, groupName))
            .list();

    if (podList == null) {
        return Optional.empty();
    }

    Optional<Pod> newestPod = podList.getItems()
                                     .stream()
                                     .sorted((o1, o2) -> {
                                         DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
                                         LocalDateTime pod1 = LocalDateTime.parse(o1.getStatus().getStartTime(), formatter);
                                         LocalDateTime pod2 = LocalDateTime.parse(o2.getStatus().getStartTime(), formatter);
                                         return pod1.compareTo(pod2);
                                     }).findFirst();

    return newestPod.map(pod -> pod
            .getMetadata()
            .getName());
}
 
Example #15
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 #16
Source File: KubernetesDeploymentsTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void shouldReturnOptionalWithPodWhenPodWasNotFoundButDeploymentExists() throws Exception {
  // given
  when(podResource.get()).thenReturn(null);
  when(deploymentResource.get()).thenReturn(deployment);
  LabelSelector labelSelector = mock(LabelSelector.class);
  doReturn(labelSelector).when(deploymentSpec).getSelector();
  doReturn(ImmutableMap.of("deployment", "existing")).when(labelSelector).getMatchLabels();

  FilterWatchListDeletable filterList = mock(FilterWatchListDeletable.class);
  doReturn(filterList).when(podsNamespaceOperation).withLabels(any());
  PodList podList = mock(PodList.class);
  doReturn(singletonList(pod)).when(podList).getItems();
  doReturn(podList).when(filterList).list();

  // when
  Optional<Pod> fetchedPodOpt = kubernetesDeployments.get("existing");

  // then
  assertTrue(fetchedPodOpt.isPresent());
  verify(podsNamespaceOperation).withName("existing");
  verify(deploymentsNamespaceOperation).withName("existing");
  assertEquals(fetchedPodOpt.get(), pod);
}
 
Example #17
Source File: PodOperationsImpl.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
public PodOperationsImpl(PodOperationContext context) {
  super(context.withPlural("pods"));
  this.type = Pod.class;
  this.listType = PodList.class;
  this.doneableType = DoneablePod.class;

  this.containerId = context.getContainerId();
  this.in = context.getIn();
  this.inPipe = context.getInPipe();
  this.out = context.getOut();
  this.outPipe = context.getOutPipe();
  this.err = context.getErr();
  this.errPipe = context.getErrPipe();
  this.errChannel = context.getErrChannel();
  this.errChannelPipe = context.getErrChannelPipe();
  this.withTTY = context.isTty();
  this.withTerminatedStatus = context.isTerminatedStatus();
  this.withTimestamps = context.isTimestamps();
  this.sinceTimestamp = context.getSinceTimestamp();
  this.sinceSeconds = context.getSinceSeconds();
  this.withTailingLines = context.getTailingLines();
  this.withPrettyOutput = context.isPrettyOutput();
  this.execListener = context.getExecListener();
  this.limitBytes = context.getLimitBytes();
  this.bufferSize = context.getBufferSize();
}
 
Example #18
Source File: KubernetesDeploymentsTest.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Test(
    expectedExceptions = InfrastructureException.class,
    expectedExceptionsMessageRegExp = "Found multiple pods in Deployment 'existing'")
public void shouldThrowExceptionWhenMultiplePodsExistsForDeploymentsOnPodFetching()
    throws Exception {
  // given
  when(podResource.get()).thenReturn(null);
  when(deploymentResource.get()).thenReturn(deployment);
  LabelSelector labelSelector = mock(LabelSelector.class);
  doReturn(labelSelector).when(deploymentSpec).getSelector();
  doReturn(ImmutableMap.of("deployment", "existing")).when(labelSelector).getMatchLabels();

  FilterWatchListDeletable filterList = mock(FilterWatchListDeletable.class);
  doReturn(filterList).when(podsNamespaceOperation).withLabels(any());
  PodList podList = mock(PodList.class);
  doReturn(asList(pod, pod)).when(podList).getItems();
  doReturn(podList).when(filterList).list();

  // when
  kubernetesDeployments.get("existing");
}
 
Example #19
Source File: KubernetesPipelineTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void podTemplateWithMultipleLabels() throws Exception {
    PodTemplate pt = new PodTemplate();
    pt.setName("podTemplate");
    pt.setLabel("label1 label2");
    ContainerTemplate jnlp = new ContainerTemplate("jnlp", "jenkins/jnlp-slave:3.35-5-alpine");
    pt.setContainers(Collections.singletonList(jnlp));
    cloud.addTemplate(pt);
    SemaphoreStep.waitForStart("pod/1", b);
    Map<String, String> labels = getLabels(cloud, this, name);
    labels.put("jenkins/label","label1_label2");
    KubernetesSlave node = r.jenkins.getNodes().stream()
            .filter(KubernetesSlave.class::isInstance)
            .map(KubernetesSlave.class::cast)
            .findAny().get();
    assertTrue(node.getAssignedLabels().containsAll(Label.parse("label1 label2")));
    PodList pods = cloud.connect().pods().withLabels(labels).list();
    assertThat(
            "Expected one pod with labels " + labels + " but got: "
                    + pods.getItems().stream().map(pod -> pod.getMetadata()).collect(Collectors.toList()),
            pods.getItems(), hasSize(1));
    SemaphoreStep.success("pod/1", null);
    r.assertBuildStatusSuccess(r.waitForCompletion(b));
}
 
Example #20
Source File: StatefulSetRollingUpdater.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
protected PodList listSelectedPods(StatefulSet obj) {
  FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podLister = pods().inNamespace(namespace);
  if (obj.getSpec().getSelector().getMatchLabels() != null) {
    podLister.withLabels(obj.getSpec().getSelector().getMatchLabels());
  }
  if (obj.getSpec().getSelector().getMatchExpressions() != null) {
    for (LabelSelectorRequirement req : obj.getSpec().getSelector().getMatchExpressions()) {
      switch (req.getOperator()) {
        case "In":
          podLister.withLabelIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "NotIn":
          podLister.withLabelNotIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "DoesNotExist":
          podLister.withoutLabel(req.getKey());
          break;
        case "Exists":
          podLister.withLabel(req.getKey());
          break;
      }
    }
  }
  return podLister.list();
}
 
Example #21
Source File: DeploymentRollingUpdater.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Override
protected PodList listSelectedPods(Deployment obj) {
  FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podLister = pods().inNamespace(namespace);
  if (obj.getSpec().getSelector().getMatchLabels() != null) {
    podLister.withLabels(obj.getSpec().getSelector().getMatchLabels());
  }
  if (obj.getSpec().getSelector().getMatchExpressions() != null) {
    for (LabelSelectorRequirement req : obj.getSpec().getSelector().getMatchExpressions()) {
      switch (req.getOperator()) {
        case "In":
          podLister.withLabelIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "NotIn":
          podLister.withLabelNotIn(req.getKey(), req.getValues().toArray(new String[]{}));
          break;
        case "DoesNotExist":
          podLister.withoutLabel(req.getKey());
          break;
        case "Exists":
          podLister.withLabel(req.getKey());
          break;
      }
    }
  }
  return podLister.list();
}
 
Example #22
Source File: ClusterStatusReportExecutorTest.java    From kubernetes-elastic-agents with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldBuildStatusReportView() throws Exception {
    NodeOperationsImpl nodes = mock(NodeOperationsImpl.class);
    PodOperationsImpl pods = mock(PodOperationsImpl.class);

    when(nodes.list()).thenReturn(new NodeList());
    when(kubernetesClient.nodes()).thenReturn(nodes);

    when(pods.withLabel(Constants.CREATED_BY_LABEL_KEY, Constants.PLUGIN_ID)).thenReturn(pods);
    when(pods.list()).thenReturn(new PodList());
    when(kubernetesClient.pods()).thenReturn(pods);

    final PluginStatusReportViewBuilder builder = mock(PluginStatusReportViewBuilder.class);
    final Template template = mock(Template.class);

    when(builder.getTemplate("status-report.template.ftlh")).thenReturn(template);
    when(builder.build(eq(template), any(KubernetesCluster.class))).thenReturn("status-report");

    final GoPluginApiResponse response = new ClusterStatusReportExecutor(request, builder, kubernetesClientFactory).execute();

    assertThat(response.responseCode(), is(200));
    assertThat(response.responseBody(), is("{\"view\":\"status-report\"}"));
}
 
Example #23
Source File: MockKube.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private MixedOperation<StatefulSet, StatefulSetList, DoneableStatefulSet, RollableScalableResource<StatefulSet, DoneableStatefulSet>>
    buildStatefulSets(MockBuilder<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> podMockBuilder, MixedOperation<Pod, PodList, DoneablePod, PodResource<Pod, DoneablePod>> mockPods,
                      MixedOperation<PersistentVolumeClaim, PersistentVolumeClaimList, DoneablePersistentVolumeClaim,
                              Resource<PersistentVolumeClaim, DoneablePersistentVolumeClaim>> mockPvcs) {
    MixedOperation<StatefulSet, StatefulSetList, DoneableStatefulSet, RollableScalableResource<StatefulSet,
            DoneableStatefulSet>> result = new StatefulSetMockBuilder(podMockBuilder, ssDb, podDb, mockPods, mockPvcs).build();
    return result;
}
 
Example #24
Source File: RollingUpdater.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
/**
 * Lets wait until there are enough Ready pods of the given RC
 */
private void waitUntilPodsAreReady(final T obj, final String namespace, final int requiredPodCount) {
  final CountDownLatch countDownLatch = new CountDownLatch(1);
  final AtomicInteger podCount = new AtomicInteger(0);

  final Runnable readyPodsPoller = () -> {
    PodList podList = listSelectedPods(obj);
    int count = 0;
    List<Pod> items = podList.getItems();
    for (Pod item : items) {
      for (PodCondition c : item.getStatus().getConditions()) {
        if (c.getType().equals("Ready") && c.getStatus().equals("True")) {
          count++;
        }
      }
    }
    podCount.set(count);
    if (count == requiredPodCount) {
      countDownLatch.countDown();
    }
  };

  ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
  ScheduledFuture poller = executor.scheduleWithFixedDelay(readyPodsPoller, 0, 1, TimeUnit.SECONDS);
  ScheduledFuture logger = executor.scheduleWithFixedDelay(() -> LOG.debug("Only {}/{} pod(s) ready for {}: {} in namespace: {} seconds so waiting...",
      podCount.get(), requiredPodCount, obj.getKind(), obj.getMetadata().getName(), namespace), 0, loggingIntervalMillis, TimeUnit.MILLISECONDS);
  try {
    countDownLatch.await(rollingTimeoutMillis, TimeUnit.MILLISECONDS);
    executor.shutdown();
  } catch (InterruptedException e) {
    Thread.currentThread().interrupt();
    poller.cancel(true);
    logger.cancel(true);
    executor.shutdown();
    LOG.warn("Only {}/{} pod(s) ready for {}: {} in namespace: {}  after waiting for {} seconds so giving up",
        podCount.get(), requiredPodCount, obj.getKind(), obj.getMetadata().getName(), namespace, TimeUnit.MILLISECONDS.toSeconds(rollingTimeoutMillis));
  }
}
 
Example #25
Source File: LabelTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void testWithoutLabels() {
  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=" + Utils.toUrlEncoded("foo!=bar"))
    .andReturn(200, new PodListBuilder().withItems(pod2).build())
    .once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=" + Utils.toUrlEncoded("app!=nginx,foo!=bar"))
    .andReturn(200, new PodListBuilder().build())
    .once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=" + Utils.toUrlEncoded("app!=nginx"))
    .andReturn(200, new PodListBuilder().withItems(pod1).build())
    .once();

  KubernetesClient client = server.getClient();
  Map<String, String> filterLabels = new HashMap<>();

  filterLabels.put("foo", "bar");
  PodList list = client.pods().inNamespace("test").withoutLabels(filterLabels).list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());

  filterLabels.put("app", "nginx");
  list = client.pods().inNamespace("test").withoutLabels(filterLabels).list();
  assertNotNull(list);
  assertEquals(0, list.getItems().size());

  filterLabels.remove("foo");
  list = client.pods().inNamespace("test").withoutLabels(filterLabels).list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());
}
 
Example #26
Source File: LabelTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void testBasicList() {
  server.expect().get().withPath("/api/v1/namespaces/test/pods")
    .andReturn(200, new PodListBuilder().withItems(pod1, pod2).build())
    .once();

  KubernetesClient client = server.getClient();

  PodList list = client.pods().inNamespace("test").list();
  assertNotNull(list);
  assertEquals(2, list.getItems().size());
}
 
Example #27
Source File: PodTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testList() {
 server.expect().withPath("/api/v1/namespaces/test/pods").andReturn(200, new PodListBuilder().build()).once();
 server.expect().withPath("/api/v1/namespaces/ns1/pods").andReturn(200, new PodListBuilder()
    .addNewItem().and()
    .addNewItem().and().build()).once();

 server.expect().withPath("/api/v1/pods").andReturn(200, new PodListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .addNewItem()
    .and().build()).once();


  KubernetesClient client = server.getClient();
  PodList podList = client.pods().list();
  assertNotNull(podList);
  assertEquals(0, podList.getItems().size());

  podList = client.pods().inNamespace("ns1").list();
  assertNotNull(podList);
  assertEquals(2, podList.getItems().size());

  podList = client.pods().inAnyNamespace().list();
  assertNotNull(podList);
  assertEquals(3, podList.getItems().size());
}
 
Example #28
Source File: KubernetesAppDeployer.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
private void deletePod(Map<String, String> labels) {
	FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> podsToDelete = client.pods()
			.withLabels(labels);

	if (podsToDelete != null && podsToDelete.list().getItems() != null) {
		boolean podsDeleted = podsToDelete.delete();
		logger.debug(String.format("Pod deleted for: %s - %b", labels, podsDeleted));
	}
}
 
Example #29
Source File: LabelTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
void testWithLabels() {
  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=" + Utils.toUrlEncoded("foo=bar"))
    .andReturn(200, new PodListBuilder().withItems(pod1).build())
    .once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=" + Utils.toUrlEncoded("app=nginx,foo=bar"))
    .andReturn(200, new PodListBuilder().build())
    .once();

  server.expect().get().withPath("/api/v1/namespaces/test/pods?labelSelector=" + Utils.toUrlEncoded("app=nginx"))
    .andReturn(200, new PodListBuilder().withItems(pod2).build())
    .once();

  KubernetesClient client = server.getClient();
  Map<String, String> filterLabels = new HashMap<>();

  filterLabels.put("foo", "bar");
  PodList list = client.pods().inNamespace("test").withLabels(filterLabels).list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());

  filterLabels.put("app", "nginx");
  list = client.pods().inNamespace("test").withLabels(filterLabels).list();
  assertNotNull(list);
  assertEquals(0, list.getItems().size());

  filterLabels.remove("foo");
  list = client.pods().inNamespace("test").withLabels(filterLabels).list();
  assertNotNull(list);
  assertEquals(1, list.getItems().size());
}
 
Example #30
Source File: PodTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testListWithLables() {
 server.expect().withPath("/api/v1/namespaces/test/pods?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2,key3=value3")).andReturn(200, new PodListBuilder().build()).always();
 server.expect().withPath("/api/v1/namespaces/test/pods?labelSelector=" + Utils.toUrlEncoded("key1=value1,key2=value2")).andReturn(200, new PodListBuilder()
    .addNewItem().and()
    .addNewItem().and()
    .addNewItem().and()
    .build()).once();

  KubernetesClient client = server.getClient();
  PodList podList = client.pods()
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .withLabel("key3","value3")
    .list();


  assertNotNull(podList);
  assertEquals(0, podList.getItems().size());

  podList = client.pods()
    .withLabel("key1", "value1")
    .withLabel("key2","value2")
    .list();

  assertNotNull(podList);
  assertEquals(3, podList.getItems().size());
}