-
Notifications
You must be signed in to change notification settings - Fork 0
/
dial.go
109 lines (94 loc) · 2.46 KB
/
dial.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package service
import (
"fmt"
"github.com/omecodes/common/errors"
"github.com/omecodes/libome"
"github.com/omecodes/libome/logs"
"google.golang.org/grpc"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials"
)
func (box *Box) dialToService(serviceType uint32) (*grpc.ClientConn, error) {
reg, err := box.Registry()
if err != nil {
return nil, err
}
infoList, err := reg.GetOfType(serviceType)
if err != nil {
return nil, err
}
var selection = infoList
var dialer Dialer
for _, info := range selection {
// Search for cached connection dialer
for _, node := range info.Nodes {
if node.Protocol == ome.Protocol_Grpc {
conn := box.dialFromCache(node.Address)
if conn != nil {
return conn, nil
}
}
}
// if no existing connection dialer found, dial new one
for _, node := range info.Nodes {
if node.Protocol == ome.Protocol_Grpc {
tlsConf, err := box.ClientMutualTLS()
if err != nil {
return nil, err
}
dialer = NewDialer(node.Address, grpc.WithTransportCredentials(credentials.NewTLS(tlsConf)))
conn, err := dialer.Dial()
if err != nil {
logs.Error("could not connect to gRPC server", logs.Err(err), logs.Details("at", fmt.Sprintf("grpc://%s@%s", node.Id, node.Address)))
} else {
logs.Info("connected to gRPC server", logs.Details("at", fmt.Sprintf("grpc://%s@%s", node.Id, node.Address)))
box.addDialerToCache(node.Address, dialer)
return conn, err
}
}
}
}
return nil, errors.ServiceNotAvailable
}
func (box *Box) dialFromCache(addr string) *grpc.ClientConn {
box.dialerMutex.Lock()
defer box.dialerMutex.Unlock()
dialer := box.dialerCache[addr]
if dialer != nil {
conn, _ := dialer.Dial()
return conn
}
return nil
}
func (box *Box) addDialerToCache(addr string, dialer Dialer) {
box.dialerMutex.Lock()
defer box.dialerMutex.Unlock()
box.dialerCache[addr] = dialer
}
type Dialer interface {
Dial() (*grpc.ClientConn, error)
}
type dialer struct {
address string
wrapped *grpc.ClientConn
options []grpc.DialOption
}
func (g *dialer) Dial() (*grpc.ClientConn, error) {
if g.wrapped == nil || g.wrapped.GetState() != connectivity.Ready {
if g.wrapped != nil {
_ = g.wrapped.Close()
}
var err error
g.wrapped, err = grpc.Dial(g.address, g.options...)
if err != nil {
return nil, err
}
}
return g.wrapped, nil
}
func NewDialer(addr string, opts ...grpc.DialOption) *dialer {
return &dialer{
address: addr,
options: opts,
}
}