-
Notifications
You must be signed in to change notification settings - Fork 6
/
route81.go
1617 lines (1510 loc) · 40.3 KB
/
route81.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 main
import (
"context"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"reflect"
"strings"
"sync"
"syscall"
"time"
"github.com/BurntSushi/toml"
"github.com/PaesslerAG/gval"
"github.com/confluentinc/confluent-kafka-go/kafka"
"github.com/rwynn/gtm"
"github.com/rwynn/route81/decoding"
"github.com/rwynn/route81/encoding"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsontype"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
const (
version = "1.2.0"
)
var supportedConsumerFormats = []string{"json-ext", "json", "avro"}
var (
infoLog = log.New(os.Stderr, "INFO ", log.Flags())
warnLog = log.New(os.Stdout, "WARN ", log.Flags())
statsLog = log.New(os.Stdout, "STATS ", log.Flags())
traceLog = log.New(os.Stdout, "TRACE ", log.Flags())
errorLog = log.New(os.Stderr, "ERROR ", log.Flags())
)
type stringargs []string
type producerError struct {
err error
op *gtm.Op
}
type kafkaMeta struct {
ID interface{} `bson:"_id,omitempty" json:"_id,omitempty"`
Timestamp primitive.Timestamp `bson:"ts" json:"ts"`
Namespace string `bson:"ns" json:"ns"`
Operation string `bson:"op,omitempty" json:"op,omitempty"`
Updates map[string]interface{} `bson:"updates,omitempty" json:"updates,omitempty"`
}
type kafkaMessage struct {
Meta kafkaMeta `bson:"meta" json:"meta"`
Data map[string]interface{} `bson:"data,omitempty" json:"data,omitempty"`
}
type kafkaMessageMeta struct {
Meta kafkaMeta `json:"meta"`
}
type kafkaSettings struct {
EnableIdempotence bool `toml:"enable-idempotence" json:"enable-idempotence"`
RequestTimeoutMs int `toml:"request-timeout-ms" json:"request-timeout-ms"`
MessageTimeoutMs int `toml:"message-timeout-ms" json:"message-timeout-ms"`
MessageMaxRetries int `toml:"message-max-retries" json:"message-max-retries"`
RetryBackoffMs int `toml:"retry-backoff-ms" json:"retry-backoff-ms"`
SecurityProto string `toml:"security-protocol" json:"security-protocol"`
SSLCAFile string `toml:"ssl-ca-location" json:"ssl-ca-location"`
SSLCertFile string `toml:"ssl-certificate-location" json:"ssl-certificate-location"`
SSLKeyFile string `toml:"ssl-key-location" json:"ssl-key-location"`
SSLKeyPass string `toml:"ssl-key-password" json:"ssl-key-password"`
BrokerVersionFallback string `toml:"broker-version-fallback" json:"broker-version-fallback"`
APIVersionFallback bool `toml:"api-version-fallback" json:"api-version-fallback"`
APIVersionFallbackMs int `toml:"api-version-fallback-ms" json:"api-version-fallback-ms"`
SASLMechanisms string `toml:"sasl-mechanisms" json:"sasl-mechanisms"`
SASLUser string `toml:"sasl-username" json:"sasl-username"`
SASLPass string `toml:"sasl-password" json:"sasl-password"`
}
type pipeline struct {
Namespace string `toml:"namespace" json:"namespace"`
Direct bool `toml:"direct" json:"direct"`
Stages string `toml:"stages" json:"stages"`
stagesVal []interface{}
}
type consumer struct {
GroupID string `toml:"group-id" json:"group-id"`
Namespace string `toml:"namespace" json:"namespace"`
Topics []string `toml:"topics" json:"topics"`
Format string `toml:"message-format" json:"message-format"`
BulkSize int `toml:"bulk-size" json:"bulk-size"`
BulkFlushDuration string `toml:"bulk-flush-duration" json:"bulk-flush-duration"`
Workers int `toml:"workers" json:"workers"`
AvroSchemaSpec string `toml:"avro-schema-spec" json:"avro-schema-spec"`
AvroBinary bool `toml:"avro-binary" json:"avro-binary"`
DocRootPath string `toml:"document-root-path" json:"document-root-path"`
DeleteIDPath string `toml:"delete-id-path" json:"delete-id-path"`
rootEval gval.Evaluable
deleteEval gval.Evaluable
}
type producerMap struct {
MongoNamespace string `toml:"mongo-namespace" json:"mongo-namespace"`
KafkaTopicName string `toml:"kafka-topic" json:"kafka-topic"`
}
type config struct {
ConfigFile string `json:"config-file"`
MongoURI string `toml:"mongo" json:"mongo"`
KafkaServers string `toml:"kafka" json:"kafka"`
TopicPrefix string `toml:"topic-name-prefix" json:"topic-name-prefix"`
StatsDuration string `toml:"stats-duration" json:"stats-duration"`
ChangeStreamNs stringargs `toml:"change-stream-namespaces" json:"change-stream-namespaces"`
DirectReadNs stringargs `toml:"direct-read-namespaces" json:"direct-read-namespaces"`
DirectReadSplitMax int `toml:"direct-read-split-max" json:"direct-read-split-max"`
DirectReadConcur int `toml:"direct-read-concur" json:"direct-read-concur"`
DisableChangeStream bool `toml:"disable-change-stream" json:"disable-change-stream"`
FailFast bool `toml:"fail-fast" json:"fail-fast"`
ExitAfterDirectReads bool `toml:"exit-after-direct-reads" json:"exit-after-direct-reads"`
DisableStats bool `toml:"disable-stats" json:"disable-stats"`
DisableStatsLog bool `toml:"disable-stats-log" json:"disable-stats-log"`
Resume bool `toml:"resume" json:"resume"`
ResumeName string `toml:"resume-name" json:"resume-name"`
MetadataDB string `toml:"metadata-db" json:"metadata-db"`
KafkaSettings kafkaSettings `toml:"kafka-settings" json:"kafka-settings"`
EnableHTTPServer bool `toml:"http-server" json:"http-server"`
HTTPServerAddr string `toml:"http-server-addr" json:"http-server-addr"`
Pprof bool `toml:"pprof" json:"pprof"`
Pipelines []pipeline `toml:"pipeline" json:"pipelines"`
Consumers []consumer `toml:"consumer" json:"consumers"`
pipe map[string][]pipeline
viewConfig bool
ProducerMaps []producerMap `toml:"producer-map" json:"producer-maps"`
}
func (pe *producerError) Error() string {
op := pe.op
var sb strings.Builder
sb.WriteString(pe.err.Error())
if op != nil {
sb.WriteString(": Document ID (")
sb.WriteString(toDocID(op, true))
sb.WriteString(") Operation (")
sb.WriteString(op.Operation)
sb.WriteString(")")
}
return sb.String()
}
func (c *config) nsFilter() gtm.OpFilter {
db := c.MetadataDB
cons := c.Consumers
return func(op *gtm.Op) bool {
if op.GetDatabase() == db {
return false
}
if len(cons) > 0 {
for _, c := range cons {
if op.Namespace == c.Namespace {
return false
}
}
}
return true
}
}
func (c *config) makePipe() gtm.PipelineBuilder {
if len(c.pipe) == 0 {
return nil
}
return func(ns string, stream bool) ([]interface{}, error) {
lines := c.pipe[ns]
if lines == nil {
return nil, nil
}
for _, line := range lines {
if stream == !line.Direct {
return line.stagesVal, nil
}
}
return nil, nil
}
}
func (c *config) resumeFunc() gtm.TimestampGenerator {
if !c.Resume {
return nil
}
return func(client *mongo.Client, opts *gtm.Options) (primitive.Timestamp, error) {
var ts primitive.Timestamp
col := client.Database(c.MetadataDB).Collection("resume")
result := col.FindOne(context.Background(), bson.M{
"_id": c.ResumeName,
})
if err := result.Err(); err == nil {
doc := make(map[string]interface{})
if err = result.Decode(&doc); err == nil {
if doc["ts"] != nil {
ts = doc["ts"].(primitive.Timestamp)
ts.I++
}
}
}
if ts.T == 0 {
ts, _ = gtm.LastOpTimestamp(client, opts)
}
infoLog.Printf("Resuming from timestamp %+v", ts)
return ts, nil
}
}
func (c *config) hasFlag(name string) bool {
passed := false
flag.Visit(func(f *flag.Flag) {
if f.Name == name {
passed = true
}
})
return passed
}
func (c *config) log(out io.Writer) {
if b, err := json.MarshalIndent(c, "", " "); err == nil {
out.Write(b)
out.Write([]byte("\n"))
}
}
func (c *config) setDefaults() *config {
if c.DisableChangeStream {
c.ChangeStreamNs = []string{}
} else if len(c.ChangeStreamNs) == 0 {
c.ChangeStreamNs = []string{""}
}
return c
}
func (c *config) validate() error {
if c.StatsDuration != "" {
if _, err := time.ParseDuration(c.StatsDuration); err != nil {
return fmt.Errorf("Invalid StatsDuration: %s", err)
}
} else {
return fmt.Errorf("StatsDuration cannot be empty")
}
for _, pm := range c.ProducerMaps {
if pm.KafkaTopicName == "" {
return fmt.Errorf("kafka-topic cannot be empty in a producer-map")
}
}
return nil
}
func (c *config) loadPipelines(fc *config) {
if len(fc.Pipelines) > 0 {
c.Pipelines = fc.Pipelines
c.pipe = make(map[string][]pipeline)
for _, p := range fc.Pipelines {
err := json.Unmarshal([]byte(p.Stages), &p.stagesVal)
if err != nil {
errorLog.Fatalf("Configuration failed: invalid pipeline stages: %s: %s",
p.Stages, err)
}
pipes := c.pipe[p.Namespace]
c.pipe[p.Namespace] = append(pipes, p)
}
}
}
func (c *config) loadConsumers(fc *config) {
var err error
if len(fc.Consumers) > 0 {
for _, con := range fc.Consumers {
if con.GroupID == "" {
con.GroupID = "route81"
}
if con.Format == "" {
con.Format = supportedConsumerFormats[0]
} else {
supportedFormat := false
for _, fmt := range supportedConsumerFormats {
if con.Format == fmt {
supportedFormat = true
break
}
}
if !supportedFormat {
errorLog.Fatalf("Configuration failed: unsupported consumer format: %s",
con.Format)
}
}
if con.Format == "avro" && con.AvroSchemaSpec == "" {
errorLog.Fatalln("Configuration failed: avro-schema-spec is required for the avro format")
}
if con.BulkSize == 0 {
con.BulkSize = 100
}
if con.BulkFlushDuration == "" {
con.BulkFlushDuration = "5s"
}
if con.Workers == 0 {
con.Workers = 4
}
ns := strings.SplitN(con.Namespace, ".", 2)
if len(ns) != 2 {
errorLog.Fatalf("Configuration failed: invalid consumer namespace: %s",
con.Namespace)
}
if con.DocRootPath != "" {
con.rootEval, err = gval.Full().NewEvaluable(con.DocRootPath)
if err != nil {
errorLog.Fatalf("Configuration failed: invalid doc root path: %s: %s",
con.DocRootPath, err)
}
}
if con.DeleteIDPath != "" {
con.deleteEval, err = gval.Full().NewEvaluable(con.DeleteIDPath)
if err != nil {
errorLog.Fatalf("Configuration failed: invalid delete ID path: %s: %s",
con.DeleteIDPath, err)
}
}
c.Consumers = append(c.Consumers, con)
}
}
}
func (c *config) override(fc *config) {
if !c.hasFlag("mongo") && fc.MongoURI != "" {
c.MongoURI = fc.MongoURI
}
if !c.hasFlag("kakfa") && fc.KafkaServers != "" {
c.KafkaServers = fc.KafkaServers
}
if fc.Pprof {
c.Pprof = true
}
if fc.EnableHTTPServer {
c.EnableHTTPServer = true
}
if !c.hasFlag("http-server-addr") && fc.HTTPServerAddr != "" {
c.HTTPServerAddr = fc.HTTPServerAddr
}
if !c.hasFlag("topic-name-prefix") && fc.TopicPrefix != "" {
c.TopicPrefix = fc.TopicPrefix
}
if fc.DisableChangeStream {
c.DisableChangeStream = true
}
if fc.FailFast {
c.FailFast = true
}
if fc.ExitAfterDirectReads {
c.ExitAfterDirectReads = true
}
if fc.DisableStats {
c.DisableStats = true
}
if fc.DisableStatsLog {
c.DisableStatsLog = true
}
if fc.Resume {
c.Resume = true
}
if !c.hasFlag("metadata-db") && fc.MetadataDB != "" {
c.MetadataDB = fc.MetadataDB
}
if !c.hasFlag("resume-name") && fc.ResumeName != "" {
c.ResumeName = fc.ResumeName
}
if !c.hasFlag("stats-duration") && fc.StatsDuration != "" {
c.StatsDuration = fc.StatsDuration
}
if len(c.ChangeStreamNs) == 0 {
c.ChangeStreamNs = fc.ChangeStreamNs
}
if len(c.DirectReadNs) == 0 {
c.DirectReadNs = fc.DirectReadNs
}
if !c.hasFlag("direct-read-split-max") && fc.DirectReadSplitMax != 0 {
c.DirectReadSplitMax = fc.DirectReadSplitMax
}
if !c.hasFlag("direct-read-concur") && fc.DirectReadConcur != 0 {
c.DirectReadConcur = fc.DirectReadConcur
}
c.loadPipelines(fc)
c.loadConsumers(fc)
c.KafkaSettings = fc.KafkaSettings
c.ProducerMaps = fc.ProducerMaps
}
func mustConfig() *config {
conf, err := loadConfig()
if err != nil {
errorLog.Fatalf("Configuration failed: %s", err)
return nil
}
return conf
}
func parseFlags() *config {
var c config
var v, help bool
flag.BoolVar(&v, "version", false, "Print the version number and exit")
flag.BoolVar(&v, "v", false, "Print the version number and exit")
flag.BoolVar(&help, "h", false, "Print help and exit")
flag.BoolVar(&c.viewConfig, "view-config", false, "Print the configuration and exit")
flag.StringVar(&c.ConfigFile, "f", "", "Path to a TOML formatted config file")
flag.StringVar(&c.MongoURI, "mongo", "mongodb://localhost:27017",
"MongoDB connection string URI")
flag.StringVar(&c.KafkaServers, "kafka", "localhost:9092",
"Address of Kafka broker")
flag.BoolVar(&c.FailFast, "fail-fast", false,
"True to exit the process after the first connection failure")
flag.BoolVar(&c.ExitAfterDirectReads, "exit-after-direct-reads", false,
"True to exit the process after direct reads have completed")
flag.BoolVar(&c.DisableChangeStream, "disable-change-stream", false,
"True to disable change events")
flag.BoolVar(&c.DisableStats, "disable-stats", false,
"True to disable stats")
flag.BoolVar(&c.DisableStatsLog, "disable-stats-log", false,
"True to disable periodic logging of indexing stats")
flag.BoolVar(&c.Resume, "resume", false,
"True to resume indexing from last saved timestamp")
flag.StringVar(&c.ResumeName, "resume-name", "default",
"Key to store and load saved timestamps from")
flag.StringVar(&c.MetadataDB, "metadata-db", "route81",
"Name of the MongoDB database to store route81 metadata")
flag.StringVar(&c.StatsDuration, "stats-duration", "10s",
"The max duration to wait before logging indexing stats")
flag.Var(&c.ChangeStreamNs, "change-stream-namespace", "MongoDB namespace to watch for changes")
flag.Var(&c.DirectReadNs, "direct-read-namespace", "MongoDB namespace to read and sync")
flag.IntVar(&c.DirectReadSplitMax, "direct-read-split-max", 9,
"The max number of times to split each collection for concurrent reads")
flag.IntVar(&c.DirectReadConcur, "direct-read-concur", 4,
"The max number collections to read concurrently")
flag.BoolVar(&c.EnableHTTPServer, "http-server", false,
"True to enable a HTTP server")
flag.StringVar(&c.HTTPServerAddr, "http-server-addr", ":8080",
"The address the HTTP server will bind to")
flag.StringVar(&c.TopicPrefix, "topic-name-prefix", "",
"A string to prepend to the MongoDB change event namespace to form the Kafka topic name")
flag.BoolVar(&c.Pprof, "pprof", false,
"True to enable profiling support")
flag.Parse()
if v {
fmt.Println(version)
os.Exit(0)
}
if help {
flag.PrintDefaults()
os.Exit(0)
}
return &c
}
func loadConfig() (*config, error) {
c := parseFlags()
if c.ConfigFile != "" {
var fc config
if md, err := toml.DecodeFile(c.ConfigFile, &fc); err != nil {
return nil, err
} else if ud := md.Undecoded(); len(ud) != 0 {
return nil, fmt.Errorf("Config file contains undecoded keys: %q", ud)
}
c.override(&fc)
}
if err := c.setDefaults().validate(); err != nil {
return nil, err
}
return c, nil
}
type clientStats struct {
Producer *producerStats `json:"producer"`
Consumer *consumerStats `json:"consumer"`
}
type consumerStats struct {
Success int64 `json:"success"`
Failed int64 `json:"failed"`
Queued int64 `json:"queued"`
sync.Mutex `json:"-"`
}
type producerStats struct {
Success int64 `json:"success"`
Failed int64 `json:"failed"`
Inserted int64 `json:"inserted"`
Updated int64 `json:"updated"`
Removed int64 `json:"removed"`
Dropped int64 `json:"dropped"`
Queued int64 `json:"queued"`
sync.Mutex `json:"-"`
}
type loggers struct {
infoLog *log.Logger
warnLog *log.Logger
statsLog *log.Logger
traceLog *log.Logger
errorLog *log.Logger
}
type msgClient struct {
mongoClient *mongo.Client
producer *kafka.Producer
config *config
readC chan bool
readContext *gtm.OpCtx
kafkaServers string
msgEncoder encoding.MessageEncoder
metaEncoder encoding.MessageEncoder
sinks []*sinkClient
stopC chan bool
allWg *sync.WaitGroup
logs *loggers
stats *producerStats
statsCons *consumerStats
statsDuration time.Duration
timestamp primitive.Timestamp
deliveryC chan kafka.Event
started time.Time
httpServer *http.Server
respHandlers int
sync.Mutex
}
type sinkClient struct {
msgClient *msgClient
consumer *consumer
events chan kafka.Event
decoder decoding.MessageDecoder
}
type sinkWorker struct {
sinkClient *sinkClient
docs []interface{}
}
func (args *stringargs) String() string {
return fmt.Sprintf("%s", *args)
}
func (args *stringargs) Set(value string) error {
*args = append(*args, value)
return nil
}
func toDocID(op *gtm.Op, ns bool) string {
var id strings.Builder
if ns {
id.WriteString(op.Namespace)
if op.Id != nil {
id.WriteString(".")
}
}
if op.Id != nil {
switch val := op.Id.(type) {
case primitive.ObjectID:
id.WriteString(val.Hex())
case float64:
intID := int(val)
if op.Id.(float64) == float64(intID) {
fmt.Fprintf(&id, "%v", intID)
} else {
fmt.Fprintf(&id, "%v", op.Id)
}
case float32:
intID := int(val)
if op.Id.(float32) == float32(intID) {
fmt.Fprintf(&id, "%v", intID)
} else {
fmt.Fprintf(&id, "%v", op.Id)
}
default:
fmt.Fprintf(&id, "%v", op.Id)
}
}
return id.String()
}
func (is *producerStats) dup() *producerStats {
is.Lock()
defer is.Unlock()
return &producerStats{
Success: is.Success,
Failed: is.Failed,
Inserted: is.Inserted,
Updated: is.Updated,
Removed: is.Removed,
Dropped: is.Dropped,
Queued: is.Queued,
}
}
func (cs *consumerStats) dup() *consumerStats {
cs.Lock()
defer cs.Unlock()
return &consumerStats{
Success: cs.Success,
Failed: cs.Failed,
Queued: cs.Queued,
}
}
func (cs *consumerStats) addSuccess(count int) {
cs.Lock()
cs.Success += int64(count)
cs.Unlock()
}
func (cs *consumerStats) addFailed(count int) {
cs.Lock()
cs.Failed += int64(count)
cs.Unlock()
}
func (cs *consumerStats) addQueued(count int) {
cs.Lock()
cs.Queued += int64(count)
cs.Unlock()
}
func (is *producerStats) addSuccess(count int) {
is.Lock()
is.Success += int64(count)
is.Unlock()
}
func (is *producerStats) addFailed(count int) {
is.Lock()
is.Failed += int64(count)
is.Unlock()
}
func (is *producerStats) addInserted(count int) {
is.Lock()
is.Inserted += int64(count)
is.Unlock()
}
func (is *producerStats) addUpdated(count int) {
is.Lock()
is.Updated += int64(count)
is.Unlock()
}
func (is *producerStats) addRemoved(count int) {
is.Lock()
is.Removed += int64(count)
is.Unlock()
}
func (is *producerStats) addDropped(count int) {
is.Lock()
is.Dropped += int64(count)
is.Unlock()
}
func (is *producerStats) addQueued(count int) {
is.Lock()
is.Queued += int64(count)
is.Unlock()
}
func isNetError(err error) bool {
if err == nil {
return false
}
switch t := err.(type) {
case net.Error:
return true
case *net.OpError:
return true
case syscall.Errno:
if t == syscall.ECONNREFUSED {
return true
}
}
return false
}
func newLoggers() *loggers {
return &loggers{
infoLog: infoLog,
warnLog: warnLog,
statsLog: statsLog,
traceLog: traceLog,
errorLog: errorLog,
}
}
func (mc *msgClient) setSinks(conf *config) *msgClient {
var sinks []*sinkClient
if len(conf.Consumers) > 0 {
for _, c := range conf.Consumers {
consumer := &c
sink := &sinkClient{
msgClient: mc,
consumer: consumer,
}
switch consumer.Format {
case "avro":
sink.decoder = &decoding.AvroMessageDecoder{
SchemaSpec: consumer.AvroSchemaSpec,
Binary: consumer.AvroBinary,
}
case "json-ext":
sink.decoder = &decoding.JSONExtMessageDecoder{}
default:
sink.decoder = &decoding.JSONMessageDecoder{}
}
sinks = append(sinks, sink)
}
}
mc.sinks = sinks
return mc
}
func newMsgClient(client *mongo.Client, producer *kafka.Producer, ctx *gtm.OpCtx, conf *config) *msgClient {
statsDuration, _ := time.ParseDuration(conf.StatsDuration)
mc := &msgClient{
mongoClient: client,
producer: producer,
config: conf,
readC: make(chan bool),
readContext: ctx,
allWg: &sync.WaitGroup{},
stopC: make(chan bool),
kafkaServers: conf.KafkaServers,
msgEncoder: &encoding.JSONExtMessageEncoder{},
metaEncoder: &encoding.JSONMessageEncoder{},
logs: newLoggers(),
stats: &producerStats{},
statsCons: &consumerStats{},
statsDuration: statsDuration,
deliveryC: make(chan (kafka.Event), 1000),
respHandlers: 4,
}
mc.setSinks(conf)
return mc
}
func (mc *msgClient) sigListen() {
sigs := make(chan os.Signal)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
defer signal.Stop(sigs)
<-sigs
go func() {
<-sigs
mc.logs.infoLog.Println("Forcing shutdown, bye bye...")
os.Exit(1)
}()
mc.logs.infoLog.Println("Shutting down")
mc.stop()
mc.logs.infoLog.Println("Ready to exit, bye bye...")
os.Exit(0)
}
func (mc *msgClient) logStats() {
producerStats := mc.stats.dup()
consumerStats := mc.statsCons.dup()
stats := &clientStats{
Producer: producerStats,
Consumer: consumerStats,
}
if b, err := json.Marshal(stats); err == nil {
mc.logs.statsLog.Println(string(b))
}
}
func (mc *msgClient) statsLoop() {
if mc.config.DisableStats || mc.config.DisableStatsLog {
return
}
heartBeat := time.NewTicker(mc.statsDuration)
defer heartBeat.Stop()
done := false
for !done {
select {
case <-heartBeat.C:
mc.logStats()
case <-mc.stopC:
mc.logStats()
done = true
}
}
}
func (mc *msgClient) readListen() {
conf := mc.config
if len(conf.DirectReadNs) > 0 {
mc.readContext.DirectReadWg.Wait()
infoLog.Println("Direct reads completed")
if conf.ExitAfterDirectReads {
mc.logs.infoLog.Println("Shutting down")
mc.stop()
os.Exit(0)
}
}
}
func (mc *msgClient) getTimestamp() primitive.Timestamp {
mc.Lock()
defer mc.Unlock()
return mc.timestamp
}
func (mc *msgClient) setTimestamp(ts primitive.Timestamp) {
mc.Lock()
if mc.stats.Failed == 0 {
// if we have a single failure do not progress the timestamp
mc.timestamp = ts
}
mc.Unlock()
}
func (mc *msgClient) saveTimestamp(ts primitive.Timestamp) error {
config := mc.config
mclient := mc.mongoClient
if ts.T == 0 {
return nil
}
col := mclient.Database(config.MetadataDB).Collection("resume")
doc := bson.M{
"ts": ts,
}
opts := options.Update()
opts.SetUpsert(true)
_, err := col.UpdateOne(context.Background(), bson.M{
"_id": config.ResumeName,
}, bson.M{
"$set": doc,
}, opts)
return err
}
func (mc *msgClient) timestampLoop() {
defer mc.allWg.Done()
ticker := time.NewTicker(time.Duration(10) * time.Second)
defer ticker.Stop()
running := true
lastTime := primitive.Timestamp{}
for running {
select {
case <-ticker.C:
ts := mc.getTimestamp()
if ts.T > lastTime.T || (ts.T == lastTime.T && ts.I > lastTime.I) {
lastTime = ts
if err := mc.saveTimestamp(lastTime); err != nil {
errorLog.Printf("Error saving timestamp: %s", err)
}
}
break
case <-mc.stopC:
running = false
break
}
}
}
func (mc *msgClient) handleFatalError() {
mc.logs.errorLog.Println("Shutting down after fatal error")
mc.stop()
os.Exit(1)
}
func (mc *msgClient) startResponseHandlers() {
for i := 0; i < mc.respHandlers; i++ {
mc.allWg.Add(1)
go mc.responseLoop()
}
}
func (mc *msgClient) responseLoop() {
defer mc.allWg.Done()
running := true
for running {
select {
case e := <-mc.deliveryC:
if err := mc.onEvent(e); err != nil {
mc.logs.errorLog.Printf("Broker response error: %s", err)
ke, ok := err.(kafka.Error)
if ok && ke.IsFatal() {
go mc.handleFatalError()
}
}
break
case <-mc.stopC:
running = false
break
}
}
}
func (mc *msgClient) metaLoop() {
config := mc.config
if config.Resume {
mc.allWg.Add(1)
go mc.timestampLoop()
}
}
func (mc *msgClient) serveHTTP() {
config := mc.config
if !config.EnableHTTPServer {
return
}
mc.buildServer()
s := mc.httpServer
infoLog.Printf("Starting http server at %s", s.Addr)
mc.started = time.Now()
err := s.ListenAndServe()
select {
case <-mc.stopC:
return
default:
errorLog.Fatalf("Unable to serve http at address %s: %s", s.Addr, err)
}
}
func (mc *msgClient) buildServer() {
mux := http.NewServeMux()
mux.HandleFunc("/started", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
data := (time.Now().Sub(mc.started)).String()
w.Write([]byte(data))
})
mux.HandleFunc("/healthz", func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(200)
w.Write([]byte("ok"))
})
if !mc.config.DisableStats {
mux.HandleFunc("/stats", func(w http.ResponseWriter, req *http.Request) {
producerStats := mc.stats.dup()
consumerStats := mc.statsCons.dup()
stats := &clientStats{
Producer: producerStats,
Consumer: consumerStats,
}
statsJSON, err := json.MarshalIndent(stats, "", " ")
if err == nil {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write(statsJSON)
} else {
w.WriteHeader(500)
fmt.Fprintf(w, "Unable to print statistics: %s", err)
}
})
}
if mc.config.Pprof {
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
}
s := &http.Server{
Addr: mc.config.HTTPServerAddr,
Handler: mux,
ErrorLog: errorLog,
}
mc.httpServer = s
}
func (sc *sinkClient) messageDoc(m *kafka.Message) (interface{}, error) {
var err error
var doc interface{}
if doc, err = sc.decoder.Decode(m.Value); err != nil {
return nil, err
}
return doc, nil
}
func (sw *sinkWorker) queueMessage(e kafka.Event) {
sc := sw.sinkClient
mc := sc.msgClient
stats := mc.statsCons
logs := mc.logs
switch ev := e.(type) {
case *kafka.Message:
var err error
if err = ev.TopicPartition.Error; err != nil {
logs.errorLog.Println(err)