forked from hashicorp/consul
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc.go
558 lines (472 loc) · 12.5 KB
/
rpc.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
package agent
/*
The agent exposes an RPC mechanism that is used for both controlling
Consul as well as providing a fast streaming mechanism for events. This
allows other applications to easily leverage Consul without embedding.
We additionally make use of the RPC layer to also handle calls from
the CLI to unify the code paths. This results in a split Request/Response
as well as streaming mode of operation.
The system is fairly simple, each client opens a TCP connection to the
agent. The connection is initialized with a handshake which establishes
the protocol version being used. This is to allow for future changes to
the protocol.
Once initialized, clients send commands and wait for responses. Certain
commands will cause the client to subscribe to events, and those will be
pushed down the socket as they are received. This provides a low-latency
mechanism for applications to send and receive events, while also providing
a flexible control mechanism for Consul.
*/
import (
"bufio"
"fmt"
"github.com/hashicorp/logutils"
"github.com/hashicorp/serf/serf"
"github.com/ugorji/go/codec"
"io"
"log"
"net"
"os"
"strings"
"sync"
)
const (
MinRPCVersion = 1
MaxRPCVersion = 1
)
const (
handshakeCommand = "handshake"
forceLeaveCommand = "force-leave"
joinCommand = "join"
membersLANCommand = "members-lan"
membersWANCommand = "members-wan"
stopCommand = "stop"
monitorCommand = "monitor"
leaveCommand = "leave"
statsCommand = "stats"
)
const (
unsupportedCommand = "Unsupported command"
unsupportedRPCVersion = "Unsupported RPC version"
duplicateHandshake = "Handshake already performed"
handshakeRequired = "Handshake required"
monitorExists = "Monitor already exists"
)
// Request header is sent before each request
type requestHeader struct {
Command string
Seq uint64
}
// Response header is sent before each response
type responseHeader struct {
Seq uint64
Error string
}
type handshakeRequest struct {
Version int32
}
type eventRequest struct {
Name string
Payload []byte
Coalesce bool
}
type forceLeaveRequest struct {
Node string
}
type joinRequest struct {
Existing []string
WAN bool
}
type joinResponse struct {
Num int32
}
type membersResponse struct {
Members []Member
}
type monitorRequest struct {
LogLevel string
}
type streamRequest struct {
Type string
}
type stopRequest struct {
Stop uint64
}
type logRecord struct {
Log string
}
type userEventRecord struct {
Event string
LTime serf.LamportTime
Name string
Payload []byte
Coalesce bool
}
type Member struct {
Name string
Addr net.IP
Port uint16
Tags map[string]string
Status string
ProtocolMin uint8
ProtocolMax uint8
ProtocolCur uint8
DelegateMin uint8
DelegateMax uint8
DelegateCur uint8
}
type memberEventRecord struct {
Event string
Members []Member
}
type AgentRPC struct {
sync.Mutex
agent *Agent
clients map[string]*rpcClient
listener net.Listener
logger *log.Logger
logWriter *logWriter
stop bool
stopCh chan struct{}
}
type rpcClient struct {
name string
conn net.Conn
reader *bufio.Reader
writer *bufio.Writer
dec *codec.Decoder
enc *codec.Encoder
writeLock sync.Mutex
version int32 // From the handshake, 0 before
logStreamer *logStream
}
// send is used to send an object using the MsgPack encoding. send
// is serialized to prevent write overlaps, while properly buffering.
func (c *rpcClient) Send(header *responseHeader, obj interface{}) error {
c.writeLock.Lock()
defer c.writeLock.Unlock()
if err := c.enc.Encode(header); err != nil {
return err
}
if obj != nil {
if err := c.enc.Encode(obj); err != nil {
return err
}
}
if err := c.writer.Flush(); err != nil {
return err
}
return nil
}
func (c *rpcClient) String() string {
return fmt.Sprintf("rpc.client: %v", c.conn)
}
// NewAgentRPC is used to create a new Agent RPC handler
func NewAgentRPC(agent *Agent, listener net.Listener,
logOutput io.Writer, logWriter *logWriter) *AgentRPC {
if logOutput == nil {
logOutput = os.Stderr
}
rpc := &AgentRPC{
agent: agent,
clients: make(map[string]*rpcClient),
listener: listener,
logger: log.New(logOutput, "", log.LstdFlags),
logWriter: logWriter,
stopCh: make(chan struct{}),
}
go rpc.listen()
return rpc
}
// Shutdown is used to shutdown the RPC layer
func (i *AgentRPC) Shutdown() {
i.Lock()
defer i.Unlock()
if i.stop {
return
}
i.stop = true
close(i.stopCh)
i.listener.Close()
// Close the existing connections
for _, client := range i.clients {
client.conn.Close()
}
}
// listen is a long running routine that listens for new clients
func (i *AgentRPC) listen() {
for {
conn, err := i.listener.Accept()
if err != nil {
if i.stop {
return
}
i.logger.Printf("[ERR] agent.rpc: Failed to accept client: %v", err)
continue
}
i.logger.Printf("[INFO] agent.rpc: Accepted client: %v", conn.RemoteAddr())
// Wrap the connection in a client
client := &rpcClient{
name: conn.RemoteAddr().String(),
conn: conn,
reader: bufio.NewReader(conn),
writer: bufio.NewWriter(conn),
}
client.dec = codec.NewDecoder(client.reader,
&codec.MsgpackHandle{RawToString: true, WriteExt: true})
client.enc = codec.NewEncoder(client.writer,
&codec.MsgpackHandle{RawToString: true, WriteExt: true})
if err != nil {
i.logger.Printf("[ERR] agent.rpc: Failed to create decoder: %v", err)
conn.Close()
continue
}
// Register the client
i.Lock()
if !i.stop {
i.clients[client.name] = client
go i.handleClient(client)
} else {
conn.Close()
}
i.Unlock()
}
}
// deregisterClient is called to cleanup after a client disconnects
func (i *AgentRPC) deregisterClient(client *rpcClient) {
// Close the socket
client.conn.Close()
// Remove from the clients list
i.Lock()
delete(i.clients, client.name)
i.Unlock()
// Remove from the log writer
if client.logStreamer != nil {
i.logWriter.DeregisterHandler(client.logStreamer)
client.logStreamer.Stop()
}
}
// handleClient is a long running routine that handles a single client
func (i *AgentRPC) handleClient(client *rpcClient) {
defer i.deregisterClient(client)
var reqHeader requestHeader
for {
// Decode the header
if err := client.dec.Decode(&reqHeader); err != nil {
if err != io.EOF && !i.stop {
i.logger.Printf("[ERR] agent.rpc: failed to decode request header: %v", err)
}
return
}
// Evaluate the command
if err := i.handleRequest(client, &reqHeader); err != nil {
i.logger.Printf("[ERR] agent.rpc: Failed to evaluate request: %v", err)
return
}
}
}
// handleRequest is used to evaluate a single client command
func (i *AgentRPC) handleRequest(client *rpcClient, reqHeader *requestHeader) error {
// Look for a command field
command := reqHeader.Command
seq := reqHeader.Seq
// Ensure the handshake is performed before other commands
if command != handshakeCommand && client.version == 0 {
respHeader := responseHeader{Seq: seq, Error: handshakeRequired}
client.Send(&respHeader, nil)
return fmt.Errorf(handshakeRequired)
}
// Dispatch command specific handlers
switch command {
case handshakeCommand:
return i.handleHandshake(client, seq)
case membersLANCommand:
return i.handleMembersLAN(client, seq)
case membersWANCommand:
return i.handleMembersWAN(client, seq)
case monitorCommand:
return i.handleMonitor(client, seq)
case stopCommand:
return i.handleStop(client, seq)
case forceLeaveCommand:
return i.handleForceLeave(client, seq)
case joinCommand:
return i.handleJoin(client, seq)
case leaveCommand:
return i.handleLeave(client, seq)
case statsCommand:
return i.handleStats(client, seq)
default:
respHeader := responseHeader{Seq: seq, Error: unsupportedCommand}
client.Send(&respHeader, nil)
return fmt.Errorf("command '%s' not recognized", command)
}
}
func (i *AgentRPC) handleHandshake(client *rpcClient, seq uint64) error {
var req handshakeRequest
if err := client.dec.Decode(&req); err != nil {
return fmt.Errorf("decode failed: %v", err)
}
resp := responseHeader{
Seq: seq,
Error: "",
}
// Check the version
if req.Version < MinRPCVersion || req.Version > MaxRPCVersion {
resp.Error = unsupportedRPCVersion
} else if client.version != 0 {
resp.Error = duplicateHandshake
} else {
client.version = req.Version
}
return client.Send(&resp, nil)
}
func (i *AgentRPC) handleForceLeave(client *rpcClient, seq uint64) error {
var req forceLeaveRequest
if err := client.dec.Decode(&req); err != nil {
return fmt.Errorf("decode failed: %v", err)
}
// Attempt leave
err := i.agent.ForceLeave(req.Node)
// Respond
resp := responseHeader{
Seq: seq,
Error: errToString(err),
}
return client.Send(&resp, nil)
}
func (i *AgentRPC) handleJoin(client *rpcClient, seq uint64) error {
var req joinRequest
if err := client.dec.Decode(&req); err != nil {
return fmt.Errorf("decode failed: %v", err)
}
// Attempt the join
var num int
var err error
if req.WAN {
num, err = i.agent.JoinWAN(req.Existing)
} else {
num, err = i.agent.JoinLAN(req.Existing)
}
// Respond
header := responseHeader{
Seq: seq,
Error: errToString(err),
}
resp := joinResponse{
Num: int32(num),
}
return client.Send(&header, &resp)
}
func (i *AgentRPC) handleMembersLAN(client *rpcClient, seq uint64) error {
raw := i.agent.LANMembers()
return formatMembers(raw, client, seq)
}
func (i *AgentRPC) handleMembersWAN(client *rpcClient, seq uint64) error {
raw := i.agent.WANMembers()
return formatMembers(raw, client, seq)
}
func formatMembers(raw []serf.Member, client *rpcClient, seq uint64) error {
members := make([]Member, 0, len(raw))
for _, m := range raw {
sm := Member{
Name: m.Name,
Addr: m.Addr,
Port: m.Port,
Tags: m.Tags,
Status: m.Status.String(),
ProtocolMin: m.ProtocolMin,
ProtocolMax: m.ProtocolMax,
ProtocolCur: m.ProtocolCur,
DelegateMin: m.DelegateMin,
DelegateMax: m.DelegateMax,
DelegateCur: m.DelegateCur,
}
members = append(members, sm)
}
header := responseHeader{
Seq: seq,
Error: "",
}
resp := membersResponse{
Members: members,
}
return client.Send(&header, &resp)
}
func (i *AgentRPC) handleMonitor(client *rpcClient, seq uint64) error {
var req monitorRequest
if err := client.dec.Decode(&req); err != nil {
return fmt.Errorf("decode failed: %v", err)
}
resp := responseHeader{
Seq: seq,
Error: "",
}
// Upper case the log level
req.LogLevel = strings.ToUpper(req.LogLevel)
// Create a level filter
filter := LevelFilter()
filter.MinLevel = logutils.LogLevel(req.LogLevel)
if !ValidateLevelFilter(filter.MinLevel, filter) {
resp.Error = fmt.Sprintf("Unknown log level: %s", filter.MinLevel)
goto SEND
}
// Check if there is an existing monitor
if client.logStreamer != nil {
resp.Error = monitorExists
goto SEND
}
// Create a log streamer
client.logStreamer = newLogStream(client, filter, seq, i.logger)
// Register with the log writer. Defer so that we can respond before
// registration, avoids any possible race condition
defer i.logWriter.RegisterHandler(client.logStreamer)
SEND:
return client.Send(&resp, nil)
}
func (i *AgentRPC) handleStop(client *rpcClient, seq uint64) error {
var req stopRequest
if err := client.dec.Decode(&req); err != nil {
return fmt.Errorf("decode failed: %v", err)
}
// Remove a log monitor if any
if client.logStreamer != nil && client.logStreamer.seq == req.Stop {
i.logWriter.DeregisterHandler(client.logStreamer)
client.logStreamer.Stop()
client.logStreamer = nil
}
// Always succeed
resp := responseHeader{Seq: seq, Error: ""}
return client.Send(&resp, nil)
}
func (i *AgentRPC) handleLeave(client *rpcClient, seq uint64) error {
i.logger.Printf("[INFO] agent.rpc: Graceful leave triggered")
// Do the leave
err := i.agent.Leave()
if err != nil {
i.logger.Printf("[ERR] agent.rpc: leave failed: %v", err)
}
resp := responseHeader{Seq: seq, Error: errToString(err)}
// Send and wait
err = client.Send(&resp, nil)
// Trigger a shutdown!
if err := i.agent.Shutdown(); err != nil {
i.logger.Printf("[ERR] agent.rpc: shutdown failed: %v", err)
}
return err
}
// handleStats is used to get various statistics
func (i *AgentRPC) handleStats(client *rpcClient, seq uint64) error {
header := responseHeader{
Seq: seq,
Error: "",
}
resp := i.agent.Stats()
return client.Send(&header, resp)
}
// Used to convert an error to a string representation
func errToString(err error) string {
if err == nil {
return ""
}
return err.Error()
}