Skip to content

Commit

Permalink
ssh: Introduce 'retry' helper
Browse files Browse the repository at this point in the history
initialConnection retries multiple times to establish the TCP connection
which will be used for ssh communication.
This commit adds a generic helper to handle the retry which will be
useful in the next commits.

Signed-off-by: Christophe Fergeau <[email protected]>
  • Loading branch information
cfergeau committed Jan 11, 2024
1 parent f01fd1c commit aa3fa9a
Showing 1 changed file with 20 additions and 9 deletions.
29 changes: 20 additions & 9 deletions pkg/sshclient/ssh_forwarder.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package sshclient

import (
"context"
"fmt"
"io"
"net"
"net/url"
Expand Down Expand Up @@ -180,32 +181,42 @@ func setupProxy(ctx context.Context, socketURI *url.URL, dest *url.URL, identity
return &SSHForward{listener, &bastion, socketURI}, nil
}

func initialConnection(ctx context.Context, connectFunc ConnectCallback) (net.Conn, error) {
const maxRetries = 60
const initialBackoff = 100 * time.Millisecond

func retry[T comparable](ctx context.Context, retryFunc func() (T, error), retryMsg string) (T, error) {
var (
conn net.Conn
err error
returnVal T
err error
)

backoff := 100 * time.Millisecond
backoff := initialBackoff

loop:
for i := 0; i < 60; i++ {
for i := 0; i < maxRetries; i++ {
select {
case <-ctx.Done():
break loop
default:
// proceed
}

conn, err = connectFunc(ctx, nil)
returnVal, err = retryFunc()
if err == nil {
break
return returnVal, nil
}
logrus.Debugf("Waiting for sshd: %s", backoff)
logrus.Debugf("%s (%s)", retryMsg, backoff)
sleep(ctx, backoff)
backoff = backOff(backoff)
}
return conn, err
return returnVal, fmt.Errorf("timeout: %w", err)
}

func initialConnection(ctx context.Context, connectFunc ConnectCallback) (net.Conn, error) {
retryFunc := func() (net.Conn, error) {
return connectFunc(ctx, nil)
}
return retry(ctx, retryFunc, "Waiting for sshd socket")
}

func acceptConnection(ctx context.Context, listener net.Listener, bastion *Bastion, socketURI *url.URL) error {
Expand Down

0 comments on commit aa3fa9a

Please sign in to comment.