/
net_connect.go
68 lines (55 loc) · 1.56 KB
/
net_connect.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 sshclient
import (
"context"
"github.com/sethvargo/go-retry"
"net"
)
type NetConnectFunc func(context.Context) (net.Conn, error)
type NetConnectMiddleware func(NetConnectFunc) NetConnectFunc
// NetCircuitBreaker wraps a NetConnectFunc and ensures that the NetConnectFunc will not be called again when a previous
// call returned an error. If the NetConnectFunc has returned an error previously, NetCircuitBreaker will not call it
// again and return the same error.
func NetCircuitBreaker() NetConnectMiddleware {
return func(next NetConnectFunc) NetConnectFunc {
var connectErr error
return func(ctx context.Context) (net.Conn, error) {
if connectErr != nil {
return nil, connectErr
}
conn, err := next(ctx)
if err != nil {
connectErr = err
return nil, err
}
return conn, nil
}
}
}
// NetRetry wraps a NetConnectFunc and attempts retries according to the provided retry.Backoff
func NetRetry(backoff retry.Backoff) NetConnectMiddleware {
return func(next NetConnectFunc) NetConnectFunc {
return func(ctx context.Context) (net.Conn, error) {
var conn net.Conn
retryErr := retry.Do(ctx, backoff, func(ctx context.Context) error {
var err error
conn, err = next(ctx)
if err != nil {
switch err.(type) {
case *net.OpError:
return retry.RetryableError(err)
}
switch err.Error() {
case "ssh: handshake failed: EOF":
return retry.RetryableError(err)
}
return err
}
return nil
})
if retryErr != nil {
return nil, retryErr
}
return conn, nil
}
}
}