Skip to content

Commit

Permalink
fix: kubectl port fwd should return on canceled context (#6700)
Browse files Browse the repository at this point in the history
Debugging the flaky `TestDevGracefulCancel/multi-config-microservices`
integration test showed that the kubectl port forwarder was stuck with
goroutines waiting on a channels(one per resource).

Search for `goroutine 235` and `goroutine 234` in this Kokoro log:
https://source.cloud.google.com/results/invocations/a9749ab5-8762-4319-a2be-f67c7440f7a2/targets/skaffold%2Fpresubmit/log

This change means that the forwarder also listens for context canceled.

**Related**: #6424, #6643, #6662, #6685
  • Loading branch information
halvards authored Oct 7, 2021
1 parent 14314b4 commit 719a890
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
15 changes: 14 additions & 1 deletion pkg/skaffold/kubernetes/portforward/kubectl_forwarder.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,20 @@ func (k *KubectlForwarder) Start(out io.Writer) {
func (k *KubectlForwarder) Forward(parentCtx context.Context, pfe *portForwardEntry) error {
errChan := make(chan error, 1)
go k.forward(parentCtx, pfe, errChan)
return <-errChan
l := log.Entry(parentCtx)
resourceName := ""
if pfe != nil {
resourceName = pfe.resource.Name
}
l.Tracef("KubectlForwarder.Forward(%s): waiting on errChan", resourceName)
select {
case <-parentCtx.Done():
l.Tracef("KubectlForwarder.Forward(%s): parentCtx canceled, returning nil error", resourceName)
return nil
case err := <-errChan:
l.Tracef("KubectlForwarder.Forward(%s): got error on errChan, returning: %+v", resourceName, err)
return err
}
}

func (k *KubectlForwarder) forward(ctx context.Context, pfe *portForwardEntry, errChan chan error) {
Expand Down
22 changes: 22 additions & 0 deletions pkg/skaffold/kubernetes/portforward/kubectl_forwarder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -481,3 +481,25 @@ func TestStartAndForward(t *testing.T) {
})
}
}

func TestForwardReturnsNilOnContextCancelled(t *testing.T) {
k := NewKubectlForwarder(&kubectl.CLI{})
k.Start(ioutil.Discard)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{}, 1)
go func() {
pfe := newPortForwardEntry(0, latestV1.PortForwardResource{}, "", "", "", "", 8080, false)
err := k.Forward(ctx, pfe)
if err != nil {
t.Errorf("expected nil error, got %+v", err)
}
close(done)
}()
cancel()
select {
case <-done:
// expected
case <-time.After(3 * time.Second):
t.Fatalf("forwarder did not return on context cancel")
}
}

0 comments on commit 719a890

Please sign in to comment.