-
Notifications
You must be signed in to change notification settings - Fork 2
/
redial.go
68 lines (63 loc) · 1.95 KB
/
redial.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package sshtunnel
import (
"context"
"net"
"github.com/sgreben/sshtunnel/backoff"
)
// ReDial opens a tunnelled connection to the address on the named network.
//
// Failed connections are re-dialled following the given back-off configuration.
// Dropped connections are immediately re-dialed.
//
// Supported networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only),
// "unix", "unixgram" and "unixpacket".
func ReDial(network, addr string, config *Config, backoffConfig backoff.Config) (<-chan net.Conn, <-chan error) {
return ReDialContext(context.Background(), network, addr, config, backoffConfig)
}
// ReDialContext opens a tunnelled connection to the address on the named network using
// the provided context.
//
// Failed connections are re-dialled following the given back-off configuration.
// Dropped connections are immediately re-dialed.
//
// See func ReDial for a description of the network and address
// parameters.
func ReDialContext(ctx context.Context, network, addr string, config *Config, backoffConfig backoff.Config) (<-chan net.Conn, <-chan error) {
dial := func() (net.Conn, <-chan error, error) {
return DialContext(ctx, network, addr, config)
}
dialBackOff := func() (net.Conn, <-chan error, error) {
return dialBackOff(ctx, dial, backoffConfig)
}
connCh := make(chan net.Conn)
errCh := make(chan error)
go func() {
defer close(connCh)
defer close(errCh)
for {
conn, closedCh, err := dialBackOff()
if err != nil {
errCh <- err
return
}
select {
case connCh <- conn:
case <-closedCh:
case <-ctx.Done():
errCh <- ctx.Err()
return
}
}
}()
return connCh, errCh
}
func dialBackOff(ctx context.Context, dial func() (net.Conn, <-chan error, error), config backoff.Config) (net.Conn, <-chan error, error) {
var conn net.Conn
var connClosedCh <-chan error
errOut := config.Run(ctx, func() error {
var err error
conn, connClosedCh, err = dial()
return err
})
return conn, connClosedCh, errOut
}