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

The following examples show how to use io.fabric8.kubernetes.api.model.PodStatus. 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: 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 #2
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 #3
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 #4
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 #5
Source File: K8sPodManagerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
private static Pod createK8sPod(String uid, String name) {
    ObjectMeta meta = new ObjectMeta();
    meta.setUid(uid);
    meta.setName(name);

    PodStatus status = new PodStatus();
    status.setPhase("Running");

    Pod pod = new Pod();
    pod.setApiVersion("v1");
    pod.setKind("pod");
    pod.setMetadata(meta);
    pod.setStatus(status);

    return pod;
}
 
Example #6
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 #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: KubeCloudInstanceImpl.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@NotNull
@Override
public Date getStartedTime() {
    final PodStatus podStatus = myPod.getStatus();
    if(podStatus == null) return myCreationTime;
    try {
        final List<PodCondition> podConditions = podStatus.getConditions();
        if (podConditions != null && !podConditions.isEmpty()) {
            for (PodCondition podCondition : podConditions) {
                if (PodConditionType.valueOf(podCondition.getType()) == PodConditionType.Ready)
                    return myPodTransitionTimeFormat.parse(podCondition.getLastTransitionTime());
            }
        }
        String startTime = podStatus.getStartTime();
        return !StringUtil.isEmpty(startTime) ? myPodStartTimeFormat.parse(startTime) : myCreationTime;
    } catch (ParseException e) {
        throw new KubeCloudException("Failed to get instance start date", e);
    }
}
 
Example #9
Source File: KubernetesGCPServiceAccountSecretManagerTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
@Parameters({"Failed", "Succeeded"})
public void shouldRemoveServiceAccountSecretsAndKeysUsedByTerminatedPods(String phase) throws Exception {
  final Secret secret = fakeServiceAccountKeySecret(
      SERVICE_ACCOUNT, SECRET_EPOCH, "json-key", "p12-key", EXPIRED_CREATION_TIMESTAMP.toString());

  when(secretList.getItems()).thenReturn(List.of(secret));

  final KubernetesSecretSpec secretSpec = KubernetesSecretSpec.builder()
      .serviceAccountSecret(secret.getMetadata().getName())
      .build();
  final Pod pod = createPod(WORKFLOW_INSTANCE, RUN_SPEC_WITH_SA, secretSpec);

  final PodStatus podStatus = podStatus(phase);
  pod.setStatus(podStatus);

  sut.cleanup();
  verify(serviceAccountKeyManager).deleteKey(keyName(SERVICE_ACCOUNT, "json-key"));
  verify(serviceAccountKeyManager).deleteKey(keyName(SERVICE_ACCOUNT, "p12-key"));
  verify(k8sClient).deleteSecret(secret.getMetadata().getName());
  verify(stats).recordServiceAccountCleanup();
}
 
Example #10
Source File: KubeUtils.java    From teamcity-kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Nullable
public static CloudErrorInfo getErrorMessage(@Nullable PodStatus podStatus){
    if (podStatus == null)
        return null;

    if (!podStatus.getPhase().equalsIgnoreCase("Failed")){
        return null;
    }
    final String message = podStatus.getMessage();
    final String reason = podStatus.getReason();
    if (message == null && reason == null){
        return new CloudErrorInfo("Unknown error occurred");
    }
    if (message == null){
        return new CloudErrorInfo(reason);
    }
    if (reason == null){
        return new CloudErrorInfo(message);
    }
    return new CloudErrorInfo(String.format("%s:%s", reason, message));
}
 
Example #11
Source File: KubernetesLanderTest.java    From data-highway with Apache License 2.0 5 votes vote down vote up
private PodStatus terminatedPostStatus(int exitCode) {
  ContainerStatus containerStatus = new ContainerStatus();
  containerStatus.setState(terminatedStateWithExitCode(exitCode));
  PodStatus podStatus = new PodStatus();
  podStatus.setContainerStatuses(Collections.singletonList(containerStatus));
  return podStatus;
}
 
Example #12
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 #13
Source File: SystemtestsKubernetesApps.java    From enmasse with Apache License 2.0 5 votes vote down vote up
private static Predicate<Pod> conditionIsTrue(final String type) {
    return p -> Optional.ofNullable(p)
            .map(Pod::getStatus)
            .map(PodStatus::getConditions)
            .flatMap(o -> o.stream().filter(c -> type.equals(c.getType())).findFirst())
            .map(PodCondition::getStatus)
            .map("True"::equals)
            .orElse(false);
}
 
