forked from nats-io/nats-on-a-log
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nats_transport.go
407 lines (354 loc) · 10.6 KB
/
nats_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
// Copyright 2017-2019 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 natslog
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"sync"
"time"
"github.com/hashicorp/raft"
"github.com/nats-io/nats"
)
const (
natsConnectInbox = "raft.%s.accept"
natsRequestInbox = "raft.%s.request.%s"
timeoutForDialAndFlush = 2 * time.Second
defaultTPortTimeout = 10 * time.Second
)
// 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 {
conn *nats.Conn
localAddr natsAddr
remoteAddr natsAddr
sub *nats.Subscription
outbox string
mu sync.RWMutex
closed bool
reader *timeoutReader
writer io.WriteCloser
parent *natsStreamLayer
}
func (n *natsConn) Read(b []byte) (int, error) {
n.mu.RLock()
closed := n.closed
n.mu.RUnlock()
if closed {
return 0, errors.New("read from closed conn")
}
return n.reader.Read(b)
}
func (n *natsConn) Write(b []byte) (int, error) {
n.mu.RLock()
closed := n.closed
n.mu.RUnlock()
if closed {
return 0, errors.New("write to closed conn")
}
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()
defer n.mu.Unlock()
if n.closed {
return nil
}
if err := n.sub.Unsubscribe(); err != nil {
return err
}
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)
}
n.closed = true
n.parent.mu.Lock()
delete(n.parent.conns, n)
n.parent.mu.Unlock()
n.writer.Close()
return nil
}
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 {
if err := n.SetReadDeadline(t); err != nil {
return err
}
return n.SetWriteDeadline(t)
}
func (n *natsConn) SetReadDeadline(t time.Time) error {
n.reader.SetDeadline(t)
return nil
}
func (n *natsConn) SetWriteDeadline(t time.Time) error {
return nil
}
func (n *natsConn) msgHandler(msg *nats.Msg) {
// Check if remote peer disconnected.
if len(msg.Data) == 0 {
n.close(false)
return
}
n.writer.Write(msg.Data)
}
// natsStreamLayer implements the raft.StreamLayer interface.
type natsStreamLayer struct {
conn *nats.Conn
localAddr natsAddr
sub *nats.Subscription
logger *log.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 *log.Logger, timeout time.Duration) (*natsStreamLayer, error) {
n := &natsStreamLayer{
localAddr: natsAddr(id),
conn: conn,
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
}
sub.SetPendingLimits(-1, -1)
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 {
// TODO: probably want a buffered pipe.
reader, writer := io.Pipe()
return &natsConn{
conn: n.conn,
localAddr: n.localAddr,
remoteAddr: natsAddr(address),
reader: newTimeoutReader(reader),
writer: writer,
parent: n,
}
}
// 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")
}
// QUESTION: The Raft NetTransport does connection pooling, which is useful
// for TCP sockets. The NATS transport simulates a socket using a
// subscription at each endpoint, but everything goes over the same NATS
// socket. This means there is little advantage to pooling here currently.
// Should we actually Dial a new NATS connection here and rely on pooling?
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)
}
peerConn := n.newNATSConn(string(address))
// Setup inbox.
sub, err := n.conn.Subscribe(connect.Inbox, peerConn.msgHandler)
if err != nil {
return nil, err
}
sub.SetPendingLimits(-1, -1)
if err := n.conn.FlushTimeout(n.dfTimeout); err != nil {
sub.Unsubscribe()
return nil, err
}
// Make connect request to peer.
msg, err := n.conn.Request(fmt.Sprintf(natsConnectInbox, address), data, n.dfTimeout)
if err != nil {
sub.Unsubscribe()
return nil, err
}
var resp connectResponseProto
if err := json.Unmarshal(msg.Data, &resp); err != nil {
sub.Unsubscribe()
return nil, err
}
peerConn.sub = sub
peerConn.outbox = resp.Inbox
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.Println("[ERR] raft-nats: Invalid connect message (missing reply inbox)")
continue
}
var connect connectRequestProto
if err := json.Unmarshal(msg.Data, &connect); err != nil {
n.logger.Println("[ERR] raft-nats: Invalid connect message (invalid data)")
continue
}
peerConn := n.newNATSConn(connect.ID)
peerConn.outbox = connect.Inbox
// Setup inbox for peer.
inbox := fmt.Sprintf(natsRequestInbox, n.localAddr.String(), nats.NewInbox())
sub, err := n.conn.Subscribe(inbox, peerConn.msgHandler)
if err != nil {
n.logger.Printf("[ERR] raft-nats: Failed to create inbox for remote peer: %v", err)
continue
}
sub.SetPendingLimits(-1, -1)
// 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.Printf("[ERR] raft-nats: Failed to send connect response to remote peer: %v", err)
sub.Unsubscribe()
continue
}
if err := n.conn.FlushTimeout(n.dfTimeout); err != nil {
n.logger.Printf("[ERR] raft-nats: Failed to flush connect response to remote peer: %v", err)
sub.Unsubscribe()
continue
}
peerConn.sub = sub
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) (*raft.NetworkTransport, error) {
if logOutput == nil {
logOutput = os.Stderr
}
return NewNATSTransportWithLogger(id, conn, timeout, log.New(logOutput, "", log.LstdFlags))
}
// 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 *log.Logger) (*raft.NetworkTransport, error) {
return createNATSTransport(id, conn, logger, timeout, func(stream raft.StreamLayer) *raft.NetworkTransport {
return raft.NewNetworkTransportWithLogger(stream, 3, timeout, logger)
})
}
// 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) {
if config.Timeout == 0 {
config.Timeout = defaultTPortTimeout
}
return createNATSTransport(id, conn, log.New(os.Stdout, "", log.LstdFlags), config.Timeout, func(stream raft.StreamLayer) *raft.NetworkTransport {
config.Stream = stream
return raft.NewNetworkTransportWithConfig(config)
})
}
func createNATSTransport(id string, conn *nats.Conn, logger *log.Logger, timeout time.Duration,
transportCreator func(stream raft.StreamLayer) *raft.NetworkTransport) (*raft.NetworkTransport, error) {
stream, err := newNATSStreamLayer(id, conn, logger, timeout)
if err != nil {
return nil, err
}
return transportCreator(stream), nil
}
func min(x, y int64) int64 {
if x < y {
return x
}
return y
}