forked from spiffe/spire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dialer.go
78 lines (64 loc) · 1.74 KB
/
dialer.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
69
70
71
72
73
74
75
76
77
78
package grpcutil
import (
"context"
"errors"
"fmt"
"net"
"time"
"github.com/sirupsen/logrus"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
type GRPCDialerConfig struct {
Log logrus.StdLogger
CredFunc func() (credentials.TransportCredentials, error)
Opts []grpc.DialOption
}
type Dialer interface {
Dial(ctx context.Context, addr string) (*grpc.ClientConn, error)
}
type grpcDialer struct {
log logrus.StdLogger
credFunc func() (credentials.TransportCredentials, error)
opts []grpc.DialOption
}
func NewGRPCDialer(c GRPCDialerConfig) Dialer {
return &grpcDialer{
log: c.Log,
credFunc: c.CredFunc,
opts: append([]grpc.DialOption{}, c.Opts...),
}
}
// Dial dials the given address, using TLS credentials, and logs information about connection
// errors.
func (d *grpcDialer) Dial(ctx context.Context, addr string) (*grpc.ClientConn, error) {
if d.credFunc == nil {
return nil, errors.New("credentials are required")
}
dialer := func(_ string, timeout time.Duration) (net.Conn, error) {
creds, err := d.credFunc()
if err != nil {
d.log.Printf("Could not fetch transport credentials: %v", err)
return nil, fmt.Errorf("fetch transport credentials: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
conn, err := proxyDial(ctx, d.log, addr)
if err != nil {
d.log.Print(err)
return nil, err
}
conn, _, err = creds.ClientHandshake(ctx, addr, conn)
if err != nil {
d.log.Print(err)
return nil, err
}
return conn, nil
}
opts := append(d.opts,
grpc.FailOnNonTempDialError(true),
grpc.WithDialer(dialer),
grpc.WithInsecure(), // we want to handle TLS by ourselves
)
return grpc.DialContext(ctx, addr, opts...)
}