forked from hyperledger/fabric
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
54 lines (47 loc) · 1.46 KB
/
connection.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
package comm
import (
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
"github.com/op/go-logging"
"github.com/spf13/viper"
)
const defaultTimeout = time.Second * 3
var commLogger = logging.MustGetLogger("comm")
// NewClientConnectionWithAddress Returns a new grpc.ClientConn to the given address.
func NewClientConnectionWithAddress(peerAddress string, block bool, tslEnabled bool, creds credentials.TransportCredentials) (*grpc.ClientConn, error) {
var opts []grpc.DialOption
if tslEnabled {
opts = append(opts, grpc.WithTransportCredentials(creds))
} else {
opts = append(opts, grpc.WithInsecure())
}
opts = append(opts, grpc.WithTimeout(defaultTimeout))
if block {
opts = append(opts, grpc.WithBlock())
}
conn, err := grpc.Dial(peerAddress, opts...)
if err != nil {
return nil, err
}
return conn, err
}
// InitTLSForPeer returns TLS credentials for peer
func InitTLSForPeer() credentials.TransportCredentials {
var sn string
if viper.GetString("peer.tls.serverhostoverride") != "" {
sn = viper.GetString("peer.tls.serverhostoverride")
}
var creds credentials.TransportCredentials
if viper.GetString("peer.tls.cert.file") != "" {
var err error
creds, err = credentials.NewClientTLSFromFile(viper.GetString("peer.tls.cert.file"), sn)
if err != nil {
grpclog.Fatalf("Failed to create TLS credentials %v", err)
}
} else {
creds = credentials.NewClientTLSFromCert(nil, sn)
}
return creds
}