forked from tolsen/mongonet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy_session.go
762 lines (705 loc) · 24 KB
/
proxy_session.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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
package mongonet
import (
"bytes"
"errors"
"fmt"
"io"
"net"
"runtime/pprof"
"strings"
"time"
"github.com/mongodb/mongonet/util"
"github.com/mongodb/slogger/v2/slogger"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/address"
"go.mongodb.org/mongo-driver/mongo/description"
"go.mongodb.org/mongo-driver/mongo/readpref"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"go.mongodb.org/mongo-driver/x/mongo/driver"
"go.mongodb.org/mongo-driver/x/mongo/driver/topology"
)
type ProxySession struct {
*Session
proxy *Proxy
interceptor ProxyInterceptor
hooks map[string]MetricsHook
mongoConn *MongoConnectionWrapper
isMetricsEnabled bool
}
type MetricsHook interface {
StartTimer() error
StopTimer()
SetGauge(val float64) error
AddCounterGauge(val float64) error
SubGauge(val float64) error
IncCounterGauge() error
DecGauge() error
}
type MetricsHookFactory interface {
NewHook(metricName, labelName, labelValue string) (MetricsHook, error)
}
type ResponseInterceptor interface {
InterceptMongoToClient(m Message, serverAddress address.Address, isRemote bool) (Message, error)
}
type ProxyInterceptor interface {
InterceptClientToMongo(m Message, previousResult SimpleBSON) (
newMsg Message,
ri ResponseInterceptor,
remoteRs string,
pinnedAddress address.Address,
err error,
)
Close()
TrackRequest(MessageHeader)
TrackResponse(MessageHeader)
CheckConnection() error
CheckConnectionInterval() time.Duration
}
type ProxyInterceptorFactory interface {
// This has to be thread safe, will be called from many clients
NewInterceptor(ps *ProxySession) (ProxyInterceptor, error)
}
// -----
func (ps *ProxySession) RemoteAddr() net.Addr {
return ps.remoteAddr
}
func (ps *ProxySession) GetLogger() *slogger.Logger {
return ps.logger
}
func (ps *ProxySession) ServerPort() int {
return ps.proxy.Config.BindPort
}
func (ps *ProxySession) Stats() bson.D {
return bson.D{
{"connectionPool", bson.D{
{"totalCreated", ps.proxy.GetConnectionsCreated()},
},
},
}
}
// doRetryLoop will retry the previous message on an RS specified by ProxyRetryError. Future iterations will read new messages on the client->proxy connection and continue to send them to the new RS
// The RS can be empty to indicate the operation should be retried on the default RS
func (ps *ProxySession) doRetryLoop(retryError *ProxyRetryError) {
// retry the message on another rs in case of a ProxyRetryError. This function assumes that ps.mongoConn is closed or nil.
var err error
retryOnRs := retryError.RetryOnRs
for {
ps.mongoConn, err = ps.doLoop(ps.mongoConn, retryError, retryOnRs)
if err != nil {
if ps.mongoConn != nil {
ps.mongoConn.Close(ps)
}
if err != io.EOF {
ps.logger.Logf(slogger.WARN, "error doing loop during retry: %v", err)
}
return
}
retryError = nil
}
}
func (ps *ProxySession) DoLoopTemp() {
defer logPanic(ps.logger)
var err error
var retryError *ProxyRetryError
var shouldRetry bool
for {
ps.mongoConn, err = ps.doLoop(ps.mongoConn, nil, "")
if err != nil {
if ps.mongoConn != nil {
ps.mongoConn.Close(ps)
}
retryError, shouldRetry = err.(*ProxyRetryError)
if shouldRetry {
ps.logger.Logf(slogger.WARN, "%v", retryError)
ps.doRetryLoop(retryError)
break
}
if err != io.EOF {
ps.logger.Logf(slogger.WARN, "error doing loop: %v", err)
}
return
}
}
}
func (ps *ProxySession) respondWithError(clientMessage Message, err error) error {
ps.logger.Logf(slogger.INFO, "respondWithError %v", err)
var errBSON bson.D
if err == nil {
errBSON = bson.D{{"ok", 1}}
} else if mongoErr, ok := err.(MongoError); ok {
errBSON = mongoErr.ToBSON()
} else {
errBSON = bson.D{{"ok", 0}, {"errmsg", err.Error()}}
}
doc, myErr := SimpleBSONConvert(errBSON)
if myErr != nil {
return myErr
}
switch clientMessage.Header().OpCode {
case OP_QUERY, OP_GET_MORE:
rm := &ReplyMessage{
MessageHeader{
0,
17, // TODO
clientMessage.Header().RequestID,
OP_REPLY},
// We should not set the error bit because we are
// responding with errmsg instead of $err
0, // flags - error bit
0, // cursor id
0, // StartingFrom
1, // NumberReturned
[]SimpleBSON{doc},
}
return SendMessage(rm, ps.conn)
case OP_COMMAND:
rm := &CommandReplyMessage{
MessageHeader{
0,
17, // TODO
clientMessage.Header().RequestID,
OP_COMMAND_REPLY},
doc,
SimpleBSONEmpty(),
[]SimpleBSON{},
}
return SendMessage(rm, ps.conn)
case OP_MSG:
rm := &MessageMessage{
MessageHeader{
0,
17, // TODO
clientMessage.Header().RequestID,
OP_MSG},
0,
[]MessageMessageSection{
&BodySection{
doc,
},
},
}
return SendMessage(rm, ps.conn)
default:
panic(fmt.Sprintf("unsupported opcode %v", clientMessage.Header().OpCode))
}
}
func (ps *ProxySession) Close() {
if ps.interceptor != nil {
ps.interceptor.Close()
}
}
func logPanic(logger *slogger.Logger) {
if r := recover(); r != nil {
var stacktraces bytes.Buffer
pprof.Lookup("goroutine").WriteTo(&stacktraces, 2)
logger.Logf(slogger.ERROR, "Recovering from mongonet panic. error is: %v \n stack traces: %v", r, stacktraces.String())
logger.Flush()
panic(r)
}
}
func getReadPrefFromOpMsg(mm *MessageMessage, logger *slogger.Logger, defaultRp *readpref.ReadPref) (rp *readpref.ReadPref, err error) {
bodyDoc, err2 := mm.BodyDoc()
if err != nil {
return nil, fmt.Errorf("Error getting body of document: %v", err2)
}
rpVal, err2 := bodyDoc.LookupErr("$readPreference")
if err2 != nil {
if err2 == bsoncore.ErrElementNotFound {
return defaultRp, nil
}
return nil, fmt.Errorf("got an error looking up $readPreference: %v", err)
}
rpDoc, ok := rpVal.DocumentOK()
if !ok {
return nil, fmt.Errorf("$readPreference isn't a document")
}
opts := make([]readpref.Option, 0, 1)
if maxStalenessVal, err := rpDoc.LookupErr("maxStalenessSeconds"); err == nil {
if maxStalenessSec, ok := maxStalenessVal.AsInt32OK(); ok && maxStalenessSec >= MinMaxStalenessVal {
opts = append(opts, readpref.WithMaxStaleness(time.Duration(maxStalenessSec)*time.Second))
} else {
return nil, fmt.Errorf("maxStalenessSeconds %v is invalid", maxStalenessVal)
}
}
if modeVal, err2 := rpDoc.LookupErr("mode"); err2 == nil {
modeStr, ok := modeVal.StringValueOK()
if !ok {
return nil, fmt.Errorf("mode %v isn't a string", modeVal)
}
switch strings.ToLower(modeStr) {
case "primarypreferred":
return readpref.PrimaryPreferred(opts...), nil
case "secondary":
return readpref.Secondary(opts...), nil
case "secondarypreferred":
return readpref.SecondaryPreferred(opts...), nil
case "nearest":
return readpref.Nearest(opts...), nil
case "primary":
return defaultRp, nil
default:
return nil, fmt.Errorf("got unsupported read preference %v", modeStr)
}
} else {
return nil, errors.New("read preference is missing the required \"mode\" field")
}
}
func PinnedServerSelector(addr address.Address) description.ServerSelector {
return description.ServerSelectorFunc(func(t description.Topology, candidates []description.Server) ([]description.Server, error) {
for _, s := range candidates {
if s.Addr == addr {
return []description.Server{s}, nil
}
}
return nil, nil
})
}
func (ps *ProxySession) getMongoConnection(
rp *readpref.ReadPref,
topology *topology.Topology,
pinnedAddress address.Address,
) (*MongoConnectionWrapper, error) {
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "finding a server. readpref=%v, pinnedAddress=%v", rp, pinnedAddress)
var srvSelector description.ServerSelector
switch {
case len(pinnedAddress.String()) > 0:
srvSelector = PinnedServerSelector(pinnedAddress)
case ps.proxy.Config.ConnectionMode == util.Cluster:
srvSelector = description.ReadPrefSelector(rp)
default:
// Direct
srvSelector = PinnedServerSelector(address.Address(ps.proxy.Config.MongoAddress()))
}
srv, err := topology.SelectServer(ps.proxy.Context, srvSelector)
if err != nil {
return nil, err
}
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "found a server. connecting")
ep, ok := srv.(driver.ErrorProcessor)
if !ok {
return nil, fmt.Errorf("server ErrorProcessor type assertion failed")
}
conn, err := srv.Connection(ps.proxy.Context)
if err != nil {
return nil, err
}
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "connected to %v", conn.Address())
ec, ok := conn.(driver.Expirable)
if !ok {
return nil, fmt.Errorf("bad connection type %T", conn)
}
return &MongoConnectionWrapper{conn, ep, ec, false, ps.proxy.logger, ps.proxy.Config.TraceConnPool}, nil
}
func wrapNetworkError(err error) error {
labels := []string{driver.NetworkError}
return driver.Error{Message: err.Error(), Labels: labels, Wrapped: err}
}
func (ps *ProxySession) doLoop(mongoConn *MongoConnectionWrapper, retryError *ProxyRetryError, remoteRs string) (*MongoConnectionWrapper, error) {
var requestDurationHook, responseDurationHook, requestErrorsHook, responseErrorsHook MetricsHook
if ps.isMetricsEnabled {
var ok bool
requestDurationHook, ok = ps.hooks["requestDurationHook"]
if !ok {
return nil, fmt.Errorf("could not access the request processing duration metric hook")
}
responseDurationHook, ok = ps.hooks["responseDurationHook"]
if !ok {
return nil, fmt.Errorf("could not access the response processing duration metric hook")
}
requestErrorsHook, ok = ps.hooks["requestErrorsHook"]
if !ok {
return nil, fmt.Errorf("could not access the request processing errors metric hook")
}
responseErrorsHook, ok = ps.hooks["responseErrorsHook"]
if !ok {
return nil, fmt.Errorf("could not access the response processing errors metric hook")
}
}
// reading message from client
var err error
var m Message
var previousRes SimpleBSON
if retryError == nil {
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "reading message from client")
m, err = ReadMessage(ps.conn)
if err != nil {
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "reading message from client fail %v", err)
if ps.isMetricsEnabled {
hookErr := requestErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment requestErrorsHook %v", hookErr)
}
}
if err == io.EOF {
return mongoConn, err
}
return mongoConn, NewStackErrorf("got error reading from client: %v", err)
}
} else {
m = retryError.MsgToRetry
previousRes = retryError.PreviousResult
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "retrying a message from client on rs=%v", retryError.RetryOnRs)
}
isRequestTimerStarted := false
startServerSelection := time.Now()
if ps.isMetricsEnabled {
hookErr := requestDurationHook.StartTimer()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to start request duration metric hook timer %v", hookErr)
} else {
isRequestTimerStarted = true
}
}
var rp *readpref.ReadPref = ps.proxy.defaultReadPref
if ps.proxy.Config.ConnectionMode == util.Cluster {
// only concerned about OP_MSG at this point
mm, ok := m.(*MessageMessage)
if ok {
rp2, err := getReadPrefFromOpMsg(mm, ps.proxy.logger, rp)
if err != nil {
if ps.isMetricsEnabled {
hookErr := requestErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment requestErrorsHook %v", hookErr)
}
}
return mongoConn, err
}
if rp2 != nil {
rp = rp2
}
}
}
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "got message from client")
ps.logMessageTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, m)
var respInter ResponseInterceptor
var pinnedAddress address.Address
if ps.interceptor != nil {
ps.interceptor.TrackRequest(m.Header())
m, respInter, remoteRs, pinnedAddress, err = ps.interceptor.InterceptClientToMongo(m, previousRes)
if err != nil {
if m == nil {
if ps.isMetricsEnabled {
hookErr := requestErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment requestErrorsHook %v", hookErr)
}
}
return mongoConn, err
}
if !m.HasResponse() {
// we can't respond, so we just fail
if ps.isMetricsEnabled {
hookErr := requestErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment requestErrorsHook %v", hookErr)
}
}
return mongoConn, err
}
if respondErr := ps.RespondWithError(m, err); respondErr != nil {
if ps.isMetricsEnabled {
hookErr := requestErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment requestErrorsHook %v", hookErr)
}
}
return mongoConn, NewStackErrorf("couldn't send error response to client; original error: %v, error sending response: %v", err, respondErr)
}
return mongoConn, nil
}
if m == nil {
// already responded
return mongoConn, nil
}
}
if retryError != nil && retryError.RetryOnRs != "" {
remoteRs = retryError.RetryOnRs
}
if mongoConn == nil || !mongoConn.expirableConn.Alive() {
topology := ps.proxy.topology
if remoteRs != "" {
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "getting remote connection for %s", remoteRs)
rc, ok := ps.proxy.remoteConnections.Load(remoteRs)
if !ok {
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "failed to get a new remote connection to %s as it wasn't initialized", remoteRs)
return nil, NewStackErrorf("failed to get a new remote connection to %s as it wasn't initialized", remoteRs)
}
topology = rc.(*RemoteConnection).topology
}
mongoConn, err = ps.getMongoConnection(rp, topology, pinnedAddress)
if err != nil {
if ps.isMetricsEnabled {
hookErr := requestErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment requestErrorsHook %v", hookErr)
}
}
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "failed to get a new connection. err=%v", err)
return nil, NewStackErrorf("cannot get connection to mongo %v using connection mode=%v readpref=%v remoteRs=%s", err, ps.proxy.Config.ConnectionMode, rp, remoteRs)
}
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "got new connection %v using connection mode=%v readpref=%v remoteRs=%s", mongoConn.conn.ID(), ps.proxy.Config.ConnectionMode, rp, remoteRs)
}
if ps.isMetricsEnabled && isRequestTimerStarted {
requestDurationHook.StopTimer()
}
serverSelectionTime := time.Now().Sub(startServerSelection).Milliseconds()
if ps.proxy.Config.ConnectionMode == util.Cluster {
// only concerned about OP_MSG at this point
if mm, ok := m.(*MessageMessage); ok {
msg, bodysec, err := MessageMessageToBSOND(mm)
if err != nil {
ps.proxy.logger.Logf(slogger.ERROR, "error converting OP_MSG to bson.D. err=%v", err)
return nil, NewStackErrorf("error converting OP_MSG to bson.D. err=%v", err)
}
maxtimeMsIdx := BSONIndexOf(msg, "maxTimeMS")
if maxtimeMsIdx >= 0 {
maxtimeMs := msg[maxtimeMsIdx]
newMaxTime := 0.0
switch val := maxtimeMs.Value.(type) {
case float64:
newMaxTime = val - float64(serverSelectionTime)
case int64:
newMaxTime = float64(val - serverSelectionTime)
case int32:
newMaxTime = float64(val - int32(serverSelectionTime))
case int:
newMaxTime = float64(val - int(serverSelectionTime))
default:
return nil, ps.RespondWithError(m, NewMongoError(fmt.Errorf("unable to parse maxTimeMs value %v and type %T", val, val), 50, "MaxTimeMSExpired"))
}
if newMaxTime < 0 {
return nil, ps.RespondWithError(m, NewMongoError(fmt.Errorf("operation took longer than %v ms", maxtimeMs.Value), 50, "MaxTimeMSExpired"))
}
maxtimeMs.Value = newMaxTime
msg[maxtimeMsIdx] = maxtimeMs
bodysec.Body, err = SimpleBSONConvert(msg)
if err != nil {
return nil, NewStackErrorf("failed to convert message after updating maxTimeMs %v", err)
}
}
}
}
// Send message to mongo
err = mongoConn.conn.WriteWireMessage(ps.proxy.Context, m.Serialize())
if err != nil {
if ps.isMetricsEnabled {
hookErr := requestErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment requestErrorsHook %v", hookErr)
}
}
mongoConn.ep.ProcessError(wrapNetworkError(err), mongoConn.conn)
return mongoConn, NewStackErrorf("error writing to mongo: %v", err)
}
if !m.HasResponse() {
return mongoConn, nil
}
defer mongoConn.Close(ps)
inExhaustMode := m.IsExhaust()
for {
// Read message back from mongo
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "reading data from mongo conn id=%v remoteRs=%s", mongoConn.conn.ID(), remoteRs)
ret, err := mongoConn.conn.ReadWireMessage(ps.proxy.Context, nil)
if err != nil {
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "error reading wire message mongo conn id=%v remoteRs=%s. err=%v", mongoConn.conn.ID(), remoteRs, err)
if ps.isMetricsEnabled {
hookErr := responseErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment responseErrorsHook %v", hookErr)
}
}
mongoConn.ep.ProcessError(wrapNetworkError(err), mongoConn.conn)
return nil, NewStackErrorf("error reading wire message from mongo conn id=%v remoteRs=%s. err=%v", mongoConn.conn.ID(), remoteRs, err)
}
isResponseTimerStarted := false
if ps.isMetricsEnabled {
hookErr := responseDurationHook.StartTimer()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to start reponse duration metric hook timer %v", hookErr)
} else {
isResponseTimerStarted = true
}
}
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "read data from mongo conn %v", mongoConn.conn.ID())
resp, err := ReadMessageFromBytes(ret)
if err != nil {
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "error reading message from bytes on mongo conn id=%v remoteRs=%s. err=%v", mongoConn.conn.ID(), remoteRs, err)
if ps.isMetricsEnabled {
hookErr := responseErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment responseErrorsHook %v", hookErr)
}
}
if err == io.EOF {
return nil, err
}
return nil, NewStackErrorf("got error reading response from mongo %v", err)
}
switch mm := resp.(type) {
case *MessageMessage:
bodyDoc, err := mm.BodyDoc()
if err != nil {
return nil, fmt.Errorf("Error getting body doc: %v", err)
}
if err := extractError(bodyDoc); err != nil {
if ps.isMetricsEnabled {
hookErr := responseErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment responseErrorsHook %v", hookErr)
}
}
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "processing error %v on mongo conn id=%v remoteRs=%s", err, mongoConn.conn.ID(), remoteRs)
mongoConn.ep.ProcessError(err, mongoConn.conn)
}
case *ReplyMessage:
if err := extractError(mm.CommandDoc()); err != nil {
if ps.isMetricsEnabled {
hookErr := responseErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment responseErrorsHook %v", hookErr)
}
}
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "processing error %v on mongo conn id=%v remoteRs=%s", err, mongoConn.conn.ID(), remoteRs)
mongoConn.ep.ProcessError(err, mongoConn.conn)
}
}
if respInter != nil {
resp, err = respInter.InterceptMongoToClient(resp, mongoConn.conn.Address(), remoteRs != "")
if err != nil {
if ps.isMetricsEnabled {
hookErr := responseErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment responseErrorsHook %v", hookErr)
}
}
if pre, ok := err.(*ProxyRetryError); ok {
return nil, pre
}
return nil, NewStackErrorf("error intercepting message %v", err)
}
}
ps.logMessageTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, resp)
if ps.isMetricsEnabled && isResponseTimerStarted {
responseDurationHook.StopTimer()
}
// Send message back to user
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "sending back data to user from mongo conn id=%v remoteRs=%s", mongoConn.conn.ID(), remoteRs)
err = SendMessage(resp, ps.conn)
if err != nil {
if ps.isMetricsEnabled {
hookErr := responseErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment responseErrorsHook %v", hookErr)
}
}
mongoConn.bad = true
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "got error sending response to client from conn id=%v remoteRs=%s. err=%v", mongoConn.conn.ID(), remoteRs, err)
return nil, NewStackErrorf("got error sending response to client from conn %v: %v", mongoConn.conn.ID(), err)
}
ps.logTrace(ps.proxy.logger, ps.proxy.Config.TraceConnPool, "sent back data to user from mongo conn id=%v remoteRs=%s", mongoConn.conn.ID(), remoteRs)
if ps.interceptor != nil {
ps.interceptor.TrackResponse(resp.Header())
}
if !inExhaustMode {
return nil, nil
}
switch r := resp.(type) {
case *ReplyMessage:
if r.CursorId == 0 {
return nil, nil
}
case *MessageMessage:
if !r.HasMoreToCome() {
// moreToCome wasn't set - stop the loop
return nil, nil
}
default:
if ps.isMetricsEnabled {
hookErr := responseErrorsHook.IncCounterGauge()
if hookErr != nil {
ps.proxy.logger.Logf(slogger.WARN, "failed to increment responseErrorsHook %v", hookErr)
}
}
return nil, NewStackErrorf("bad response type from server %T", r)
}
}
}
func (ps *ProxySession) logTrace(logger *slogger.Logger, trace bool, format string, args ...interface{}) {
if trace {
msg := fmt.Sprintf(fmt.Sprintf("client: %v - %s", ps.RemoteAddr(), format), args...)
logger.Logf(slogger.DEBUG, msg)
}
}
func (ps *ProxySession) logMessageTrace(logger *slogger.Logger, trace bool, m Message) {
if trace {
var doc bson.D
var msg string
var err error
switch mm := m.(type) {
case *MessageMessage:
for _, section := range mm.Sections {
if bs, ok := section.(*BodySection); ok {
doc, err = bs.Body.ToBSOND()
if err != nil {
logger.Logf(slogger.WARN, "failed to convert body to Bson.D. err=%v", err)
return
}
break
}
}
msg = fmt.Sprintf("got OP_MSG %v", doc)
case *QueryMessage:
doc, err = mm.Query.ToBSOND()
if err != nil {
logger.Logf(slogger.WARN, "failed to convert query to Bson.D. err=%v", err)
return
}
msg = fmt.Sprintf("got OP_QUERY %v", doc)
case *ReplyMessage:
doc, err = mm.Docs[0].ToBSOND()
if err != nil {
logger.Logf(slogger.WARN, "failed to convert reply doc to Bson.D. err=%v", err)
return
}
msg = fmt.Sprintf("got OP_REPLY %v", doc)
default:
// not bothering about printing other message types
msg = fmt.Sprintf("got another type %T", mm)
}
msg = fmt.Sprintf("client: %v - %s", ps.RemoteAddr(), msg)
logger.Logf(slogger.DEBUG, msg)
}
}
// MongoConnectionWrapper is used to wrap the driver connection so we can explicitly expire (close out) connections on certain occasions that aren't being picked up by the driver
type MongoConnectionWrapper struct {
conn driver.Connection
ep driver.ErrorProcessor
expirableConn driver.Expirable
bad bool
logger *slogger.Logger
trace bool
}
func (m *MongoConnectionWrapper) Close(ps *ProxySession) {
if m.conn == nil {
m.logger.Logf(slogger.WARN, "attempt to close a nil mongo connection. noop")
return
}
id := m.conn.ID()
if m.bad {
if m.expirableConn.Alive() {
ps.logTrace(m.logger, m.trace, "closing underlying bad mongo connection %v", id)
if err := m.expirableConn.Expire(); err != nil {
ps.logTrace(m.logger, m.trace, "failed to expire connection. %v", err)
}
} else {
ps.logTrace(m.logger, m.trace, "bad mongo connection is nil!")
}
}
ps.logTrace(m.logger, m.trace, "closing mongo connection %v", id)
if m.expirableConn.Alive() {
if err := m.conn.Close(); err != nil {
ps.logTrace(m.logger, m.trace, "failed to close mongo connection %v: %v", id, err)
}
}
}