/
raft_transport.go
567 lines (505 loc) · 13.7 KB
/
raft_transport.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// Copyright 2017-2021 The NATS Authors
// 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.
// RAFT Transport implementation using NATS
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"sync"
"time"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/raft"
"github.com/nats-io/nats.go"
)
const (
natsConnectInbox = "raft.%s.accept"
natsRequestInbox = "raft.%s.request.%s"
timeoutForDialAndFlush = 2 * time.Second
natsLogAppName = "raft-nats"
)
type natsRaftConnCreator func(name string) (*nats.Conn, error)
// natsAddr implements the net.Addr interface. An address for the NATS
// transport is simply a node id, which is then used to construct an inbox.
type natsAddr string
func (n natsAddr) Network() string {
return "nats"
}
func (n natsAddr) String() string {
return string(n)
}
type connectRequestProto struct {
ID string `json:"id"`
Inbox string `json:"inbox"`
}
type connectResponseProto struct {
Inbox string `json:"inbox"`
}
// natsConn implements the net.Conn interface by simulating a stream-oriented
// connection between two peers. It does this by establishing a unique inbox at
// each endpoint which the peers use to stream data to each other.
type natsConn struct {
mu sync.RWMutex
conn *nats.Conn
streamConn bool
localAddr natsAddr
remoteAddr natsAddr
sub *nats.Subscription
subTimeout time.Duration
pendingH *pendingBuf // head of pending buffers list
pendingT *pendingBuf // tail of pending buffers list
ch chan struct{} // to send notification that a buffer is available
outbox string
closed bool
parent *natsStreamLayer
}
type pendingBuf struct {
buf []byte
next *pendingBuf
}
var pendingBufPool = &sync.Pool{
New: func() interface{} {
return &pendingBuf{}
},
}
func (n *natsConn) onMsg(msg *nats.Msg) {
pb := pendingBufPool.Get().(*pendingBuf)
n.mu.Lock()
if n.closed {
n.mu.Unlock()
return
}
pb.buf = msg.Data
var notify bool
if n.pendingT != nil {
n.pendingT.next = pb
} else {
n.pendingH = pb
notify = true
}
n.pendingT = pb
n.mu.Unlock()
if notify {
select {
case n.ch <- struct{}{}:
default:
}
}
}
func (n *natsConn) Read(b []byte) (int, error) {
var subTimeout time.Duration
n.mu.RLock()
if n.closed {
n.mu.RUnlock()
return 0, io.EOF
}
// Reference, but do not remove the pending buffer in case we
// cannot copy the whole buffer, we will update the buffer slice.
pb := n.pendingH
// We will wait only if there is no pending buffer.
if pb == nil {
subTimeout = n.subTimeout
if subTimeout == 0 {
subTimeout = time.Duration(0x7FFFFFFFFFFFFFFF)
}
}
n.mu.RUnlock()
// There was no buffer, so we need to wait.
if pb == nil {
WAIT_FOR_BUFFER:
select {
case <-time.After(subTimeout):
return 0, nats.ErrTimeout
case _, ok := <-n.ch:
if !ok {
return 0, io.EOF
}
}
n.mu.RLock()
// We notify when adding the first pending buffer, but if Read() is called
// after, we will detect that there is a pending and skip the whole select.
// So after consuming the pending, the next Read() would get the past
// notification. If that is the case, go back to the select.
if n.pendingH == nil {
n.mu.RUnlock()
goto WAIT_FOR_BUFFER
}
// We have been notified, so get the reference to the head of the list.
pb = n.pendingH
n.mu.RUnlock()
}
buf := pb.buf
bufSize := len(buf)
// A buf of size 0 means that the remote closed
if bufSize == 0 {
n.close(false)
return 0, io.EOF
}
limit := bufSize
if limit > len(b) {
limit = len(b)
}
nb := copy(b, buf[:limit])
// If we did not copy everything, reduce size by what we copied.
if nb != bufSize {
buf = buf[nb:]
} else {
buf = nil
}
var release bool
n.mu.Lock()
if buf != nil {
pb.buf = buf
} else {
// We are done with this pending buffer, remove from the pending list.
n.pendingH = n.pendingH.next
if n.pendingH == nil {
n.pendingT = nil
}
release = true
}
n.mu.Unlock()
if release {
pb.buf, pb.next = nil, nil
pendingBufPool.Put(pb)
}
return nb, nil
}
func (n *natsConn) Write(b []byte) (int, error) {
n.mu.RLock()
closed := n.closed
n.mu.RUnlock()
if closed {
return 0, io.EOF
}
if len(b) == 0 {
return 0, nil
}
// Send data in chunks to avoid hitting max payload.
for i := 0; i < len(b); {
chunkSize := min(int64(len(b[i:])), n.conn.MaxPayload())
if err := n.conn.Publish(n.outbox, b[i:int64(i)+chunkSize]); err != nil {
return i, err
}
i += int(chunkSize)
}
return len(b), nil
}
func (n *natsConn) Close() error {
return n.close(true)
}
func (n *natsConn) close(signalRemote bool) error {
n.mu.Lock()
if n.closed {
n.mu.Unlock()
return nil
}
if signalRemote {
// Send empty message to signal EOF for a graceful disconnect. Not
// concerned with errors here as this is best effort.
n.conn.Publish(n.outbox, nil)
// Best effort, don't block for too long and don't check returned error.
n.conn.FlushTimeout(500 * time.Millisecond)
}
// If connection is owned by stream, simply unsubscribe. Note that we
// check for sub != nil because this can be called during setup where
// sub has not been attached.
var err error
if n.streamConn {
if n.sub != nil {
err = n.sub.Unsubscribe()
}
} else {
n.conn.Close()
}
n.closed = true
stream := n.parent
close(n.ch)
n.mu.Unlock()
stream.mu.Lock()
delete(stream.conns, n)
stream.mu.Unlock()
return err
}
func (n *natsConn) LocalAddr() net.Addr {
return n.localAddr
}
func (n *natsConn) RemoteAddr() net.Addr {
return n.remoteAddr
}
func (n *natsConn) SetDeadline(t time.Time) error {
n.mu.Lock()
if t.IsZero() {
n.subTimeout = 0
} else {
n.subTimeout = time.Until(t)
}
n.mu.Unlock()
return nil
}
func (n *natsConn) SetReadDeadline(t time.Time) error {
return n.SetDeadline(t)
}
func (n *natsConn) SetWriteDeadline(t time.Time) error {
return n.SetDeadline(t)
}
// natsStreamLayer implements the raft.StreamLayer interface.
type natsStreamLayer struct {
conn *nats.Conn
makeConn natsRaftConnCreator
localAddr natsAddr
sub *nats.Subscription
logger hclog.Logger
conns map[*natsConn]struct{}
mu sync.Mutex
// This is the timeout we will use for flush and dial (request timeout),
// not the timeout that RAFT will use to call SetDeadline.
dfTimeout time.Duration
}
func newNATSStreamLayer(id string, conn *nats.Conn, logger hclog.Logger, timeout time.Duration, makeConn natsRaftConnCreator) (*natsStreamLayer, error) {
n := &natsStreamLayer{
localAddr: natsAddr(id),
conn: conn,
makeConn: makeConn,
logger: logger,
conns: map[*natsConn]struct{}{},
dfTimeout: timeoutForDialAndFlush,
}
// Could be the case in tests...
if timeout < n.dfTimeout {
n.dfTimeout = timeout
}
sub, err := conn.SubscribeSync(fmt.Sprintf(natsConnectInbox, id))
if err != nil {
return nil, err
}
if err := conn.FlushTimeout(n.dfTimeout); err != nil {
sub.Unsubscribe()
return nil, err
}
n.sub = sub
return n, nil
}
func (n *natsStreamLayer) newNATSConn(address string) (*natsConn, error) {
var conn *nats.Conn
var err error
c := &natsConn{
localAddr: n.localAddr,
remoteAddr: natsAddr(address),
parent: n,
ch: make(chan struct{}, 1),
}
if n.makeConn == nil {
c.conn = n.conn
c.streamConn = true
} else {
conn, err = n.makeConn(address)
if err != nil {
return nil, err
}
c.conn = conn
}
return c, nil
}
// Dial creates a new net.Conn with the remote address. This is implemented by
// performing a handshake over NATS which establishes unique inboxes at each
// endpoint for streaming data.
func (n *natsStreamLayer) Dial(address raft.ServerAddress, timeout time.Duration) (net.Conn, error) {
if !n.conn.IsConnected() {
return nil, errors.New("raft-nats: dial failed, not connected")
}
connect := &connectRequestProto{
ID: n.localAddr.String(),
Inbox: fmt.Sprintf(natsRequestInbox, n.localAddr.String(), nats.NewInbox()),
}
data, err := json.Marshal(connect)
if err != nil {
panic(err)
}
// When creating the transport, we pass a 10s timeout, but for Dial, we want
// to use a different timeout, unless the one provided is smaller.
if timeout > n.dfTimeout {
timeout = n.dfTimeout
}
// Make connect request to peer.
msg, err := n.conn.Request(fmt.Sprintf(natsConnectInbox, address), data, timeout)
if err != nil {
return nil, err
}
var resp connectResponseProto
if err := json.Unmarshal(msg.Data, &resp); err != nil {
return nil, err
}
// Success, so now create a new NATS connection...
peerConn, err := n.newNATSConn(string(address))
if err != nil {
return nil, fmt.Errorf("raft-nats: unable to create connection to %q: %v", string(address), err)
}
// Setup inbox.
peerConn.mu.Lock()
sub, err := peerConn.conn.Subscribe(connect.Inbox, peerConn.onMsg)
if err != nil {
peerConn.mu.Unlock()
peerConn.Close()
return nil, err
}
sub.SetPendingLimits(-1, -1)
peerConn.sub = sub
peerConn.outbox = resp.Inbox
peerConn.mu.Unlock()
if err := peerConn.conn.FlushTimeout(timeout); err != nil {
peerConn.Close()
return nil, err
}
n.mu.Lock()
n.conns[peerConn] = struct{}{}
n.mu.Unlock()
return peerConn, nil
}
// Accept waits for and returns the next connection to the listener.
func (n *natsStreamLayer) Accept() (net.Conn, error) {
for {
msg, err := n.sub.NextMsgWithContext(context.TODO())
if err != nil {
return nil, err
}
if msg.Reply == "" {
n.logger.Error("Invalid connect message (missing reply inbox)")
continue
}
var connect connectRequestProto
if err := json.Unmarshal(msg.Data, &connect); err != nil {
n.logger.Error("Invalid connect message (invalid data)")
continue
}
peerConn, err := n.newNATSConn(connect.ID)
if err != nil {
n.logger.Error("Unable to create connection to %q: %v", connect.ID, err)
continue
}
// Setup inbox for peer.
inbox := fmt.Sprintf(natsRequestInbox, n.localAddr.String(), nats.NewInbox())
peerConn.mu.Lock()
sub, err := peerConn.conn.Subscribe(inbox, peerConn.onMsg)
if err != nil {
peerConn.mu.Unlock()
n.logger.Error("Failed to create inbox for remote peer", "error", err)
peerConn.Close()
continue
}
sub.SetPendingLimits(-1, -1)
peerConn.outbox = connect.Inbox
peerConn.sub = sub
shouldFlush := !peerConn.streamConn
peerConn.mu.Unlock()
if shouldFlush {
if err := peerConn.conn.FlushTimeout(n.dfTimeout); err != nil {
peerConn.Close()
continue
}
}
// Reply to peer.
resp := &connectResponseProto{Inbox: inbox}
data, err := json.Marshal(resp)
if err != nil {
panic(err)
}
if err := n.conn.Publish(msg.Reply, data); err != nil {
n.logger.Error("Failed to send connect response to remote peer", "error", err)
peerConn.Close()
continue
}
if err := n.conn.FlushTimeout(n.dfTimeout); err != nil {
n.logger.Error("Failed to flush connect response to remote peer", "error", err)
peerConn.Close()
continue
}
n.mu.Lock()
n.conns[peerConn] = struct{}{}
n.mu.Unlock()
return peerConn, nil
}
}
func (n *natsStreamLayer) Close() error {
n.mu.Lock()
nc := n.conn
// Do not set nc.conn to nil since it is accessed in some functions
// without the stream layer lock
conns := make(map[*natsConn]struct{}, len(n.conns))
for conn, s := range n.conns {
conns[conn] = s
}
n.mu.Unlock()
for c := range conns {
c.Close()
}
if nc != nil {
nc.Close()
}
return nil
}
func (n *natsStreamLayer) Addr() net.Addr {
return n.localAddr
}
// newNATSTransport creates a new raft.NetworkTransport implemented with NATS
// as the transport layer.
func newNATSTransport(id string, conn *nats.Conn, timeout time.Duration, logOutput io.Writer, makeConn natsRaftConnCreator) (*raft.NetworkTransport, error) {
if logOutput == nil {
logOutput = os.Stderr
}
logger := hclog.New(&hclog.LoggerOptions{
Name: natsLogAppName,
Level: hclog.Debug,
Output: logOutput,
})
return createNATSTransport(id, conn, timeout, makeConn, logger, nil)
}
// newNATSTransportWithLogger creates a new raft.NetworkTransport implemented
// with NATS as the transport layer using the provided Logger.
func newNATSTransportWithLogger(id string, conn *nats.Conn, timeout time.Duration, logger hclog.Logger) (*raft.NetworkTransport, error) {
return createNATSTransport(id, conn, timeout, nil, logger, nil)
}
// newNATSTransportWithConfig returns a raft.NetworkTransport implemented
// with NATS as the transport layer, using the given config struct.
func newNATSTransportWithConfig(id string, conn *nats.Conn, config *raft.NetworkTransportConfig) (*raft.NetworkTransport, error) {
return createNATSTransport(id, conn, 0, nil, nil, config)
}
func createNATSTransport(id string, conn *nats.Conn, timeout time.Duration, makeConn natsRaftConnCreator,
logger hclog.Logger, config *raft.NetworkTransportConfig) (*raft.NetworkTransport, error) {
if config != nil {
if config.Timeout == 0 {
config.Timeout = defaultTPortTimeout
}
timeout = config.Timeout
logger = config.Logger
}
stream, err := newNATSStreamLayer(id, conn, logger, timeout, makeConn)
if err != nil {
return nil, err
}
if config != nil {
config.Stream = stream
return raft.NewNetworkTransportWithConfig(config), nil
}
return raft.NewNetworkTransportWithLogger(stream, 3, timeout, logger), nil
}
func min(x, y int64) int64 {
if x < y {
return x
}
return y
}