forked from argoproj/argo-workflows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wait.go
58 lines (52 loc) · 1.79 KB
/
wait.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package wait
import (
"context"
"fmt"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
v1 "k8s.io/client-go/kubernetes/typed/core/v1"
"github.com/simster7/argo/v2/workflow/executor/common"
)
func UntilTerminated(ctx context.Context, kubernetesInterface kubernetes.Interface, namespace, podName, containerID string) error {
log.Infof("Waiting for container %s to be terminated", containerID)
podInterface := kubernetesInterface.CoreV1().Pods(namespace)
listOptions := metav1.ListOptions{FieldSelector: "metadata.name=" + podName}
for {
done, err := untilTerminatedAux(ctx, podInterface, containerID, listOptions)
if done {
return err
}
}
}
func untilTerminatedAux(ctx context.Context, podInterface v1.PodInterface, containerID string, listOptions metav1.ListOptions) (bool, error) {
for {
timedOut, done, err := doWatch(ctx, podInterface, containerID, listOptions)
if !timedOut {
return done, err
}
log.Infof("Pod watch timed out, restarting watch on %s", containerID)
}
}
func doWatch(ctx context.Context, podInterface v1.PodInterface, containerID string, listOptions metav1.ListOptions) (bool, bool, error) {
w, err := podInterface.Watch(ctx, listOptions)
if err != nil {
return false, true, fmt.Errorf("could not watch pod: %w", err)
}
defer w.Stop()
for event := range w.ResultChan() {
pod, ok := event.Object.(*corev1.Pod)
if !ok {
return false, false, apierrors.FromObject(event.Object)
}
for _, s := range pod.Status.ContainerStatuses {
if common.GetContainerID(&s) == containerID && s.State.Terminated != nil {
return false, true, nil
}
}
listOptions.ResourceVersion = pod.ResourceVersion
}
return true, false, nil
}