Java Code Examples for io.fabric8.kubernetes.api.model.PodList#getItems()

The following examples show how to use io.fabric8.kubernetes.api.model.PodList#getItems() . 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: 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 2
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 3
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 4
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 5
Source File: ReplicationControllerOperationsImpl.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<>();
  ReplicationController rc = fromServer().get();
  String rcUid = rc.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(rc.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 6
Source File: VerifyIntegrationTestAction.java    From yaks with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve pod running state.
 * @param integration
 * @return
 */
private Pod getRunningIntegrationPod(String integration) {
    PodList pods = client.pods().inNamespace(CamelKHelper.namespace()).withLabel("camel.apache.org/integration", integration).list();
    if (pods.getItems().size() == 0) {
        return null;
    }
    for (Pod p : pods.getItems()) {
        if (p.getStatus() != null && "Running".equals(p.getStatus().getPhase())) {
            return p;
        }
    }
    return null;
}
 
Example 7
Source File: PortForwardService.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private Pod getNewestPod(LabelSelector selector) {
    FilterWatchListDeletable<Pod, PodList, Boolean, Watch, Watcher<Pod>> pods =
            KubernetesHelper.withSelector(kubernetes.pods(), selector, log);

    PodList list = pods.list();
    if (list != null) {
        List<Pod> items = list.getItems();
        return getNewestPod(items);
    }
    return null;
}
 
Example 8
Source File: PodsList.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
protected TablePrinter podsAsTable(PodList pods) {
    TablePrinter table = new TablePrinter();
    table.columns("id", "image(s)", "host", "labels", "status");
    List<Pod> items = pods.getItems();
    if (items == null) {
        items = Collections.EMPTY_LIST;
    }
    Filter<Pod> filter = KubernetesHelper.createPodFilter(filterText.getValue());
    for (Pod item : items) {
        if (filter.matches(item)) {
            String id = KubernetesHelper.getName(item);
            PodStatus podStatus = item.getStatus();
            String status = "";
            String host = "";
            if (podStatus != null) {
                status = KubernetesHelper.getStatusText(podStatus);
                host = podStatus.getHostIP();
            }
            Map<String, String> labelMap = item.getMetadata().getLabels();
            String labels = KubernetesHelper.toLabelsString(labelMap);
            PodSpec spec = item.getSpec();
            if (spec != null) {
                List<Container> containerList = spec.getContainers();
                for (Container container : containerList) {
                    String image = container.getImage();
                    table.row(id, image, host, labels, status);

                    id = "";
                    host = "";
                    status = "";
                    labels = "";
                }
            }
        }
    }
    return table;
}
 
Example 9
Source File: KubernetesAppDeployer.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
@Override
public String getLog(String appId) {
	Map<String, String> selector = new HashMap<>();
	selector.put(SPRING_APP_KEY, appId);
	PodList podList = client.pods().withLabels(selector).list();
	StringBuilder logAppender = new StringBuilder();
	for (Pod pod : podList.getItems()) {

		if(pod.getSpec().getContainers().size() > 1){
			for(Container container : pod.getSpec().getContainers()) {
				if(container.getEnv().stream().anyMatch(envVar -> "SPRING_CLOUD_APPLICATION_GUID".equals(envVar.getName()))) {
					//find log for this container
					logAppender.append(this.client.pods()
											   .withName(pod.getMetadata().getName())
											   .inContainer(container.getName())
											   .tailingLines(500).getLog());
					break;
				}

			}
		}
		else{
			logAppender.append(this.client.pods().withName(pod.getMetadata().getName()).tailingLines(500).getLog());
		}
	}

	return logAppender.toString();
}
 
Example 10
Source File: AbstractKubernetesDeployer.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
protected AppStatus buildAppStatus(String id, PodList podList, ServiceList services) {
	AppStatus.Builder statusBuilder = AppStatus.of(id);
	Service service = null;
	if (podList != null && podList.getItems() != null) {
		for (Pod pod : podList.getItems()) {
			String deploymentKey = pod.getMetadata().getLabels().get(SPRING_DEPLOYMENT_KEY);
			for (Service svc : services.getItems()) {
				if (svc.getMetadata().getName().equals(deploymentKey)) {
					service = svc;
					break;
				}
			}
			//find the container with the correct env var
			for(Container container : pod.getSpec().getContainers()) {
				if(container.getEnv().stream().anyMatch(envVar -> "SPRING_CLOUD_APPLICATION_GUID".equals(envVar.getName()))) {
					//find container status for this container
					Optional<ContainerStatus> containerStatusOptional =
						pod.getStatus().getContainerStatuses()
						   .stream().filter(containerStatus -> container.getName().equals(containerStatus.getName()))
						   .findFirst();

					statusBuilder.with(new KubernetesAppInstanceStatus(pod, service, properties, containerStatusOptional.orElse(null)));

					break;
				}
			}
		}
	}
	return statusBuilder.build();
}
 
Example 11
Source File: KubernetesCloud.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Query for running or pending pods
 */
private List<Pod> getActiveSlavePods(KubernetesClient client, String templateNamespace, Map<String, String> podLabels) {
    PodList slaveList = client.pods().inNamespace(templateNamespace).withLabels(podLabels).list();
    List<Pod> activeSlavePods = null;
    // JENKINS-53370 check for nulls
    if (slaveList != null && slaveList.getItems() != null) {
        activeSlavePods = slaveList.getItems().stream() //
                .filter(x -> x.getStatus().getPhase().toLowerCase().matches("(running|pending)"))
                .collect(Collectors.toList());
    }
    return activeSlavePods;
}
 
Example 12
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));
  }
}