Skip to content

Commit

Permalink
Stop watching SIGTERM before starting process
Browse files Browse the repository at this point in the history
  • Loading branch information
n1koo committed Oct 26, 2020
1 parent 3e82f4e commit b29740b
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions cmd/kubexit/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,9 +171,9 @@ func main() {

func waitForBirthDeps(birthDeps []string, namespace, podName string, timeout time.Duration) error {
// Cancel context on SIGTERM to trigger graceful exit
ctx := withCancelOnSignal(context.Background(), syscall.SIGTERM)
ctxParent, parentCancel := withCancelOnSignal(context.Background(), syscall.SIGTERM)

ctx, stopPodWatcher := context.WithTimeout(ctx, timeout)
ctx, stopPodWatcher := context.WithTimeout(ctxParent, timeout)
// Stop pod watcher on exit, if not sooner
defer stopPodWatcher()

Expand All @@ -187,6 +187,7 @@ func waitForBirthDeps(birthDeps []string, namespace, podName string, timeout tim

// Block until all birth deps are ready
<-ctx.Done()
parentCancel()
err = ctx.Err()
if err == context.DeadlineExceeded {
return fmt.Errorf("timed out waiting for birth deps to be ready: %s", timeout)
Expand All @@ -200,7 +201,7 @@ func waitForBirthDeps(birthDeps []string, namespace, podName string, timeout tim
}

// withCancelOnSignal calls cancel when one of the specified signals is recieved.
func withCancelOnSignal(ctx context.Context, signals ...os.Signal) context.Context {
func withCancelOnSignal(ctx context.Context, signals ...os.Signal) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithCancel(ctx)

sigCh := make(chan os.Signal, 1)
Expand All @@ -214,16 +215,16 @@ func withCancelOnSignal(ctx context.Context, signals ...os.Signal) context.Conte
if !ok {
return
}
log.Printf("Received shutdown signal: %v", s)
cancel()
log.Printf("Received shutdown signal: %v, exiting", s)
os.Exit(0)
case <-ctx.Done():
signal.Reset()
close(sigCh)
}
}
}()

return ctx
return ctx, cancel
}

// wait for the child to exit and return the exit code
Expand Down

0 comments on commit b29740b

Please sign in to comment.