gokuberneteskubernetes-go-client

How to use the kubernetes go-client to get the same Pod status info that kubectl gives


Using the kubernetes go-client (k8s.io/client-go/kubernetes), I know how to get pod.Status and I find the pod.Status.Phase useful (docs). For example, I can output the Pod Status Phase of all Pods using this:

    ...
    api := clientset.CoreV1()
    pods, err := api.Pods("").List(metav1.ListOptions{})
    for i, pod := range pods.Items {
        podstatusPhase := string(pod.Status.Phase)
        podCreationTime := pod.GetCreationTimestamp()
        age := time.Since(podCreationTime.Time).Round(time.Second)

        podInfo := fmt.Sprintf("[%d] Pod: %s, Phase: %s , Created: %s, Age: %s", i, pod.GetName(), podstatusPhase, podCreationTime, age.String())
        fmt.Println(podInfo)
    }

However, the phase is a little simplistic in that it only ever shows 5 values (Pending, Running, Succeeded, Failed, Unknown). I'd rather get the same info that kubectl get pods gives in the Status column, for example:

$ kubectl get pods

NAME                                        READY   STATUS              RESTARTS   AGE     IP             NODE                           NOMINATED NODE   READINESS GATES
moby-dick-cron-scheduler-1564578660-bg4sb   0/2     ContainerCreating   0          178m    <none>         ip-10-30-13-151.ec2.internal   <none>           <none>
notifications-missed-calls-1564564740-js762 0/2     Init:0/1            0          6h49m   <none>         ip-10-30-13-6.ec2.internal     <none>           <none>
antivirus-scanner-cron-1564576740-sd6hh     0/2     Completed           0          3h30m   10.30.13.169   ip-10-30-13-151.ec2.internal   <none>           <none>

In particular, I'm interested in Init:0/1 and PodInitializing statuses. The Pods in these statuses just show as "Pending" when using pod.Status.Phase.

Is there a way to get a Status such as Init:0/1 using k8s.io/client-go/kubernetes? or is there no short-cut, and I'd need to re-calculate it the same way kubectl does? I guess it uses Pod Status Conditions and container statuses to build the info. If I need to re-calculate it, maybe I can use the kubectl sourcecode? Does anyone know where I can find the relevant bit? (I have very limited golang experience)


Solution

  • I was able to show the exact same information as kubectl get pods. Please see the answer here: https://stackoverflow.com/a/74722781/7129053