Pod size returned zero post kubernetes job creation

72 Views Asked by At

We are creating kubernates job using java kubernates client api (V:5.12.2) like below.

I am struck with two places . Could some one please help on this ?

  1. podList.getItems().size() in below code snippet is some times returning zero even though I see pod get created and with other existing jobs.
  2. How to specify particular label to job pod?
KubernetesClient kubernetesClient = new DefaultKubernetesClient();
String namespace = System.getenv(POD_NAMESPACE);
String jobName = TextUtils.concatenateToString("flatten" + Constants.HYPHEN+ flattenId);
Job jobRequest = createJob(flattenId, authValue);

var jobResult = kubernetesClient.batch().v1().jobs().inNamespace(namespace)
    .create(jobRequest);
PodList podList = kubernetesClient.pods().inNamespace(namespace)
    .withLabel("job-name", jobName).list();


// Wait for pod to complete
var pods = podList.getItems().size();
var terminalPodStatus = List.of("succeeded", "failed");
_LOGGER.info("pods created size:" + pods);
if (pods > 0) {
// returns zero some times. 
var k8sPod = podList.getItems().get(0);
var podName = k8sPod.getMetadata().getName();
kubernetesClient.pods().inNamespace(namespace).withName(podName)
    .waitUntilCondition(pod -> {
      var podPhase = pod.getStatus().getPhase();
       //some logic 
      return terminalPodStatus.contains(podPhase.toLowerCase());
    }, JOB_TIMEOUT, TimeUnit.MINUTES);
kubernetesClient.close();
}
private Job createJob(String flattenId, String authValue) {
       return new JobBuilder()
        .withApiVersion(API_VERSION)
        .withNewMetadata().withName(jobName)
        .withLabels(labels)
        .endMetadata()
        .withNewSpec()
        .withTtlSecondsAfterFinished(300)
        .withBackoffLimit(0)
        .withNewTemplate()
        .withNewMetadata().withAnnotations(LINKERD_INJECT_ANNOTATIONS)
        .endMetadata()
        .withNewSpec()
        .withServiceAccount(Constants.TEST_SERVICEACCOUNT)
        .addNewContainer()
        .addAllToEnv(envVars)
        .withImage(System.getenv(BUILD_JOB_IMAGE))
        .withName(“”test)
        .withCommand("/bin/bash", "-c", "java -jar test.jar")
        .endContainer()
        .withRestartPolicy(RESTART_POLICY_NEVER)
        .endSpec()
        .endTemplate()
        .endSpec()
        .build();
  }
1

There are 1 best solutions below

4
On

Pods are not instantly created as consequence of creating a Job: The Job controller needs to become active and create the Pods accordingly. Depending on the load on your control plane and number of Job instances you may need to wait more or less time.