Skip to content

Commit 64157a5

Browse files
Handle error properly during port forwarding initialization.
1 parent 88af617 commit 64157a5

File tree

1 file changed

+14
-7
lines changed

1 file changed

+14
-7
lines changed

port_forwarding.go

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package testcontainers
22

33
import (
44
"context"
5+
"errors"
56
"fmt"
67
"io"
78
"net"
@@ -231,20 +232,22 @@ func (sshdC *sshdContainer) exposeHostPort(ctx context.Context, ports ...int) er
231232
go pw.Forward(ctx)
232233
}
233234

235+
var err error
236+
234237
// continue when all port forwarders have created the connection
235238
for _, pfw := range sshdC.portForwarders {
236-
<-pfw.connectionCreated
239+
err = errors.Join(err, <-pfw.connectionCreated)
237240
}
238241

239-
return nil
242+
return err
240243
}
241244

242245
type PortForwarder struct {
243246
sshDAddr string
244247
sshConfig *ssh.ClientConfig
245248
remotePort int
246249
localPort int
247-
connectionCreated chan struct{} // used to signal that the connection has been created, so the caller can proceed
250+
connectionCreated chan error // used to signal that the connection has been created, so the caller can proceed
248251
terminateChan chan struct{} // used to signal that the connection has been terminated
249252
}
250253

@@ -254,7 +257,7 @@ func NewPortForwarder(sshDAddr string, sshConfig *ssh.ClientConfig, remotePort,
254257
sshConfig: sshConfig,
255258
remotePort: remotePort,
256259
localPort: localPort,
257-
connectionCreated: make(chan struct{}),
260+
connectionCreated: make(chan error),
258261
terminateChan: make(chan struct{}),
259262
}
260263
}
@@ -267,18 +270,22 @@ func (pf *PortForwarder) Close(ctx context.Context) {
267270
func (pf *PortForwarder) Forward(ctx context.Context) error {
268271
client, err := ssh.Dial("tcp", pf.sshDAddr, pf.sshConfig)
269272
if err != nil {
270-
return fmt.Errorf("error dialing ssh server: %w", err)
273+
err = fmt.Errorf("error dialing ssh server: %w", err)
274+
pf.connectionCreated <- err
275+
return err
271276
}
272277
defer client.Close()
273278

274279
listener, err := client.Listen("tcp", fmt.Sprintf("localhost:%d", pf.remotePort))
275280
if err != nil {
276-
return fmt.Errorf("error listening on remote port: %w", err)
281+
err = fmt.Errorf("error listening on remote port: %w", err)
282+
pf.connectionCreated <- err
283+
return err
277284
}
278285
defer listener.Close()
279286

280287
// signal that the connection has been created
281-
pf.connectionCreated <- struct{}{}
288+
pf.connectionCreated <- nil
282289

283290
// check if the context or the terminateChan has been closed
284291
select {

0 commit comments

Comments
 (0)