Java Code Examples for io.fabric8.kubernetes.api.model.Pod#getStatus()

The following examples show how to use io.fabric8.kubernetes.api.model.Pod#getStatus() . 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: KubernetesResourceUtil.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
public static String getDockerContainerID(Pod pod) {
    PodStatus status = pod.getStatus();
    if (status != null) {
        List<ContainerStatus> containerStatuses = status.getContainerStatuses();
        if (containerStatuses != null) {
            for (ContainerStatus containerStatus : containerStatuses) {
                String containerID = containerStatus.getContainerID();
                if (StringUtils.isNotBlank(containerID)) {
                    String prefix = "://";
                    int idx = containerID.indexOf(prefix);
                    if (idx > 0) {
                        return containerID.substring(idx + prefix.length());
                    }
                    return containerID;
                }
            }
        }
    }
    return null;
}
 
Example 2
Source File: KubernetesClientUtil.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
protected static String getPodCondition(Pod pod) {
    PodStatus podStatus = pod.getStatus();
    if (podStatus == null) {
        return "";
    }
    List<PodCondition> conditions = podStatus.getConditions();
    if (conditions == null || conditions.isEmpty()) {
        return "";
    }


    for (PodCondition condition : conditions) {
        String type = condition.getType();
        if (StringUtils.isNotBlank(type)) {
            if ("ready".equalsIgnoreCase(type)) {
                String statusText = condition.getStatus();
                if (StringUtils.isNotBlank(statusText)) {
                    if (Boolean.parseBoolean(statusText)) {
                        return type;
                    }
                }
            }
        }
    }
    return "";
}
 
Example 3
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns true if the pod is running and ready
 *
 * @param pod Pod object
 * @return boolean value indicating it's status
 */
public static boolean isPodReady(Pod pod) {
    if (!isPodRunning(pod)) {
        return false;
    }

    PodStatus podStatus = pod.getStatus();
    if (podStatus == null) {
        return true;
    }

    List<PodCondition> conditions = podStatus.getConditions();
    if (conditions == null || conditions.isEmpty()) {
        return true;
    }

    // Check "ready" condition
    for (PodCondition condition : conditions) {
        if ("ready".equalsIgnoreCase(condition.getType())) {
            return Boolean.parseBoolean(condition.getStatus());
        }
    }

    return true;
}
 
Example 4
Source File: PublishingStateMonitor.java    From syndesis with Apache License 2.0 6 votes vote down vote up
protected LinkType getPodUrls(Pod pod) {
    LinkType linkType;

    final PodStatus status = pod.getStatus();
    switch (status.getPhase()) {
    case "Pending":
    case "Unknown":
        // get pod events url
        linkType = EVENTS;
        break;
    default:
        // Running, Succeeded or Failed
        // get pod logs url
        linkType = LOGS;
        break;
    }
    return linkType;
}
 
Example 5
Source File: PVCSubPathHelper.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean apply(Pod pod) {
  if (pod.getStatus() == null) {
    return false;
  }
  switch (pod.getStatus().getPhase()) {
    case POD_PHASE_FAILED:
      // fall through
    case POD_PHASE_SUCCEEDED:
      // job is finished.
      return true;
    default:
      // job is not finished.
      return false;
  }
}
 
Example 6
Source File: PodWatcher.java    From data-highway with Apache License 2.0 6 votes vote down vote up
@Override
public void eventReceived(io.fabric8.kubernetes.client.Watcher.Action action, Pod pod) {
  log.info("Event received for pod: {}, action: {}", podName, action);
  PodStatus status = pod.getStatus();
  List<ContainerStatus> containerStatuses = status.getContainerStatuses();
  if (!containerStatuses.isEmpty()) {
    ContainerStatus containerStatus = containerStatuses.get(0);
    ContainerState state = containerStatus.getState();
    ContainerStateTerminated terminated = state.getTerminated();
    if (terminated != null) {
      Integer exitCode = terminated.getExitCode();
      log.info("Container exit code for pod {}: {}", podName, exitCode);
      if (exitCode == 0) {
        exitCodeFuture.complete(0);
      } else {
        exitCodeFuture.completeExceptionally(new RuntimeException("Completed with non zero exit code: " + exitCode));
      }
      resource.delete();
      watch.close();
    } else {
      log.warn("ContainerStateTerminated was null for pod: {}, action {}", podName, action);
    }
  } else {
    log.warn("ContainerStatus list was empty for pod: {}, action {}", podName, action);
  }
}
 
