9

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
}
Ellis Percival
  • 4,632
  • 2
  • 24
  • 34
mohd.gadi
  • 495
  • 1
  • 7
  • 15

2 Answers2

11

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)
Ellis Percival
  • 4,632
  • 2
  • 24
  • 34
Tushar Dudani
  • 151
  • 1
  • 4
  • `fmt.Println(p.Status.Phase)` does not show `COMPLETED` status when all containers stop in a pod like `kubectl get pods -w` does. – Janshair Khan Jun 18 '20 at 19:22
-5

You keep could keep checking the pod status in a loop and whenever the status changes to successful, you're done

for {
    pod, _ := clientset.CoreV1().Pods(Namespace).Get(podName, metav1.GetOptions{})
    if pod.Status.Phase != corev1.PodPending {
        break
    }
}
pod, _ := clientset.CoreV1().Pods(corev1.NamespaceDefault).Get(podName, metav1.GetOptions{})
if pod.Status.Phase != corev1.PodSucceeded {
    return false, fmt.Errorf("Pod did not succeed/complete")
}
return true, nil
him229
  • 1,284
  • 1
  • 11
  • 21