portforward: return error on lost connection to pod

Currently, when the remote connection is unexpected closed, forward() prints an error message saying "lost connection to pod" via runtime.HandleError, but then it returns nil for the error.

This prevents the caller from being able to handle this error differently.

This commit changes forward() to return the "lost connection to pod" error so that it can be handled by the caller.

Making this change enables kubectl port-forward to exit with code 1, instead of 0, which is the expected behavior for a command that has failed.

Kubernetes-commit: a9f04103854893056237a09250ad3335867b0391
This commit is contained in:
Brian Pursley
2022-12-13 13:32:42 -05:00
committed by Kubernetes Publisher
parent 5ea7f43b5d
commit d0842249d3
2 changed files with 33 additions and 1 deletions

View File

@@ -567,3 +567,33 @@ func TestWaitForConnectionExitsOnStreamConnClosed(t *testing.T) {
port := ForwardedPort{}
pf.waitForConnection(&listener, port)
}
func TestForwardPortsReturnsErrorWhenConnectionIsLost(t *testing.T) {
dialer := &fakeDialer{
conn: newFakeConnection(),
}
stopChan := make(chan struct{})
readyChan := make(chan struct{})
errChan := make(chan error)
pf, err := New(dialer, []string{":5000"}, stopChan, readyChan, os.Stdout, os.Stderr)
if err != nil {
t.Fatalf("faile to create new PortForwarder: %s", err)
}
go func() {
errChan <- pf.ForwardPorts()
}()
<-pf.Ready
pf.streamConn.Close()
err = <-errChan
if err == nil {
t.Fatalf("unexpected non-error from pf.ForwardPorts()")
} else if err != ErrLostConnectionToPod {
t.Fatalf("unexpected error from pf.ForwardPorts(): %s", err)
}
}