forked from hyperledger/fabric
-
Notifications
You must be signed in to change notification settings - Fork 5
/
conn.go
342 lines (291 loc) · 8.9 KB
/
conn.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package comm
import (
"context"
"sync"
proto "github.com/hyperledger/fabric-protos-go/gossip"
"github.com/hyperledger/fabric/gossip/common"
"github.com/hyperledger/fabric/gossip/metrics"
"github.com/hyperledger/fabric/gossip/protoext"
"github.com/hyperledger/fabric/gossip/util"
"github.com/pkg/errors"
"google.golang.org/grpc"
)
type handler func(message *protoext.SignedGossipMessage)
type blockingBehavior bool
const (
blockingSend = blockingBehavior(true)
nonBlockingSend = blockingBehavior(false)
)
type connFactory interface {
createConnection(endpoint string, pkiID common.PKIidType) (*connection, error)
}
type connectionStore struct {
config ConnConfig
logger util.Logger // logger
isClosing bool // whether this connection store is shutting down
shutdownOnce sync.Once // ensure shutdown is only called once per connectionStore
connFactory connFactory // creates a connection to remote peer
sync.RWMutex // synchronize access to shared variables
pki2Conn map[string]*connection // mapping between pkiID to connections
destinationLocks map[string]*sync.Mutex //mapping between pkiIDs and locks,
// used to prevent concurrent connection establishment to the same remote endpoint
}
func newConnStore(connFactory connFactory, logger util.Logger, config ConnConfig) *connectionStore {
return &connectionStore{
connFactory: connFactory,
isClosing: false,
pki2Conn: make(map[string]*connection),
destinationLocks: make(map[string]*sync.Mutex),
logger: logger,
config: config,
}
}
func (cs *connectionStore) getConnection(peer *RemotePeer) (*connection, error) {
cs.RLock()
isClosing := cs.isClosing
cs.RUnlock()
if isClosing {
return nil, errors.Errorf("conn store is closing")
}
pkiID := peer.PKIID
endpoint := peer.Endpoint
cs.Lock()
destinationLock, hasConnected := cs.destinationLocks[string(pkiID)]
if !hasConnected {
destinationLock = &sync.Mutex{}
cs.destinationLocks[string(pkiID)] = destinationLock
}
cs.Unlock()
destinationLock.Lock()
cs.RLock()
conn, exists := cs.pki2Conn[string(pkiID)]
if exists {
cs.RUnlock()
destinationLock.Unlock()
return conn, nil
}
cs.RUnlock()
createdConnection, err := cs.connFactory.createConnection(endpoint, pkiID)
if err == nil {
cs.logger.Debugf("Created new connection to %s, %s", endpoint, pkiID)
}
destinationLock.Unlock()
cs.RLock()
isClosing = cs.isClosing
cs.RUnlock()
if isClosing {
return nil, errors.Errorf("conn store is closing")
}
cs.Lock()
delete(cs.destinationLocks, string(pkiID))
defer cs.Unlock()
// check again, maybe someone connected to us during the connection creation?
conn, exists = cs.pki2Conn[string(pkiID)]
if exists {
if createdConnection != nil {
createdConnection.close()
}
return conn, nil
}
// no one connected to us AND we failed connecting!
if err != nil {
return nil, err
}
// At this point we know the latest PKI-ID of the remote peer.
// Perhaps we are trying to connect to a peer that changed its PKI-ID.
// Ensure that we are not already connected to that PKI-ID,
// and if so - close the old connection in order to keep the latest one.
// We keep the latest one because the remote peer is going to close
// our old connection anyway once it sensed this connection handshake.
if conn, exists := cs.pki2Conn[string(createdConnection.pkiID)]; exists {
conn.close()
}
// at this point in the code, we created a connection to a remote peer
conn = createdConnection
cs.pki2Conn[string(createdConnection.pkiID)] = conn
go conn.serviceConnection()
return conn, nil
}
func (cs *connectionStore) connNum() int {
cs.RLock()
defer cs.RUnlock()
return len(cs.pki2Conn)
}
func (cs *connectionStore) shutdown() {
cs.shutdownOnce.Do(func() {
cs.Lock()
cs.isClosing = true
for _, conn := range cs.pki2Conn {
conn.close()
}
cs.pki2Conn = make(map[string]*connection)
cs.Unlock()
})
}
// onConnected closes any connection to the remote peer and creates a new connection object to it in order to have only
// one single bi-directional connection between a pair of peers
func (cs *connectionStore) onConnected(serverStream proto.Gossip_GossipStreamServer,
connInfo *protoext.ConnectionInfo, metrics *metrics.CommMetrics) *connection {
cs.Lock()
defer cs.Unlock()
if c, exists := cs.pki2Conn[string(connInfo.ID)]; exists {
c.close()
}
conn := newConnection(nil, nil, serverStream, metrics, cs.config)
conn.pkiID = connInfo.ID
conn.info = connInfo
conn.logger = cs.logger
cs.pki2Conn[string(connInfo.ID)] = conn
return conn
}
func (cs *connectionStore) closeConnByPKIid(pkiID common.PKIidType) {
cs.Lock()
defer cs.Unlock()
if conn, exists := cs.pki2Conn[string(pkiID)]; exists {
conn.close()
delete(cs.pki2Conn, string(pkiID))
}
}
func newConnection(cl proto.GossipClient, c *grpc.ClientConn, s stream, metrics *metrics.CommMetrics, config ConnConfig) *connection {
connection := &connection{
metrics: metrics,
outBuff: make(chan *msgSending, config.SendBuffSize),
cl: cl,
conn: c,
gossipStream: s,
stopChan: make(chan struct{}, 1),
recvBuffSize: config.RecvBuffSize,
}
return connection
}
// ConnConfig is the configuration required to initialize a new conn
type ConnConfig struct {
RecvBuffSize int
SendBuffSize int
}
type connection struct {
recvBuffSize int
metrics *metrics.CommMetrics
cancel context.CancelFunc
info *protoext.ConnectionInfo
outBuff chan *msgSending
logger util.Logger // logger
pkiID common.PKIidType // pkiID of the remote endpoint
handler handler // function to invoke upon a message reception
conn *grpc.ClientConn // gRPC connection to remote endpoint
cl proto.GossipClient // gRPC stub of remote endpoint
gossipStream stream // there can only be one
stopChan chan struct{} // a method to stop the server-side gRPC call from a different go-routine
stopOnce sync.Once // once to ensure close is called only once
}
func (conn *connection) close() {
conn.stopOnce.Do(func() {
close(conn.stopChan)
if conn.conn != nil {
conn.conn.Close()
}
if conn.cancel != nil {
conn.cancel()
}
})
}
func (conn *connection) send(msg *protoext.SignedGossipMessage, onErr func(error), shouldBlock blockingBehavior) {
m := &msgSending{
envelope: msg.Envelope,
onErr: onErr,
}
select {
case conn.outBuff <- m:
// room in channel, successfully sent message, nothing to do
case <-conn.stopChan:
conn.logger.Debugf("Aborting send() to %s because connection is closing", conn.info.Endpoint)
default: // did not send
if shouldBlock {
select {
case conn.outBuff <- m: // try again, and wait to send
case <-conn.stopChan: //stop blocking if the connection is closing
}
} else {
conn.metrics.BufferOverflow.Add(1)
conn.logger.Debugf("Buffer to %s overflowed, dropping message %s", conn.info.Endpoint, msg)
}
}
}
func (conn *connection) serviceConnection() error {
errChan := make(chan error, 1)
msgChan := make(chan *protoext.SignedGossipMessage, conn.recvBuffSize)
// Call stream.Recv() asynchronously in readFromStream(),
// and wait for either the Recv() call to end,
// or a signal to close the connection, which exits
// the method and makes the Recv() call to fail in the
// readFromStream() method
go conn.readFromStream(errChan, msgChan)
go conn.writeToStream()
for {
select {
case <-conn.stopChan:
conn.logger.Debug("Closing reading from stream")
return nil
case err := <-errChan:
return err
case msg := <-msgChan:
conn.handler(msg)
}
}
}
func (conn *connection) writeToStream() {
stream := conn.gossipStream
for {
select {
case m := <-conn.outBuff:
err := stream.Send(m.envelope)
if err != nil {
go m.onErr(err)
return
}
conn.metrics.SentMessages.Add(1)
case <-conn.stopChan:
conn.logger.Debug("Closing writing to stream")
return
}
}
}
func (conn *connection) readFromStream(errChan chan error, msgChan chan *protoext.SignedGossipMessage) {
stream := conn.gossipStream
for {
select {
case <-conn.stopChan:
return
default:
envelope, err := stream.Recv()
if err != nil {
errChan <- err
conn.logger.Debugf("Got error, aborting: %v", err)
return
}
conn.metrics.ReceivedMessages.Add(1)
msg, err := protoext.EnvelopeToGossipMessage(envelope)
if err != nil {
errChan <- err
conn.logger.Warningf("Got error, aborting: %v", err)
return
}
select {
case <-conn.stopChan:
case msgChan <- msg:
}
}
}
}
type msgSending struct {
envelope *proto.Envelope
onErr func(error)
}
//go:generate mockery -dir . -name MockStream -case underscore -output mocks/
type MockStream interface {
proto.Gossip_GossipStreamClient
}