-
Notifications
You must be signed in to change notification settings - Fork 1
/
gtm.go
1267 lines (1168 loc) · 28.8 KB
/
gtm.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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package gtm
import (
"fmt"
"log"
"math"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/pkg/errors"
"github.com/serialx/hashring"
)
type OrderingGuarantee int
const (
Oplog OrderingGuarantee = iota // ops sent in oplog order (strong ordering)
Namespace // ops sent in oplog order within a namespace
Document // ops sent in oplog order for a single document
)
type QuerySource int
const (
OplogQuerySource QuerySource = iota
DirectQuerySource
)
type Options struct {
After TimestampGenerator
Filter OpFilter
NamespaceFilter OpFilter
OpLogDatabaseName *string
OpLogCollectionName *string
CursorTimeout *string
ChannelSize int
BufferSize int
BufferDuration time.Duration
EOFDuration time.Duration
Ordering OrderingGuarantee
WorkerCount int
UpdateDataAsDelta bool
DirectReadNs []string
DirectReadFilter OpFilter
DirectReadBatchSize int
DirectReadCursors int
Unmarshal DataUnmarshaller
Log *log.Logger
MaxBackoffTime time.Duration
IncludeMigrate bool // should internal `fromMigrate` oplog entries be counted
}
type Op struct {
Id interface{} `json:"_id"`
Operation string `json:"operation"`
Namespace string `json:"namespace"`
Data map[string]interface{} `json:"data,omitempty"`
Timestamp bson.MongoTimestamp `json:"timestamp"`
Source QuerySource `json:"source"`
Doc interface{} `json:"doc,omitempty"`
DataSize int `json:"data_size"`
}
type OpLog struct {
Timestamp bson.MongoTimestamp "ts"
HistoryID int64 "h"
MongoVersion int "v"
Operation string "op"
Namespace string "ns"
Doc *bson.Raw "o"
Update *bson.Raw "o2"
}
type CursorInfo struct {
Firstbatch []bson.Raw "firstBatch"
Namespace string "ns"
Id int64 "id"
}
type Cursor struct {
Info CursorInfo "cursor"
Ok bool "ok"
}
type PCollectionScanResult struct {
Cursors []Cursor "cursors"
Ok int "ok"
}
type PCollectionScan struct {
Namespace string "parallelCollectionScan"
Numcursors int "numCursors"
}
type Doc struct {
Id interface{} "_id"
}
type OpChan chan *Op
type OpLogEntry map[string]interface{}
type OpFilter func(*Op) bool
type ShardInsertHandler func(*ShardInfo) (*mgo.Session, error)
type TimestampGenerator func(*mgo.Session, *Options) bson.MongoTimestamp
type DataUnmarshaller func(namespace string, raw *bson.Raw) (interface{}, error)
type OpBuf struct {
Entries []*Op
BufferSize int
BufferDuration time.Duration
FlushTicker *time.Ticker
}
type OpCtx struct {
lock *sync.Mutex
OpC OpChan
ErrC chan error
DirectReadWg *sync.WaitGroup
stopC chan bool
allWg *sync.WaitGroup
seekC chan bson.MongoTimestamp
pauseC chan bool
resumeC chan bool
paused bool
stopped bool
log *log.Logger
}
type OpCtxMulti struct {
lock *sync.Mutex
contexts []*OpCtx
OpC OpChan
ErrC chan error
DirectReadWg *sync.WaitGroup
stopC chan bool
allWg *sync.WaitGroup
seekC chan bson.MongoTimestamp
pauseC chan bool
resumeC chan bool
paused bool
stopped bool
log *log.Logger
}
type ShardInfo struct {
hostname string
}
type BuildInfo struct {
version []int
major int
minor int
patch int
}
type N struct {
database string
collection string
}
func (b *BuildInfo) build() {
parts := len(b.version)
if parts > 0 {
b.major = b.version[0]
}
if parts > 1 {
b.minor = b.version[1]
}
if parts > 2 {
b.patch = b.version[2]
}
}
func (n *N) parse(ns string) (err error) {
parts := strings.SplitN(ns, ".", 2)
if len(parts) != 2 {
err = fmt.Errorf("Invalid ns: %s :expecting db.collection", ns)
} else {
n.database = parts[0]
n.collection = parts[1]
}
return
}
func (shard *ShardInfo) GetURL() string {
hostParts := strings.SplitN(shard.hostname, "/", 2)
if len(hostParts) == 2 {
return hostParts[1] + "?replicaSet=" + hostParts[0]
} else {
return hostParts[0]
}
}
func (ctx *OpCtx) waitForConnection(wg *sync.WaitGroup, session *mgo.Session, options *Options) {
defer wg.Done()
t := time.NewTicker(5 * time.Second)
defer t.Stop()
for {
select {
case <-ctx.stopC:
return
case <-t.C:
s := session.Copy()
if err := s.Ping(); err == nil {
s.Close()
return
}
s.Close()
}
}
}
func (ctx *OpCtx) isStopped() bool {
ctx.lock.Lock()
defer ctx.lock.Unlock()
return ctx.stopped
}
func (ctx *OpCtx) Since(ts bson.MongoTimestamp) {
ctx.lock.Lock()
defer ctx.lock.Unlock()
ctx.seekC <- ts
}
func (ctx *OpCtx) Pause() {
ctx.lock.Lock()
defer ctx.lock.Unlock()
if !ctx.paused {
ctx.paused = true
ctx.pauseC <- true
}
}
func (ctx *OpCtx) Resume() {
ctx.lock.Lock()
defer ctx.lock.Unlock()
if ctx.paused {
ctx.paused = false
ctx.resumeC <- true
}
}
func (ctx *OpCtx) Stop() {
ctx.lock.Lock()
defer ctx.lock.Unlock()
if !ctx.stopped {
ctx.stopped = true
close(ctx.stopC)
ctx.allWg.Wait()
}
}
func (ctx *OpCtxMulti) Since(ts bson.MongoTimestamp) {
ctx.lock.Lock()
defer ctx.lock.Unlock()
for _, child := range ctx.contexts {
child.Since(ts)
}
}
func (ctx *OpCtxMulti) Pause() {
ctx.lock.Lock()
defer ctx.lock.Unlock()
if !ctx.paused {
ctx.paused = true
ctx.pauseC <- true
for _, child := range ctx.contexts {
child.Pause()
}
}
}
func (ctx *OpCtxMulti) Resume() {
ctx.lock.Lock()
defer ctx.lock.Unlock()
if ctx.paused {
ctx.paused = false
ctx.resumeC <- true
for _, child := range ctx.contexts {
child.Resume()
}
}
}
func (ctx *OpCtxMulti) Stop() {
ctx.lock.Lock()
defer ctx.lock.Unlock()
if !ctx.stopped {
ctx.stopped = true
close(ctx.stopC)
for _, child := range ctx.contexts {
go child.Stop()
}
ctx.allWg.Wait()
}
}
func tailShards(multi *OpCtxMulti, ctx *OpCtx, options *Options, handler ShardInsertHandler) {
defer multi.allWg.Done()
if options == nil {
options = DefaultOptions()
} else {
options.SetDefaults()
}
for {
select {
case <-multi.stopC:
return
case <-multi.pauseC:
<-multi.resumeC
select {
case <-multi.stopC:
return
}
case err := <-ctx.ErrC:
multi.ErrC <- err
case op := <-ctx.OpC:
// new shard detected
shardInfo := &ShardInfo{
hostname: op.Data["host"].(string),
}
shardSession, err := handler(shardInfo)
if err != nil {
multi.ErrC <- errors.Wrap(err, "Error calling shard handler")
continue
}
shardCtx := Start(shardSession, options)
multi.lock.Lock()
multi.contexts = append(multi.contexts, shardCtx)
multi.DirectReadWg.Add(1)
go func() {
defer multi.DirectReadWg.Done()
shardCtx.DirectReadWg.Wait()
}()
multi.allWg.Add(1)
go func() {
defer multi.allWg.Done()
shardCtx.allWg.Wait()
}()
go func(c OpChan) {
for op := range c {
multi.OpC <- op
}
}(shardCtx.OpC)
go func(c chan error) {
for err := range c {
multi.ErrC <- err
}
}(shardCtx.ErrC)
multi.lock.Unlock()
}
}
}
func (ctx *OpCtxMulti) AddShardListener(
configSession *mgo.Session, shardOptions *Options, handler ShardInsertHandler) {
opts := DefaultOptions()
opts.NamespaceFilter = func(op *Op) bool {
return op.Namespace == "config.shards" && op.IsInsert()
}
configCtx := Start(configSession, opts)
ctx.allWg.Add(1)
go tailShards(ctx, configCtx, shardOptions, handler)
}
func ChainOpFilters(filters ...OpFilter) OpFilter {
return func(op *Op) bool {
for _, filter := range filters {
if filter(op) == false {
return false
}
}
return true
}
}
func (this *Op) IsDrop() bool {
if _, drop := this.IsDropDatabase(); drop {
return true
}
if _, drop := this.IsDropCollection(); drop {
return true
}
return false
}
func (this *Op) IsDropCollection() (string, bool) {
if this.IsCommand() {
if this.Data != nil {
if val, ok := this.Data["drop"]; ok {
return val.(string), true
}
}
}
return "", false
}
func (this *Op) IsDropDatabase() (string, bool) {
if this.IsCommand() {
if this.Data != nil {
if _, ok := this.Data["dropDatabase"]; ok {
return this.GetDatabase(), true
}
}
}
return "", false
}
func (this *Op) IsCommand() bool {
return this.Operation == "c"
}
func (this *Op) IsInsert() bool {
return this.Operation == "i"
}
func (this *Op) IsUpdate() bool {
return this.Operation == "u"
}
func (this *Op) IsDelete() bool {
return this.Operation == "d"
}
func (this *Op) IsSourceOplog() bool {
return this.Source == OplogQuerySource
}
func (this *Op) IsSourceDirect() bool {
return this.Source == DirectQuerySource
}
func (this *Op) ParseNamespace() []string {
return strings.SplitN(this.Namespace, ".", 2)
}
func (this *Op) GetDatabase() string {
return this.ParseNamespace()[0]
}
func (this *Op) GetCollection() string {
if _, drop := this.IsDropDatabase(); drop {
return ""
} else if col, drop := this.IsDropCollection(); drop {
return col
} else {
return this.ParseNamespace()[1]
}
}
func (this *OpBuf) Append(op *Op) {
this.Entries = append(this.Entries, op)
}
func (this *OpBuf) IsFull() bool {
return len(this.Entries) >= this.BufferSize
}
func (this *OpBuf) Flush(session *mgo.Session, ctx *OpCtx, options *Options) {
if len(this.Entries) == 0 {
return
}
ns := make(map[string][]interface{})
byId := make(map[interface{}][]*Op)
for _, op := range this.Entries {
if op.IsUpdate() && op.Doc == nil {
idKey := fmt.Sprintf("%s.%v", op.Namespace, op.Id)
ns[op.Namespace] = append(ns[op.Namespace], op.Id)
byId[idKey] = append(byId[idKey], op)
}
}
Retry:
for n, opIds := range ns {
var parts = strings.SplitN(n, ".", 2)
var results []*bson.Raw
db, col := parts[0], parts[1]
sel := bson.M{"_id": bson.M{"$in": opIds}}
collection := session.DB(db).C(col)
err := collection.Find(sel).All(&results)
if err == nil {
for _, result := range results {
var doc Doc
result.Unmarshal(&doc)
resultId := fmt.Sprintf("%s.%v", n, doc.Id)
if ops, ok := byId[resultId]; ok {
for _, o := range ops {
if u, err := options.Unmarshal(o.Namespace, result); err == nil {
o.processData(u)
} else {
ctx.ErrC <- err
}
}
}
}
} else {
ctx.ErrC <- errors.Wrap(err, "Error finding documents to associate with ops")
var wg sync.WaitGroup
wg.Add(1)
go ctx.waitForConnection(&wg, session, options)
wg.Wait()
if ctx.isStopped() {
this.Entries = nil
return
}
session.Refresh()
break Retry
}
}
for _, op := range this.Entries {
if op.matchesFilter(options) {
ctx.OpC <- op
}
}
this.Entries = nil
}
func UpdateIsReplace(entry map[string]interface{}) bool {
if _, ok := entry["$set"]; ok {
return false
} else if _, ok := entry["$unset"]; ok {
return false
} else {
return true
}
}
func (this *Op) shouldParse() bool {
return this.IsInsert() || this.IsDelete() || this.IsUpdate() || this.IsCommand()
}
func (this *Op) matchesNsFilter(options *Options) bool {
return options.NamespaceFilter == nil || options.NamespaceFilter(this)
}
func (this *Op) matchesFilter(options *Options) bool {
return options.Filter == nil || options.Filter(this)
}
func (this *Op) matchesDirectFilter(options *Options) bool {
return options.DirectReadFilter == nil || options.DirectReadFilter(this)
}
func (this *Op) processData(data interface{}) {
if data != nil {
this.Doc = data
if m, ok := data.(map[string]interface{}); ok {
this.Data = m
}
}
}
func (this *Op) ParseLogEntry(entry *OpLog, options *Options) (include bool, err error) {
var rawField *bson.Raw
var u interface{}
this.Operation = entry.Operation
this.Timestamp = entry.Timestamp
this.Namespace = entry.Namespace
if this.shouldParse() {
if this.IsCommand() {
var objectField map[string]interface{}
rawField = entry.Doc
err = rawField.Unmarshal(&objectField)
this.processData(objectField)
}
if this.matchesNsFilter(options) {
if this.IsInsert() || this.IsDelete() || this.IsUpdate() {
if this.IsUpdate() {
rawField = entry.Update
} else {
rawField = entry.Doc
}
var doc Doc
rawField.Unmarshal(&doc)
this.Id = doc.Id
if this.IsInsert() {
if u, err = options.Unmarshal(this.Namespace, rawField); err == nil {
this.processData(u)
}
} else if this.IsUpdate() {
var changeField map[string]interface{}
rawField = entry.Doc
rawField.Unmarshal(&changeField)
if options.UpdateDataAsDelta || UpdateIsReplace(changeField) {
if u, err = options.Unmarshal(this.Namespace, rawField); err == nil {
this.processData(u)
}
}
}
include = true
} else if this.IsCommand() {
include = this.IsDrop()
}
}
}
return
}
func OpLogCollectionName(session *mgo.Session, options *Options) string {
localDB := session.DB(*options.OpLogDatabaseName)
col_names, err := localDB.CollectionNames()
if err == nil {
var col_name *string = nil
for _, name := range col_names {
if strings.HasPrefix(name, "oplog.") {
col_name = &name
break
}
}
if col_name == nil {
msg := fmt.Sprintf(`
Unable to find oplog collection
in database %v`, *options.OpLogDatabaseName)
panic(msg)
} else {
return *col_name
}
} else {
msg := fmt.Sprintf(`Unable to get collection names
for database %v: %s`, *options.OpLogDatabaseName, err)
panic(msg)
}
}
func OpLogCollection(session *mgo.Session, options *Options) *mgo.Collection {
localDB := session.DB(*options.OpLogDatabaseName)
return localDB.C(*options.OpLogCollectionName)
}
func ParseTimestamp(timestamp bson.MongoTimestamp) (int32, int32) {
ordinal := (timestamp << 32) >> 32
ts := (timestamp >> 32)
return int32(ts), int32(ordinal)
}
func LastOpTimestamp(session *mgo.Session, options *Options) bson.MongoTimestamp {
var opLog OpLog
collection := OpLogCollection(session, options)
collection.Find(nil).Sort("-$natural").One(&opLog)
return opLog.Timestamp
}
func GetOpLogQuery(session *mgo.Session, after bson.MongoTimestamp, options *Options) *mgo.Query {
var query bson.M
if options.IncludeMigrate {
query = bson.M{"ts": bson.M{"$gt": after}}
} else {
query = bson.M{"ts": bson.M{"$gt": after}, "fromMigrate": bson.M{"$exists": false}}
}
collection := OpLogCollection(session, options)
return collection.Find(query).LogReplay().Sort("$natural")
}
func TailOps(ctx *OpCtx, session *mgo.Session, channels []OpChan, options *Options) error {
defer ctx.allWg.Done()
s := session.Copy()
defer s.Close()
options.Fill(s)
duration, err := time.ParseDuration(*options.CursorTimeout)
if err != nil {
panic(fmt.Sprintf("Invalid value <%s> for CursorTimeout", *options.CursorTimeout))
}
currTimestamp := options.After(s, options)
iter := GetOpLogQuery(s, currTimestamp, options).Tail(duration)
numConsecutiveErrors := 0
for {
var rawBson bson.Raw
var entry OpLog
Seek:
for iter.Next(&rawBson) {
op := &Op{
Id: "",
Operation: "",
Namespace: "",
Data: nil,
Timestamp: bson.MongoTimestamp(0),
Source: OplogQuerySource,
DataSize: len(rawBson.Data),
}
if err := rawBson.Unmarshal(&entry); err == nil {
if ok, err := op.ParseLogEntry(&entry, options); err == nil {
if ok && op.matchesFilter(options) {
if options.UpdateDataAsDelta {
ctx.OpC <- op
} else {
// broadcast to fetch channels
for _, channel := range channels {
channel <- op
}
}
}
numConsecutiveErrors = 0
} else {
ctx.ErrC <- err
numConsecutiveErrors += 1
}
} else {
ctx.ErrC <- err
numConsecutiveErrors += 1
}
select {
case <-ctx.stopC:
return nil
case ts := <-ctx.seekC:
currTimestamp = ts
break Seek
case <-ctx.pauseC:
<-ctx.resumeC
select {
case <-ctx.stopC:
return nil
case ts := <-ctx.seekC:
currTimestamp = ts
break Seek
default:
currTimestamp = op.Timestamp
}
default:
currTimestamp = op.Timestamp
}
if numConsecutiveErrors > 0 {
if sleepTime := time.Duration(int(math.Pow(float64(2), float64(numConsecutiveErrors)))) * time.Millisecond; sleepTime > options.MaxBackoffTime {
time.Sleep(options.MaxBackoffTime)
} else {
time.Sleep(sleepTime)
}
}
}
if err = iter.Close(); err != nil {
ctx.ErrC <- errors.Wrap(err, "Error tailing oplog entries")
numConsecutiveErrors += 1
var wg sync.WaitGroup
wg.Add(1)
go ctx.waitForConnection(&wg, s, options)
wg.Wait()
if ctx.isStopped() {
return nil
}
s.Refresh()
iter = GetOpLogQuery(s, currTimestamp, options).Tail(duration)
continue
}
if iter.Timeout() {
select {
case <-ctx.stopC:
return nil
case ts := <-ctx.seekC:
currTimestamp = ts
case <-ctx.pauseC:
<-ctx.resumeC
select {
case ts := <-ctx.seekC:
currTimestamp = ts
default:
continue
}
default:
continue
}
}
iter = GetOpLogQuery(s, currTimestamp, options).Tail(duration)
}
return nil
}
func SupportsCollectionScan(session *mgo.Session) (supports bool, err error) {
var buildInfo *BuildInfo
if buildInfo, err = VersionInfo(session); err == nil {
if buildInfo.major > 2 {
supports = true
} else if buildInfo.major == 2 && buildInfo.minor >= 6 {
supports = true
}
}
return
}
func DirectReadCollectionScan(ctx *OpCtx, session *mgo.Session, ns string, options *Options) (err error) {
defer ctx.allWg.Done()
defer ctx.DirectReadWg.Done()
n := &N{}
if err = n.parse(ns); err != nil {
ctx.ErrC <- errors.Wrap(err, "Error parsing direct read namespace")
return
}
scan := PCollectionScan{
Namespace: n.collection,
Numcursors: options.DirectReadCursors,
}
var result PCollectionScanResult
s := session.Copy()
err = s.DB(n.database).Run(scan, &result)
if err != nil || result.Ok == 0 {
defer s.Close()
msg := fmt.Sprintf("Parallel collection scan of %s failed", ns)
ctx.ErrC <- errors.Wrap(err, msg)
ctx.log.Println("Reverting to single-threaded collection read")
ctx.allWg.Add(1)
ctx.DirectReadWg.Add(1)
go DirectRead(ctx, session, ns, options)
return
}
if len(result.Cursors) > 1 {
for _, cursor := range result.Cursors {
ctx.allWg.Add(1)
ctx.DirectReadWg.Add(1)
go DirectReadCursor(ctx, s, ns, options, cursor.Info)
}
} else {
defer s.Close()
if scan.Numcursors > 1 {
ctx.log.Println("Only 1 cursor available for collection scan in this storage engine")
}
ctx.log.Println("Reverting to single-threaded collection read")
ctx.allWg.Add(1)
ctx.DirectReadWg.Add(1)
go DirectRead(ctx, session, ns, options)
}
return
}
func DirectReadCursor(ctx *OpCtx, s *mgo.Session, ns string, options *Options, cursor CursorInfo) (err error) {
defer ctx.allWg.Done()
defer ctx.DirectReadWg.Done()
n := &N{}
if err = n.parse(ns); err != nil {
ctx.ErrC <- errors.Wrap(err, "Error parsing direct read namespace")
return
}
c := s.DB(n.database).C(n.collection)
iter := c.NewIter(nil, cursor.Firstbatch, cursor.Id, nil)
for {
foundResults := false
var result = &bson.Raw{}
for iter.Next(result) {
foundResults = true
t := time.Now().UTC().Unix()
var doc Doc
result.Unmarshal(&doc)
op := &Op{
Id: doc.Id,
Operation: "i",
Namespace: ns,
Source: DirectQuerySource,
Timestamp: bson.MongoTimestamp(t << 32),
}
if u, err := options.Unmarshal(ns, result); err == nil {
op.processData(u)
if op.matchesDirectFilter(options) {
ctx.OpC <- op
}
} else {
ctx.ErrC <- err
}
result = &bson.Raw{}
select {
case <-ctx.stopC:
return
default:
continue
}
}
if err = iter.Close(); err != nil {
ctx.ErrC <- errors.Wrap(err, "Error performing direct reads of collections")
var wg sync.WaitGroup
wg.Add(1)
go ctx.waitForConnection(&wg, s, options)
wg.Wait()
if ctx.isStopped() {
return
}
s.Refresh()
continue
} else if !foundResults {
break
}
}
return
}
func DirectRead(ctx *OpCtx, session *mgo.Session, ns string, options *Options) (err error) {
defer ctx.allWg.Done()
defer ctx.DirectReadWg.Done()
s := session.Copy()
defer s.Close()
n := &N{}
if err = n.parse(ns); err != nil {
ctx.ErrC <- errors.Wrap(err, "Error parsing direct read namespace")
return
}
c := s.DB(n.database).C(n.collection)
var sel bson.M = nil
for {
foundResults := false
q := c.Find(sel).Sort("_id").Hint("_id").Batch(options.DirectReadBatchSize)
iter := q.Iter()
var result = &bson.Raw{}
for iter.Next(result) {
foundResults = true
var doc Doc
result.Unmarshal(&doc)
sel = bson.M{"_id": bson.M{"$gt": doc.Id}}
t := time.Now().UTC().Unix()
op := &Op{
Id: doc.Id,
Operation: "i",
Namespace: ns,
Source: DirectQuerySource,
Timestamp: bson.MongoTimestamp(t << 32),
}
if u, err := options.Unmarshal(ns, result); err == nil {
op.processData(u)
if op.matchesDirectFilter(options) {
ctx.OpC <- op
}
} else {
ctx.ErrC <- err
}
result = &bson.Raw{}
select {
case <-ctx.stopC:
return
default:
continue
}
}
if err = iter.Close(); err != nil {
ctx.ErrC <- errors.Wrap(err, "Error performing direct reads of collections")
var wg sync.WaitGroup
wg.Add(1)
go ctx.waitForConnection(&wg, s, options)
wg.Wait()
if ctx.isStopped() {
return
}
s.Refresh()
continue
} else if !foundResults {
break
}
}
return
}
func FetchDocuments(ctx *OpCtx, session *mgo.Session, filter OpFilter, buf *OpBuf, inOp OpChan, options *Options) error {
defer ctx.allWg.Done()
s := session.Copy()
defer s.Close()
for {
select {
case <-ctx.stopC:
return nil
case <-buf.FlushTicker.C:
buf.Flush(s, ctx, options)
case op := <-inOp:
if filter(op) {
buf.Append(op)
if buf.IsFull() {
buf.Flush(s, ctx, options)
buf.FlushTicker.Stop()
buf.FlushTicker = time.NewTicker(buf.BufferDuration)
}
}
}
}
return nil
}
func OpFilterForOrdering(ordering OrderingGuarantee, workers []string, worker string) OpFilter {
switch ordering {
case Document:
ring := hashring.New(workers)
return func(op *Op) bool {
var key string
if op.Id != nil {
key = fmt.Sprintf("%v", op.Id)
} else {
key = op.Namespace
}
if who, ok := ring.GetNode(key); ok {
return who == worker
} else {
return false
}
}
case Namespace:
ring := hashring.New(workers)
return func(op *Op) bool {
if who, ok := ring.GetNode(op.Namespace); ok {
return who == worker
} else {
return false