Example #14
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 #15
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 #16
Source File: KubeApiConnectorImpl.java    From teamcity-kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public PodStatus getPodStatus(@NotNull String podName) {
    return withKubernetesClient(kubernetesClient -> {
        final Pod podNow = kubernetesClient.pods().withName(podName).get();
        return podNow == null ? null : podNow.getStatus();
    });
}
 
Example #17
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 #18
Source File: KubeUtils.java    From teamcity-kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@NotNull
public static InstanceStatus mapPodPhase(@NotNull PodStatus podStatus) {
    if (podStatus == null){
        return InstanceStatus.SCHEDULED_TO_START;
    }
    final String phase = podStatus.getPhase();
    return myPhasesMap.getOrDefault(phase, InstanceStatus.UNKNOWN);
}
 
Example #19
Source File: KubernetesDockerRunnerTest.java    From styx with Apache License 2.0 4 votes vote down vote up
@Parameters({
    "Running,   20, true",
    "Running,   1,  true",
    "Running,   0,  true",
    "Succeeded, 20, true",
    "Succeeded, 1,  true",
    "Succeeded, 0,  true",
    "Failed,    20, true",
    "Failed,    1,  true",
    "Running,   20, false",
    "Running,   1,  false",
    "Running,   0,  false",
    "Succeeded, 20, false",
    "Succeeded, 1,  false",
    "Succeeded, 0,  false",
    "Failed,    20, false",
    "Failed,    1,  false"
})
@Test
public void shouldCompleteWithStatusCodeOnMainContainerTerminated(String phase, int code,
    boolean withKeepaliveContainer) throws Exception {

  final PodStatus podStatus = podStatusNoContainer(phase);

  podStatus.getContainerStatuses()
      .add(new ContainerStatusBuilder()
          .withState(terminatedContainerState(code, ""))
          .withName(MAIN_CONTAINER_NAME)
          .build());

  // Verify that old pods without a keepalive container are also correctly handled
  if (withKeepaliveContainer) {
    podStatus.getContainerStatuses()
        .add(new ContainerStatusBuilder()
            .withName(KEEPALIVE_CONTAINER_NAME)
            .withNewState().withNewRunning().endRunning().endState()
            .build());
  }

  createdPod.setStatus(podStatus);
  receiveAndProcessEvent(Watcher.Action.MODIFIED, createdPod);

  verify(stateManager).receive(Event.started(WORKFLOW_INSTANCE), -1);
  verify(stateManager).receive(Event.terminate(WORKFLOW_INSTANCE, Optional.of(code)), 0);
}
 
Example #20
Source File: PodRetentionTest.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
private PodStatus buildStatus(String phase) {
    return new PodStatusBuilder().withPhase(phase).build();
}
 
Example #21
Source File: AllContainersRunningPodWatcher.java    From kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
public PodStatus getPodStatus() {
    return this.pod.getStatus();
}
 
Example #22
Source File: DeploymentStateMonitorControllerTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static Pod getPod(PodStatus status, String name) {
    return new PodBuilder().withNewStatusLike(status).endStatus().withNewMetadata().withName(name).endMetadata().build();
}
 
Example #23
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 #24
Source File: KubeApiConnector.java    From teamcity-kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Nullable
PodStatus getPodStatus(@NotNull String podName);
 
Example #25
Source File: KubernetesPodEventTranslatorTest.java    From styx with Apache License 2.0 4 votes vote down vote up
static PodStatus podStatusNoContainer(String phase) {
  return new PodStatusBuilder()
      .withPhase(phase)
      .build();
}
 
Example #26
Source File: KubernetesPodEventTranslatorTest.java    From styx with Apache License 2.0 4 votes vote down vote up
static PodStatus waiting(String phase, String reason, String message) {
  return podStatus(phase, true, waitingContainerState(reason, message), false);
}
 
Example #27
Source File: KubernetesPodEventTranslatorTest.java    From styx with Apache License 2.0 4 votes vote down vote up
static PodStatus waiting(String phase, String reason) {
  return podStatus(phase, true, waitingContainerState(reason), false);
}
 
Example #28
Source File: KubernetesPodEventTranslatorTest.java    From styx with Apache License 2.0 4 votes vote down vote up
static PodStatus terminated(String phase, Integer exitCode, String message) {
  return podStatus(phase, true, terminatedContainerState(exitCode, message), false);
}
 
Example #29
Source File: KubernetesPodEventTranslatorTest.java    From styx with Apache License 2.0 4 votes vote down vote up
static PodStatus running(boolean ready) {
  return podStatus("Running", ready, runningContainerState(), true);
}
 
Example #30
Source File: FakeKubeApiConnector.java    From teamcity-kubernetes-plugin with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public PodStatus getPodStatus(@NotNull final String podName) {
  return null;
}