Skip to content

Commit dc4c246

Browse files
authored
Merge pull request #2 from Revolyssup/revolyssup/fix1
fix: wait for container to start before fetching logs
2 parents 9f688b8 + 5a02484 commit dc4c246

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

pkg/logs/record/main.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import (
1616
"github.com/revolyssup/k8sdebug/pkg"
1717
appsv1 "k8s.io/api/apps/v1"
1818
v1 "k8s.io/api/core/v1"
19+
kerrors "k8s.io/apimachinery/pkg/api/errors"
1920
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2021
"k8s.io/apimachinery/pkg/watch"
2122
"k8s.io/client-go/kubernetes"
@@ -179,6 +180,49 @@ func main() {
179180
func processPod(ctx context.Context, cs *kubernetes.Clientset, pod *v1.Pod, namespace string) {
180181
creationTime := pod.CreationTimestamp.Time
181182
podName := pod.Name
183+
// Wait for pod to be ready or reach a terminal state
184+
waitCtx, cancel := context.WithTimeout(ctx, 5*time.Minute)
185+
defer cancel()
186+
podWaitLoop:
187+
for {
188+
select {
189+
case <-waitCtx.Done():
190+
fmt.Printf("Timeout waiting for pod %s to be ready\n", podName)
191+
break podWaitLoop
192+
default:
193+
currentPod, err := cs.CoreV1().Pods(namespace).Get(waitCtx, podName, metav1.GetOptions{})
194+
if err != nil {
195+
if kerrors.IsNotFound(err) {
196+
fmt.Printf("Pod %s no longer exists\n", podName)
197+
break podWaitLoop
198+
}
199+
fmt.Printf("Error fetching pod %s: %v\n", podName, err)
200+
time.Sleep(2 * time.Second)
201+
continue
202+
}
203+
204+
switch currentPod.Status.Phase {
205+
case v1.PodRunning:
206+
// Check container status
207+
for _, cs := range currentPod.Status.ContainerStatuses {
208+
if cs.State.Running != nil {
209+
fmt.Printf("Pod %s is ready\n", podName)
210+
break podWaitLoop
211+
}
212+
}
213+
fmt.Printf("Pod %s is running but containers not ready\n", podName)
214+
time.Sleep(2 * time.Second)
215+
case v1.PodSucceeded, v1.PodFailed:
216+
fmt.Printf("Pod %s in terminal state: %s\n", podName, currentPod.Status.Phase)
217+
break podWaitLoop
218+
default:
219+
fmt.Printf("Pod %s in phase: %s\n", podName, currentPod.Status.Phase)
220+
time.Sleep(2 * time.Second)
221+
}
222+
}
223+
}
224+
225+
fmt.Println("New pod added:", pod.Name, "at", creationTime.Format("2006-01-02 15:04:05"))
182226
// podNs := pod.Namespace
183227
// TODO: Fix this 5 second wait
184228
time.Sleep(time.Second * 5) // Wait for the pod to be ready

0 commit comments

Comments
 (0)