Skip to content

Commit

Permalink
Move pod processing into function to make linter happy about defer call
Browse files Browse the repository at this point in the history
Signed-off-by: Marvin Beckers <marvin@kubermatic.com>
  • Loading branch information
embik committed Apr 4, 2024
1 parent 2aaedcd commit 5ddb68e
Showing 1 changed file with 34 additions and 30 deletions.
64 changes: 34 additions & 30 deletions pkg/service/list_images.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,39 +95,43 @@ func PrintListImages(ctx context.Context, clientSet *kubernetes.Clientset) error

// Check if the pod is in a terminal state
if pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {
// Trigger desired action (e.g., fetching and printing logs)
log.Printf("Pod completed: %s", pod.Status.Phase)

// Fetch the logs
req := clientSet.CoreV1().Pods("default").GetLogs(pod.Name, &corev1.PodLogOptions{})
podLogs, err := req.Stream(ctx)
if err != nil {
return fmt.Errorf("failed to fetch Pod logs: %w", err)
}
defer podLogs.Close()

// Read and print the logs
buf := new(bytes.Buffer)
_, err = io.Copy(buf, podLogs)
if err != nil {
return fmt.Errorf("failed to read Pod logs: %w", err)
}

lines := strings.Split(buf.String(), "\n")
sort.Strings(lines)
for _, line := range lines {
fmt.Println(line)
}

err = clientSet.CoreV1().Pods("default").Delete(ctx, pod.Name, metav1.DeleteOptions{})
if err != nil {
return fmt.Errorf("failed to delete Pod: %w", err)
}
return nil
return handlePod(ctx, clientSet, pod)
}

case <-time.After(2 * time.Second):
// Check status every 2 seconds
}
}
}

func handlePod(ctx context.Context, clientSet *kubernetes.Clientset, pod *corev1.Pod) error {
// Trigger desired action (e.g., fetching and printing logs)
log.Printf("Pod completed: %s", pod.Status.Phase)

// Fetch the logs
req := clientSet.CoreV1().Pods("default").GetLogs(pod.Name, &corev1.PodLogOptions{})
podLogs, err := req.Stream(ctx)
if err != nil {
return fmt.Errorf("failed to fetch Pod logs: %w", err)
}
defer podLogs.Close()

// Read and print the logs
buf := new(bytes.Buffer)
_, err = io.Copy(buf, podLogs)
if err != nil {
return fmt.Errorf("failed to read Pod logs: %w", err)
}

lines := strings.Split(buf.String(), "\n")
sort.Strings(lines)
for _, line := range lines {
fmt.Println(line)
}

err = clientSet.CoreV1().Pods("default").Delete(ctx, pod.Name, metav1.DeleteOptions{})
if err != nil {
return fmt.Errorf("failed to delete Pod: %w", err)
}

return nil
}

0 comments on commit 5ddb68e

Please sign in to comment.