Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch kubernetes pod status to be completed in client-go

I am creating a pod in k8 client go and making a watch to get notified for when the pod has completed so that i can read the logs of the pod. The watch interface doesnt seem to provide any events on the channel. Here is the code, how would I get notified that the pod status is now completed and is ready to read the logs

func readLogs(clientset *kubernetes.Clientset) {
// namespace := "default"
// label := "cithu"
var (
    pod *v1.Pod
    // watchface watch.Interface
    err error
)
// returns a pod after creation

pod, err = createPod(clientset)
fmt.Println(pod.Name, pod.Status, err)

if watchface, err = clientset.CoreV1().Pods(namespace).Watch(metav1.ListOptions{
    LabelSelector: pod.Name,
}); err != nil {
    log.Fatalf(err.Error())
}

// How do I get notified when the pod.Status == completed
}
like image 331
mohd.gadi Avatar asked Sep 29 '18 10:09

mohd.gadi


People also ask

How do I check my Kubernetes pod status?

Using kubectl describe pods to check kube-system If the output from a specific pod is desired, run the command kubectl describe pod pod_name --namespace kube-system . The Status field should be "Running" - any other status will indicate issues with the environment.

What is completed status in Kubernetes pod?

what is the pod status completed mean ? That means inside pod's container process has been successfully completed.

How do I know what processes are running in pods?

Kubernetes' probes can help to determine whether a process in a pod is executing and is not stuck in a zombie state. You can check by executing the following command kubectl exec -it <pod_name> /bin/bash -c env.

How do I view pod logs?

When kubectl describe pod does not show any information about an error, we can use another kubectl command, that is, logs . The kubectl logs command allows us to print container logs, and we can also view them in real time as well.


1 Answers

The events can be listed using the following snippet. You can then process the pod events as needed.

label := ""
for k := range pod.GetLabels() {
    label = k
    break
}
watch, err := clientset.CoreV1().Pods(namespace).Watch(metav1.ListOptions{
    LabelSelector: label,
})
if err != nil {
    log.Fatal(err.Error())
}
go func() {
    for event := range watch.ResultChan() {
        fmt.Printf("Type: %v\n", event.Type)
        p, ok := event.Object.(*v1.Pod)
        if !ok {
            log.Fatal("unexpected type")
        }
        fmt.Println(p.Status.ContainerStatuses)
        fmt.Println(p.Status.Phase)
    }
}()
time.Sleep(5 * time.Second)
like image 189
Tushar Dudani Avatar answered Nov 26 '22 15:11

Tushar Dudani