Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix long running k8s job timeouts #10

Merged
merged 1 commit into from
Sep 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 18 additions & 17 deletions worker/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ import (
"fmt"
"io"
"text/template"
"time"

"github.com/ohsu-comp-bio/funnel/tes"
v1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/watch"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
batchv1 "k8s.io/client-go/kubernetes/typed/batch/v1"
"k8s.io/client-go/rest"
)

Expand Down Expand Up @@ -84,14 +85,7 @@ func (kcmd KubernetesCommand) Run(ctx context.Context) error {
return fmt.Errorf("creating job: %v", err)
}

// Wait until the job finishes
watcher, err := client.Watch(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("job-name=%s-%d", taskId, kcmd.JobId)})
if err != nil {
return err
}

defer watcher.Stop()
waitForJobFinish(ctx, watcher)
waitForJobFinish(ctx, client, metav1.ListOptions{LabelSelector: fmt.Sprintf("job-name=%s-%d", taskId, kcmd.JobId)})

pods, err := clientset.CoreV1().Pods(kcmd.Namespace).List(ctx, metav1.ListOptions{LabelSelector: fmt.Sprintf("job-name=%s-%d", taskId, kcmd.JobId)})
if err != nil {
Expand Down Expand Up @@ -145,23 +139,30 @@ func (kcmd KubernetesCommand) Stop() error {
}

// Waits until the job finishes
func waitForJobFinish(ctx context.Context, watcher watch.Interface) {
func waitForJobFinish(ctx context.Context, client batchv1.JobInterface, listOptions metav1.ListOptions) {
ticker := time.NewTicker(10 * time.Second)

for {
select {
case event := <-watcher.ResultChan():
if event.Type == watch.Error || event.Type == watch.Deleted {
case <-ctx.Done():
return
case <-ticker.C:
jobs, err := client.List(ctx, listOptions)

if err != nil {
return
} else if event.Type == watch.Bookmark {
continue
}

job := event.Object.(*v1.Job)
if len(jobs.Items) == 0 {
// Should not happen
return
}

// There should be always only one job
job := jobs.Items[0]
if job.Status.Succeeded > 0 || job.Status.Failed > 0 {
return
}
case <-ctx.Done():
return
}
}
}
Expand Down