-
Notifications
You must be signed in to change notification settings - Fork 199
/
Copy pathconnection.go
176 lines (157 loc) · 4.66 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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
/*
Copyright 2019 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package connection manages cached client connections to gRPC servers.
package connection
import (
"context"
"errors"
"fmt"
"sync"
log "github.com/golang/glog"
"google.golang.org/grpc"
)
// DEFAULT is the name of the dialer that is used if not explicitly specified in
// Connection.
const DEFAULT = ""
type connection struct {
id string
ref int
c *grpc.ClientConn // Set during dial attempt, before signaling ready.
err error // Set during dial attempt, before signaling ready.
ready chan struct{}
}
// Manager provides functionality for creating cached client gRPC connections.
type Manager struct {
opts []grpc.DialOption
d map[string]Dial
mu sync.Mutex
conns map[string]*connection
}
// NewManager creates a new Manager. The opts arguments are used
// to dial new gRPC targets, with the same semantics as grpc.DialContext.
func NewManager(opts ...grpc.DialOption) (*Manager, error) {
return NewManagerCustom(map[string]Dial{DEFAULT: grpc.DialContext}, opts...)
}
// Dial defines a function to dial the gRPC connection.
type Dial func(ctx context.Context, target string, opts ...grpc.DialOption) (conn *grpc.ClientConn, err error)
// NewManagerCustom creates a new Manager. The opts arguments are used
// to dial new gRPC targets, using the provided Dial function.
func NewManagerCustom(d map[string]Dial, opts ...grpc.DialOption) (*Manager, error) {
if len(d) == 0 {
return nil, errors.New("no Dial provided")
}
for name, dialer := range d {
if dialer == nil {
return nil, fmt.Errorf("dialer %q is nil", name)
}
}
m := &Manager{}
m.conns = map[string]*connection{}
m.opts = opts
m.d = d
return m, nil
}
// remove should be called while locking m.
func (m *Manager) remove(addr string) {
c, ok := m.conns[addr]
if !ok {
log.Errorf("Connection %q missing or already removed", addr)
}
delete(m.conns, addr)
if c.c != nil {
if err := c.c.Close(); err != nil {
log.Errorf("Error cleaning up connection %q: %v", addr, err)
}
}
}
func (m *Manager) dial(ctx context.Context, addr, dialer string, c *connection) {
defer close(c.ready)
d, ok := m.d[dialer]
var err error
if !ok {
err = fmt.Errorf("no such dialer: %v", dialer)
}
var cc *grpc.ClientConn
if err == nil {
cc, err = d(ctx, addr, m.opts...)
}
if err != nil {
log.Infof("Error creating gRPC connection to %q: %v", addr, err)
m.mu.Lock()
m.remove(addr)
c.err = err
m.mu.Unlock()
return
}
log.Infof("Created gRPC connection to %q", addr)
c.c = cc
}
func (c *connection) done(m *Manager) func() {
var once sync.Once
fn := func() {
if c == nil {
log.Error("Attempted to call done on nil connection")
return
}
m.mu.Lock()
defer m.mu.Unlock()
c.ref--
if c.ref <= 0 {
m.remove(c.id)
}
}
return func() {
once.Do(fn)
}
}
func newConnection(addr string) *connection {
return &connection{
id: addr,
ready: make(chan struct{}),
}
}
// Connection creates a new grpc.ClientConn to the destination address or
// returns the existing connection, along with a done function.
//
// Usage is registered when a connection is retrieved using Connection. Clients
// should call the returned done function when the returned connection handle is
// unused. Subsequent calls to the same done function have no effect. If an
// error is returned, done has no effect. Connections with no usages will be
// immediately closed and removed from Manager.
//
// If there is already a pending connection attempt for the same addr,
// Connection blocks until that attempt finishes and returns a shared result.
// Note that canceling the context of a pending attempt early would propagate
// an error to blocked callers.
func (m *Manager) Connection(ctx context.Context, addr, dialer string) (conn *grpc.ClientConn, done func(), err error) {
select {
case <-ctx.Done():
return nil, func() {}, ctx.Err()
default:
m.mu.Lock()
c, ok := m.conns[addr]
if !ok {
c = newConnection(addr)
m.conns[addr] = c
go m.dial(ctx, addr, dialer, c)
}
c.ref++
m.mu.Unlock()
<-c.ready
if c.err != nil {
return nil, func() {}, c.err
}
log.V(2).Infof("Reusing connection %q", addr)
return c.c, c.done(m), nil
}
}