Example 7
Source File: KubernetesTaskLauncher.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
private TaskStatus buildPodStatus(String id) {
	Pod pod = getPodByName(id);
	if (pod == null) {
		return new TaskStatus(id, LaunchState.unknown, new HashMap<>());
	}

	PodStatus podStatus = pod.getStatus();
	if (podStatus == null) {
		return new TaskStatus(id, LaunchState.unknown, new HashMap<>());
	}

	String phase = podStatus.getPhase();

	switch (phase) {
	case "Pending":
		return new TaskStatus(id, LaunchState.launching, new HashMap<>());
	case "Failed":
		return new TaskStatus(id, LaunchState.failed, new HashMap<>());
	case "Succeeded":
		return new TaskStatus(id, LaunchState.complete, new HashMap<>());
	default:
		return new TaskStatus(id, LaunchState.running, new HashMap<>());
	}
}
 
Example 8
Source File: KubernetesPodEventTranslator.java    From styx with Apache License 2.0 5 votes vote down vote up
private static Optional<Event> isInErrorState(WorkflowInstance workflowInstance, Pod pod,
                                              Optional<ContainerStatus> mainContainerStatusOpt) {
  final PodStatus status = pod.getStatus();
  final String phase = status.getPhase();

  if ("NodeLost".equals(pod.getStatus().getReason())) {
    return Optional.of(Event.runError(workflowInstance, "Lost node running pod"));
  }

  switch (phase) {
    case "Pending":
      // check if one or more docker contains failed to pull their image, a possible silent error
      return mainContainerStatusOpt
          .flatMap(KubernetesPodEventTranslator::imageError)
          .map(msg -> Event.runError(workflowInstance, msg));

    case "Succeeded":
    case "Failed":
      if (mainContainerStatusOpt.isEmpty()) {
        return Optional.of(Event.runError(workflowInstance, "Could not find our container in pod"));
      }

      final ContainerStatus containerStatus = mainContainerStatusOpt.get();
      final ContainerStateTerminated terminated = containerStatus.getState().getTerminated();
      if (terminated == null) {
        return Optional.of(Event.runError(workflowInstance, "Unexpected null terminated status"));
      }
      return Optional.empty();

    case "Unknown":
      return Optional.of(Event.runError(workflowInstance, "Pod entered Unknown phase"));

    default:
      return Optional.empty();
  }
}
 
Example 9
Source File: Readiness.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the ready condition of the pod.
 * @param pod   The target pod.
 * @return      The {@link PodCondition} or null if not found.
 */
private static PodCondition getPodReadyCondition(Pod pod) {
  Utils.checkNotNull(pod, "Pod can't be null.");

  if (pod.getStatus() == null || pod.getStatus().getConditions() == null) {
    return null;
  }

  for (PodCondition condition : pod.getStatus().getConditions()) {
    if (POD_READY.equals(condition.getType())) {
      return condition;
    }
  }
  return null;
}
 
Example 10
Source File: PodUtils.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
public static List<ContainerStatus> getContainerStatus(Pod pod) {
    PodStatus podStatus = pod.getStatus();
    if (podStatus == null) {
        return Collections.emptyList();
    }
    return podStatus.getContainerStatuses();
}
 
Example 11
Source File: OnFailure.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean shouldDeletePod(KubernetesCloud cloud, Pod pod) {
    if (pod == null || pod.getStatus() == null) {
        return false;
    }
    boolean hasErrors = pod.getStatus().getPhase().toLowerCase().matches("(failed|unknown)");
    return !hasErrors;
}
 
Example 12
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 13
Source File: KubernetesHelper.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public static String getPodPhase(Pod pod) {
    if (pod != null) {
        PodStatus podStatus = pod.getStatus();
        if (podStatus != null) {
            String actualPhase = podStatus.getPhase();
            return actualPhase != null ? actualPhase : "";
        }
    }
    return "";
}
 
Example 14
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 15
Source File: KubernetesFacade.java    From kubernetes-pipeline-plugin with Apache License 2.0 4 votes vote down vote up
public static final boolean isPodRunning(Pod pod) {
    return pod != null && pod.getStatus() != null && RUNNING_PHASE.equals(pod.getStatus().getPhase());
}
 
