forked from nsqio/nsq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_v2.go
614 lines (508 loc) · 14.8 KB
/
client_v2.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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
package nsqd
import (
"bufio"
"compress/flate"
"crypto/tls"
"errors"
"fmt"
"net"
"sync"
"sync/atomic"
"time"
"github.com/bitly/nsq/util/auth"
"github.com/mreiferson/go-snappystream"
)
const defaultBufferSize = 16 * 1024
const (
stateInit = iota
stateDisconnected
stateConnected
stateSubscribed
stateClosing
)
type identifyDataV2 struct {
ShortId string `json:"short_id"` // TODO: deprecated, remove in 1.0
LongId string `json:"long_id"` // TODO: deprecated, remove in 1.0
ClientID string `json:"client_id"`
Hostname string `json:"hostname"`
HeartbeatInterval int `json:"heartbeat_interval"`
OutputBufferSize int `json:"output_buffer_size"`
OutputBufferTimeout int `json:"output_buffer_timeout"`
FeatureNegotiation bool `json:"feature_negotiation"`
TLSv1 bool `json:"tls_v1"`
Deflate bool `json:"deflate"`
DeflateLevel int `json:"deflate_level"`
Snappy bool `json:"snappy"`
SampleRate int32 `json:"sample_rate"`
UserAgent string `json:"user_agent"`
MsgTimeout int `json:"msg_timeout"`
}
type identifyEvent struct {
OutputBufferTimeout time.Duration
HeartbeatInterval time.Duration
SampleRate int32
MsgTimeout time.Duration
}
type clientV2 struct {
// 64bit atomic vars need to be first for proper alignment on 32bit platforms
ReadyCount int64
InFlightCount int64
MessageCount uint64
FinishCount uint64
RequeueCount uint64
sync.RWMutex
ID int64
ctx *context
UserAgent string
// original connection
net.Conn
// connections based on negotiated features
tlsConn *tls.Conn
flateWriter *flate.Writer
// reading/writing interfaces
Reader *bufio.Reader
Writer *bufio.Writer
OutputBufferSize int
OutputBufferTimeout time.Duration
HeartbeatInterval time.Duration
MsgTimeout time.Duration
State int32
ConnectTime time.Time
Channel *Channel
ReadyStateChan chan int
ExitChan chan int
ClientID string
Hostname string
SampleRate int32
IdentifyEventChan chan identifyEvent
SubEventChan chan *Channel
TLS int32
Snappy int32
Deflate int32
// re-usable buffer for reading the 4-byte lengths off the wire
lenBuf [4]byte
lenSlice []byte
AuthSecret string
AuthState *auth.AuthState
}
func newClientV2(id int64, conn net.Conn, ctx *context) *clientV2 {
var identifier string
if conn != nil {
identifier, _, _ = net.SplitHostPort(conn.RemoteAddr().String())
}
c := &clientV2{
ID: id,
ctx: ctx,
Conn: conn,
Reader: bufio.NewReaderSize(conn, defaultBufferSize),
Writer: bufio.NewWriterSize(conn, defaultBufferSize),
OutputBufferSize: defaultBufferSize,
OutputBufferTimeout: 250 * time.Millisecond,
MsgTimeout: ctx.nsqd.opts.MsgTimeout,
// ReadyStateChan has a buffer of 1 to guarantee that in the event
// there is a race the state update is not lost
ReadyStateChan: make(chan int, 1),
ExitChan: make(chan int),
ConnectTime: time.Now(),
State: stateInit,
ClientID: identifier,
Hostname: identifier,
SubEventChan: make(chan *Channel, 1),
IdentifyEventChan: make(chan identifyEvent, 1),
// heartbeats are client configurable but default to 30s
HeartbeatInterval: ctx.nsqd.opts.ClientTimeout / 2,
}
c.lenSlice = c.lenBuf[:]
return c
}
func (c *clientV2) String() string {
return c.RemoteAddr().String()
}
func (c *clientV2) Identify(data identifyDataV2) error {
c.ctx.nsqd.logf("[%s] IDENTIFY: %+v", c, data)
// TODO: for backwards compatibility, remove in 1.0
hostname := data.Hostname
if hostname == "" {
hostname = data.LongId
}
// TODO: for backwards compatibility, remove in 1.0
clientId := data.ClientID
if clientId == "" {
clientId = data.ShortId
}
c.Lock()
c.ClientID = clientId
c.Hostname = hostname
c.UserAgent = data.UserAgent
c.Unlock()
err := c.SetHeartbeatInterval(data.HeartbeatInterval)
if err != nil {
return err
}
err = c.SetOutputBufferSize(data.OutputBufferSize)
if err != nil {
return err
}
err = c.SetOutputBufferTimeout(data.OutputBufferTimeout)
if err != nil {
return err
}
err = c.SetSampleRate(data.SampleRate)
if err != nil {
return err
}
err = c.SetMsgTimeout(data.MsgTimeout)
if err != nil {
return err
}
ie := identifyEvent{
OutputBufferTimeout: c.OutputBufferTimeout,
HeartbeatInterval: c.HeartbeatInterval,
SampleRate: c.SampleRate,
MsgTimeout: c.MsgTimeout,
}
// update the client's message pump
select {
case c.IdentifyEventChan <- ie:
default:
}
return nil
}
func (c *clientV2) Stats() ClientStats {
c.RLock()
// TODO: deprecated, remove in 1.0
name := c.ClientID
clientId := c.ClientID
hostname := c.Hostname
userAgent := c.UserAgent
var identity string
var identityUrl string
if c.AuthState != nil {
identity = c.AuthState.Identity
identityUrl = c.AuthState.IdentityUrl
}
c.RUnlock()
stats := ClientStats{
// TODO: deprecated, remove in 1.0
Name: name,
Version: "V2",
RemoteAddress: c.RemoteAddr().String(),
ClientID: clientId,
Hostname: hostname,
UserAgent: userAgent,
State: atomic.LoadInt32(&c.State),
ReadyCount: atomic.LoadInt64(&c.ReadyCount),
InFlightCount: atomic.LoadInt64(&c.InFlightCount),
MessageCount: atomic.LoadUint64(&c.MessageCount),
FinishCount: atomic.LoadUint64(&c.FinishCount),
RequeueCount: atomic.LoadUint64(&c.RequeueCount),
ConnectTime: c.ConnectTime.Unix(),
SampleRate: atomic.LoadInt32(&c.SampleRate),
TLS: atomic.LoadInt32(&c.TLS) == 1,
Deflate: atomic.LoadInt32(&c.Deflate) == 1,
Snappy: atomic.LoadInt32(&c.Snappy) == 1,
Authed: c.HasAuthorizations(),
AuthIdentity: identity,
AuthIdentityURL: identityUrl,
}
if stats.TLS {
p := prettyConnectionState{c.tlsConn.ConnectionState()}
stats.CipherSuite = p.GetCipherSuite()
stats.TLSVersion = p.GetVersion()
stats.TLSNegotiatedProtocol = p.NegotiatedProtocol
stats.TLSNegotiatedProtocolIsMutual = p.NegotiatedProtocolIsMutual
}
return stats
}
// struct to convert from integers to the human readable strings
type prettyConnectionState struct {
tls.ConnectionState
}
// taken from http://golang.org/src/pkg/crypto/tls/cipher_suites.go
// to be compatible with older versions
const (
local_TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005
local_TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000a
local_TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002f
local_TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035
local_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xc007
local_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xc009
local_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xc00a
local_TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xc011
local_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc012
local_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xc013
local_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xc014
local_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02f
local_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b
)
func (p *prettyConnectionState) GetCipherSuite() string {
switch p.CipherSuite {
case local_TLS_RSA_WITH_RC4_128_SHA:
return "TLS_RSA_WITH_RC4_128_SHA"
case local_TLS_RSA_WITH_3DES_EDE_CBC_SHA:
return "TLS_RSA_WITH_3DES_EDE_CBC_SHA"
case local_TLS_RSA_WITH_AES_128_CBC_SHA:
return "TLS_RSA_WITH_AES_128_CBC_SHA"
case local_TLS_RSA_WITH_AES_256_CBC_SHA:
return "TLS_RSA_WITH_AES_256_CBC_SHA"
case local_TLS_ECDHE_ECDSA_WITH_RC4_128_SHA:
return "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"
case local_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA:
return "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"
case local_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA:
return "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"
case local_TLS_ECDHE_RSA_WITH_RC4_128_SHA:
return "TLS_ECDHE_RSA_WITH_RC4_128_SHA"
case local_TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA:
return "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"
case local_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA:
return "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
case local_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
return "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
case local_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256:
return "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
case local_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
return "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"
}
return fmt.Sprintf("unkown %d", p.CipherSuite)
}
func (c *clientV2) IsReadyForMessages() bool {
if c.Channel.IsPaused() {
return false
}
readyCount := atomic.LoadInt64(&c.ReadyCount)
inFlightCount := atomic.LoadInt64(&c.InFlightCount)
if c.ctx.nsqd.opts.Verbose {
c.ctx.nsqd.logf("[%s] state rdy: %4d inflt: %4d",
c, readyCount, inFlightCount)
}
if inFlightCount >= readyCount || readyCount <= 0 {
return false
}
return true
}
func (c *clientV2) SetReadyCount(count int64) {
atomic.StoreInt64(&c.ReadyCount, count)
c.tryUpdateReadyState()
}
func (c *clientV2) tryUpdateReadyState() {
// you can always *try* to write to ReadyStateChan because in the cases
// where you cannot the message pump loop would have iterated anyway.
// the atomic integer operations guarantee correctness of the value.
select {
case c.ReadyStateChan <- 1:
default:
}
}
func (c *clientV2) FinishedMessage() {
atomic.AddUint64(&c.FinishCount, 1)
atomic.AddInt64(&c.InFlightCount, -1)
c.tryUpdateReadyState()
}
func (c *clientV2) Empty() {
atomic.StoreInt64(&c.InFlightCount, 0)
c.tryUpdateReadyState()
}
func (c *clientV2) SendingMessage() {
atomic.AddInt64(&c.InFlightCount, 1)
atomic.AddUint64(&c.MessageCount, 1)
}
func (c *clientV2) TimedOutMessage() {
atomic.AddInt64(&c.InFlightCount, -1)
c.tryUpdateReadyState()
}
func (c *clientV2) RequeuedMessage() {
atomic.AddUint64(&c.RequeueCount, 1)
atomic.AddInt64(&c.InFlightCount, -1)
c.tryUpdateReadyState()
}
func (c *clientV2) StartClose() {
// Force the client into ready 0
c.SetReadyCount(0)
// mark this client as closing
atomic.StoreInt32(&c.State, stateClosing)
}
func (c *clientV2) Pause() {
c.tryUpdateReadyState()
}
func (c *clientV2) UnPause() {
c.tryUpdateReadyState()
}
func (c *clientV2) SetHeartbeatInterval(desiredInterval int) error {
c.Lock()
defer c.Unlock()
switch {
case desiredInterval == -1:
c.HeartbeatInterval = 0
case desiredInterval == 0:
// do nothing (use default)
case desiredInterval >= 1000 &&
desiredInterval <= int(c.ctx.nsqd.opts.MaxHeartbeatInterval/time.Millisecond):
c.HeartbeatInterval = time.Duration(desiredInterval) * time.Millisecond
default:
return errors.New(fmt.Sprintf("heartbeat interval (%d) is invalid", desiredInterval))
}
return nil
}
func (c *clientV2) SetOutputBufferSize(desiredSize int) error {
var size int
switch {
case desiredSize == -1:
// effectively no buffer (every write will go directly to the wrapped net.Conn)
size = 1
case desiredSize == 0:
// do nothing (use default)
case desiredSize >= 64 && desiredSize <= int(c.ctx.nsqd.opts.MaxOutputBufferSize):
size = desiredSize
default:
return errors.New(fmt.Sprintf("output buffer size (%d) is invalid", desiredSize))
}
if size > 0 {
c.Lock()
defer c.Unlock()
c.OutputBufferSize = size
err := c.Writer.Flush()
if err != nil {
return err
}
c.Writer = bufio.NewWriterSize(c.Conn, size)
}
return nil
}
func (c *clientV2) SetOutputBufferTimeout(desiredTimeout int) error {
c.Lock()
defer c.Unlock()
switch {
case desiredTimeout == -1:
c.OutputBufferTimeout = 0
case desiredTimeout == 0:
// do nothing (use default)
case desiredTimeout >= 1 &&
desiredTimeout <= int(c.ctx.nsqd.opts.MaxOutputBufferTimeout/time.Millisecond):
c.OutputBufferTimeout = time.Duration(desiredTimeout) * time.Millisecond
default:
return errors.New(fmt.Sprintf("output buffer timeout (%d) is invalid", desiredTimeout))
}
return nil
}
func (c *clientV2) SetSampleRate(sampleRate int32) error {
if sampleRate < 0 || sampleRate > 99 {
return errors.New(fmt.Sprintf("sample rate (%d) is invalid", sampleRate))
}
atomic.StoreInt32(&c.SampleRate, sampleRate)
return nil
}
func (c *clientV2) SetMsgTimeout(msgTimeout int) error {
c.Lock()
defer c.Unlock()
switch {
case msgTimeout == 0:
// do nothing (use default)
case msgTimeout >= 1000 &&
msgTimeout <= int(c.ctx.nsqd.opts.MaxMsgTimeout/time.Millisecond):
c.MsgTimeout = time.Duration(msgTimeout) * time.Millisecond
default:
return errors.New(fmt.Sprintf("msg timeout (%d) is invalid", msgTimeout))
}
return nil
}
func (c *clientV2) UpgradeTLS() error {
c.Lock()
defer c.Unlock()
tlsConn := tls.Server(c.Conn, c.ctx.nsqd.tlsConfig)
tlsConn.SetDeadline(time.Now().Add(5 * time.Second))
err := tlsConn.Handshake()
if err != nil {
return err
}
c.tlsConn = tlsConn
c.Reader = bufio.NewReaderSize(c.tlsConn, defaultBufferSize)
c.Writer = bufio.NewWriterSize(c.tlsConn, c.OutputBufferSize)
atomic.StoreInt32(&c.TLS, 1)
return nil
}
func (c *clientV2) UpgradeDeflate(level int) error {
c.Lock()
defer c.Unlock()
conn := c.Conn
if c.tlsConn != nil {
conn = c.tlsConn
}
c.Reader = bufio.NewReaderSize(flate.NewReader(conn), defaultBufferSize)
fw, _ := flate.NewWriter(conn, level)
c.flateWriter = fw
c.Writer = bufio.NewWriterSize(fw, c.OutputBufferSize)
atomic.StoreInt32(&c.Deflate, 1)
return nil
}
func (c *clientV2) UpgradeSnappy() error {
c.Lock()
defer c.Unlock()
conn := c.Conn
if c.tlsConn != nil {
conn = c.tlsConn
}
c.Reader = bufio.NewReaderSize(snappystream.NewReader(conn, snappystream.SkipVerifyChecksum), defaultBufferSize)
c.Writer = bufio.NewWriterSize(snappystream.NewWriter(conn), c.OutputBufferSize)
atomic.StoreInt32(&c.Snappy, 1)
return nil
}
func (c *clientV2) Flush() error {
var zeroTime time.Time
if c.HeartbeatInterval > 0 {
c.SetWriteDeadline(time.Now().Add(c.HeartbeatInterval))
} else {
c.SetWriteDeadline(zeroTime)
}
err := c.Writer.Flush()
if err != nil {
return err
}
if c.flateWriter != nil {
return c.flateWriter.Flush()
}
return nil
}
func (c *clientV2) QueryAuthd() error {
remoteIp, _, err := net.SplitHostPort(c.String())
if err != nil {
return err
}
tls := atomic.LoadInt32(&c.TLS) == 1
tlsEnabled := "false"
if tls {
tlsEnabled = "true"
}
authState, err := auth.QueryAnyAuthd(c.ctx.nsqd.opts.AuthHTTPAddresses,
remoteIp, tlsEnabled, c.AuthSecret)
if err != nil {
return err
}
c.AuthState = authState
return nil
}
func (c *clientV2) Auth(secret string) error {
c.AuthSecret = secret
return c.QueryAuthd()
}
func (c *clientV2) IsAuthorized(topic, channel string) (bool, error) {
if c.AuthState == nil {
return false, nil
}
if c.AuthState.IsExpired() {
err := c.QueryAuthd()
if err != nil {
return false, err
}
}
if c.AuthState.IsAllowed(topic, channel) {
return true, nil
}
return false, nil
}
func (c *clientV2) HasAuthorizations() bool {
if c.AuthState != nil {
return len(c.AuthState.Authorizations) != 0
}
return false
}