Pods

Read more on Kubernets Pods. In client-go, PodInterface includes all the APIs to deal with Pods.

  • List

kubectl

kubectl get pods -n <namespace>

client-go

import (
    "context"

    "k8s.io/client-go/kubernetes"
    v1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func ListPods(clientset kubernetes.Interface, namespace string) ([]v1.Pod, error) {
    pods, err := clientset.CoreV1().Pods(namespace).List(context.TODO(), metav1.ListOptions{})

    if err != nil {
        return nil, err
    }

    return pods.Items, nil
}

kubectl get pods -n <namespace> displays 5 columns:

| NAME                          | READY | STATUS  | RESTARTS | AGE |
|-------------------------------|-------|---------|----------|-----|
| kube-flannel-ds-amd64-gdltp   | 1/1   | Running | 0        | 14d |

1. Name

Name is the Metadata of Pod.

2. Status

To see if a Node is Pending, Running, Succeeded, Failed or Unknown:

import (
    "k8s.io/api/core/v1"
)

func Status(pod *v1.Pod) v1.PodPhase {
    return pod.Status.Phase
}

3. Restarts

Get the restart count of the Pod:

func RestartCount(pod *v1.Pod) int32 {
    if len(pod.Status.ContainerStatuses) > 0 {
        return pod.Status.ContainerStatuses[0].RestartCount
    }
	
    return 0
}

4. Age

I believe the Age of the Pod could be calculated from the CreationTimestamp as well. Or you could calculate it from the StartTime of the Pod.

func Age(pod *v1.Pod) uint {
    diff := uint(time.Now().Sub(pod.Status.StartTime.Time).Hours())
    return uint(diff / 24)
}
  • Get

kubectl

kubectl get pod <pod_name> -n <namespace> -o yaml

client-go

func GetPod(clientset kubernetes.Interface, namespace, name string) (*v1.Pod, error) {
    return clientset.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{})
}