Example 16
Source File: KubernetesFacade.java    From kubernetes-pipeline-plugin with Apache License 2.0 4 votes vote down vote up
public static final boolean isPodCompleted(Pod pod) {
    return pod != null && pod.getStatus() != null &&
            (SUCCEEDED_PHASE.equals(pod.getStatus().getPhase()) || FAILED_PHASE.equals(pod.getStatus().getPhase()));
}
 
Example 17
Source File: PVCSubPathHelper.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
private void execute(
    RuntimeIdentity identity,
    String workspaceId,
    String namespace,
    String pvcName,
    String[] commandBase,
    Map<String, String> startOptions,
    String... arguments) {
  final String jobName = commandBase[0];
  final String podName = jobName + '-' + workspaceId;
  final String[] command = buildCommand(commandBase, arguments);
  final Pod pod = newPod(podName, pvcName, command);
  securityContextProvisioner.provision(pod.getSpec());

  KubernetesDeployments deployments = null;
  try {
    deployments = factory.access(workspaceId, namespace).deployments();
    deployments.create(pod);
    watchLogsIfDebugEnabled(deployments, pod, identity, startOptions);
    final Pod finished = deployments.wait(podName, WAIT_POD_TIMEOUT_MIN, POD_PREDICATE::apply);
    PodStatus finishedStatus = finished.getStatus();
    if (POD_PHASE_FAILED.equals(finishedStatus.getPhase())) {
      String logs = deployments.getPodLogs(podName);
      LOG.error(
          "Job command '{}' execution is failed. Logs: {}",
          Arrays.toString(command),
          Strings.nullToEmpty(logs).replace("\n", " \\n")); // Force logs onto one line
    }
  } catch (InfrastructureException ex) {
    LOG.error(
        "Unable to perform '{}' command for the workspace '{}' cause: '{}'",
        Arrays.toString(command),
        workspaceId,
        ex.getMessage());
    deployments.stopWatch(true);
  } finally {
    if (deployments != null) {
      deployments.stopWatch();
      try {
        deployments.delete(podName);
      } catch (InfrastructureException ignored) {
      }
    }
  }
}
 
Example 18
Source File: PodInfo.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
@Override
protected void executePod(Pod podInfo, String podId) {
    System.out.println("Created: " + podInfo.getMetadata().getCreationTimestamp());
    System.out.println("Labels: ");
    Map<String, String> labels = podInfo.getMetadata().getLabels();
    for (Map.Entry<String, String> entry : labels.entrySet()) {
        System.out.println(indent + entry.getKey() + " = " + entry.getValue());
    }
    PodStatus currentState = podInfo.getStatus();
    if (currentState != null) {
        printValue("Host", currentState.getHostIP());
        printValue("IP", currentState.getPodIP());
        printValue("Status", getStatusText(currentState));
    }
    PodSpec spec = podInfo.getSpec();
    if (spec != null) {
        List<Container> containers = spec.getContainers();
        if (notEmpty(containers)) {
            System.out.println("Containers:");
            indentCount++;
            for (Container container : containers) {
                printValue("Name", container.getName());
                printValue("Image", container.getImage());
                printValue("Working Dir", container.getWorkingDir());
                printValue("Command", container.getCommand());

                List<ContainerPort> ports = container.getPorts();
                if (notEmpty(ports)) {
                    println("Ports:");
                    indentCount++;
                    for (ContainerPort port : ports) {
                        printValue("Name", port.getName());
                        printValue("Protocol", port.getProtocol());
                        printValue("Host Port", port.getHostPort());
                        printValue("Container Port", port.getContainerPort());
                    }
                    indentCount--;
                }

                List<EnvVar> envList = container.getEnv();
                if (notEmpty(envList)) {
                    println("Environment:");
                    indentCount++;
                    for (EnvVar env : envList) {
                        printValue(env.getName(), env.getValue());
                    }
                    indentCount--;
                }
                List<VolumeMount> volumeMounts = container.getVolumeMounts();
                if (notEmpty(volumeMounts)) {
                    println("Volume Mounts:");
                    indentCount++;
                    for (VolumeMount volumeMount : volumeMounts) {
                        printValue("Name", volumeMount.getName());
                        printValue("Mount Path", volumeMount.getMountPath());
                        printValue("Read Only", volumeMount.getReadOnly());
                    }
                    indentCount--;
                }
            }
        }

        List<Volume> volumes = spec.getVolumes();
        if (volumes != null) {
            System.out.println("Volumes: ");
            for (Volume volume : volumes) {
                System.out.println(indent + volume.getName());
            }
        }
    }
}