forked from rwynn/monstache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmonstache.go
4265 lines (4090 loc) · 123 KB
/
monstache.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 provides the monstache binary
package main
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"math"
"net"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"plugin"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"text/template"
"time"
"github.com/BurntSushi/toml"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/coreos/go-systemd/daemon"
jsonpatch "github.com/evanphx/json-patch"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/olivere/elastic"
aws "github.com/olivere/elastic/aws/v4"
"github.com/robertkrimen/otto"
_ "github.com/robertkrimen/otto/underscore"
"github.com/rwynn/gtm"
"github.com/rwynn/gtm/consistent"
"github.com/rwynn/monstache/monstachemap"
"golang.org/x/net/context"
"gopkg.in/Graylog2/go-gelf.v2/gelf"
"gopkg.in/natefinch/lumberjack.v2"
)
var infoLog = log.New(os.Stdout, "INFO ", log.Flags())
var warnLog = log.New(os.Stdout, "WARN ", log.Flags())
var statsLog = log.New(os.Stdout, "STATS ", log.Flags())
var traceLog = log.New(os.Stdout, "TRACE ", log.Flags())
var errorLog = log.New(os.Stderr, "ERROR ", log.Flags())
var mapperPlugin func(*monstachemap.MapperPluginInput) (*monstachemap.MapperPluginOutput, error)
var filterPlugin func(*monstachemap.MapperPluginInput) (bool, error)
var processPlugin func(*monstachemap.ProcessPluginInput) error
var pipePlugin func(string, bool) ([]interface{}, error)
var mapEnvs map[string]*executionEnv = make(map[string]*executionEnv)
var filterEnvs map[string]*executionEnv = make(map[string]*executionEnv)
var pipeEnvs map[string]*executionEnv = make(map[string]*executionEnv)
var mapIndexTypes map[string]*indexTypeMapping = make(map[string]*indexTypeMapping)
var relates map[string][]*relation = make(map[string][]*relation)
var fileNamespaces map[string]bool = make(map[string]bool)
var patchNamespaces map[string]bool = make(map[string]bool)
var tmNamespaces map[string]bool = make(map[string]bool)
var routingNamespaces map[string]bool = make(map[string]bool)
var mux sync.Mutex
var chunksRegex = regexp.MustCompile("\\.chunks$")
var systemsRegex = regexp.MustCompile("system\\..+$")
var exitStatus = 0
var mongoDialInfo *mgo.DialInfo
const version = "4.18.0"
const mongoURLDefault string = "localhost"
const resumeNameDefault string = "default"
const elasticMaxConnsDefault int = 4
const elasticClientTimeoutDefault int = 0
const elasticMaxDocsDefault int = -1
const elasticMaxBytesDefault int = 8 * 1024 * 1024
const gtmChannelSizeDefault int = 512
const typeFromFuture string = "_doc"
const fileDownloadersDefault = 10
const relateThreadsDefault = 10
const relateBufferDefault = 1000
const postProcessorsDefault = 10
const redact = "REDACTED"
const configDatabaseNameDefault = "monstache"
const relateQueueOverloadMsg = "Relate queue is full. Skipping relate for %v.(%v) to keep pipeline healthy."
type deleteStrategy int
const (
statelessDeleteStrategy deleteStrategy = iota
statefulDeleteStrategy
ignoreDeleteStrategy
)
type stringargs []string
type awsConnect struct {
AccessKey string `toml:"access-key"`
SecretKey string `toml:"secret-key"`
Region string
}
type executionEnv struct {
VM *otto.Otto
Script string
lock *sync.Mutex
}
type javascript struct {
Namespace string
Script string
Path string
Routing bool
}
type relation struct {
Namespace string
WithNamespace string `toml:"with-namespace"`
SrcField string `toml:"src-field"`
MatchField string `toml:"match-field"`
KeepSrc bool `toml:"keep-src"`
MaxDepth int `toml:"max-depth"`
db string
col string
}
type indexTypeMapping struct {
Namespace string
Index string
Type string
}
type findConf struct {
vm *otto.Otto
ns string
name string
session *mgo.Session
byId bool
multi bool
pipe bool
pipeAllowDisk bool
}
type findCall struct {
config *findConf
session *mgo.Session
query interface{}
db string
col string
limit int
sort []string
sel map[string]int
}
type logFiles struct {
Info string
Warn string
Error string
Trace string
Stats string
}
type indexingMeta struct {
Routing string
Index string
Type string
Parent string
Version int64
VersionType string
Pipeline string
RetryOnConflict int
Skip bool
ID string
}
type outputChans struct {
indexC chan *gtm.Op
processC chan *gtm.Op
fileC chan *gtm.Op
relateC chan *gtm.Op
filter gtm.OpFilter
}
type mongoDialSettings struct {
Timeout int
Ssl bool
ReadTimeout int `toml:"read-timeout"`
WriteTimeout int `toml:"write-timeout"`
}
type mongoSessionSettings struct {
SocketTimeout int `toml:"socket-timeout"`
SyncTimeout int `toml:"sync-timeout"`
}
type mongoX509Settings struct {
ClientCertPemFile string `toml:"client-cert-pem-file"`
ClientKeyPemFile string `toml:"client-key-pem-file"`
}
type gtmSettings struct {
ChannelSize int `toml:"channel-size"`
BufferSize int `toml:"buffer-size"`
BufferDuration string `toml:"buffer-duration"`
}
type httpServerCtx struct {
httpServer *http.Server
bulk *elastic.BulkProcessor
config *configOptions
shutdown bool
started time.Time
enabled *bool
}
type instanceStatus struct {
Enabled bool `json:"enabled"`
Pid int `json:"pid"`
Hostname string `json:"hostname"`
ClusterName string `json:"cluster"`
ResumeName string `json:"resumeName"`
LastTs string `json:"lastTs"`
}
type configOptions struct {
EnableTemplate bool
EnvDelimiter string
MongoURL string `toml:"mongo-url"`
MongoConfigURL string `toml:"mongo-config-url"`
MongoPemFile string `toml:"mongo-pem-file"`
MongoValidatePemFile bool `toml:"mongo-validate-pem-file"`
MongoOpLogDatabaseName string `toml:"mongo-oplog-database-name"`
MongoOpLogCollectionName string `toml:"mongo-oplog-collection-name"`
MongoDialSettings mongoDialSettings `toml:"mongo-dial-settings"`
MongoSessionSettings mongoSessionSettings `toml:"mongo-session-settings"`
MongoX509Settings mongoX509Settings `toml:"mongo-x509-settings"`
GtmSettings gtmSettings `toml:"gtm-settings"`
AWSConnect awsConnect `toml:"aws-connect"`
Logs logFiles `toml:"logs"`
GraylogAddr string `toml:"graylog-addr"`
ElasticUrls stringargs `toml:"elasticsearch-urls"`
ElasticUser string `toml:"elasticsearch-user"`
ElasticPassword string `toml:"elasticsearch-password"`
ElasticPemFile string `toml:"elasticsearch-pem-file"`
ElasticValidatePemFile bool `toml:"elasticsearch-validate-pem-file"`
ElasticVersion string `toml:"elasticsearch-version"`
ElasticHealth0 int `toml:"elasticsearch-healthcheck-timeout-startup"`
ElasticHealth1 int `toml:"elasticsearch-healthcheck-timeout"`
ResumeName string `toml:"resume-name"`
NsRegex string `toml:"namespace-regex"`
NsDropRegex string `toml:"namespace-drop-regex"`
NsExcludeRegex string `toml:"namespace-exclude-regex"`
NsDropExcludeRegex string `toml:"namespace-drop-exclude-regex"`
ClusterName string `toml:"cluster-name"`
Print bool `toml:"print-config"`
Version bool
Pprof bool
DisableChangeEvents bool `toml:"disable-change-events"`
EnableEasyJSON bool `toml:"enable-easy-json"`
Stats bool
IndexStats bool `toml:"index-stats"`
StatsDuration string `toml:"stats-duration"`
StatsIndexFormat string `toml:"stats-index-format"`
Gzip bool
Verbose bool
Resume bool
ResumeWriteUnsafe bool `toml:"resume-write-unsafe"`
ResumeFromTimestamp int64 `toml:"resume-from-timestamp"`
Replay bool
DroppedDatabases bool `toml:"dropped-databases"`
DroppedCollections bool `toml:"dropped-collections"`
IndexFiles bool `toml:"index-files"`
IndexAsUpdate bool `toml:"index-as-update"`
FileHighlighting bool `toml:"file-highlighting"`
EnablePatches bool `toml:"enable-patches"`
FailFast bool `toml:"fail-fast"`
IndexOplogTime bool `toml:"index-oplog-time"`
OplogTsFieldName string `toml:"oplog-ts-field-name"`
OplogDateFieldName string `toml:"oplog-date-field-name"`
OplogDateFieldFormat string `toml:"oplog-date-field-format"`
ExitAfterDirectReads bool `toml:"exit-after-direct-reads"`
MergePatchAttr string `toml:"merge-patch-attribute"`
ElasticMaxConns int `toml:"elasticsearch-max-conns"`
ElasticRetry bool `toml:"elasticsearch-retry"`
ElasticMaxDocs int `toml:"elasticsearch-max-docs"`
ElasticMaxBytes int `toml:"elasticsearch-max-bytes"`
ElasticMaxSeconds int `toml:"elasticsearch-max-seconds"`
ElasticClientTimeout int `toml:"elasticsearch-client-timeout"`
ElasticMajorVersion int
ElasticMinorVersion int
MaxFileSize int64 `toml:"max-file-size"`
ConfigFile string
Script []javascript
Filter []javascript
Pipeline []javascript
Mapping []indexTypeMapping
Relate []relation
FileNamespaces stringargs `toml:"file-namespaces"`
PatchNamespaces stringargs `toml:"patch-namespaces"`
Workers stringargs
Worker string
ChangeStreamNs stringargs `toml:"change-stream-namespaces"`
DirectReadNs stringargs `toml:"direct-read-namespaces"`
DirectReadSplitMax int `toml:"direct-read-split-max"`
DirectReadConcur int `toml:"direct-read-concur"`
DirectReadNoTimeout bool `toml:"direct-read-no-timeout"`
MapperPluginPath string `toml:"mapper-plugin-path"`
EnableHTTPServer bool `toml:"enable-http-server"`
HTTPServerAddr string `toml:"http-server-addr"`
TimeMachineNamespaces stringargs `toml:"time-machine-namespaces"`
TimeMachineIndexPrefix string `toml:"time-machine-index-prefix"`
TimeMachineIndexSuffix string `toml:"time-machine-index-suffix"`
TimeMachineDirectReads bool `toml:"time-machine-direct-reads"`
PipeAllowDisk bool `toml:"pipe-allow-disk"`
RoutingNamespaces stringargs `toml:"routing-namespaces"`
DeleteStrategy deleteStrategy `toml:"delete-strategy"`
DeleteIndexPattern string `toml:"delete-index-pattern"`
ConfigDatabaseName string `toml:"config-database-name"`
FileDownloaders int `toml:"file-downloaders"`
RelateThreads int `toml:"relate-threads"`
RelateBuffer int `toml:"relate-buffer"`
PostProcessors int `toml:"post-processors"`
PruneInvalidJSON bool `toml:"prune-invalid-json"`
Debug bool
}
func (rel *relation) IsIdentity() bool {
if rel.SrcField == "_id" && rel.MatchField == "_id" {
return true
} else {
return false
}
}
func (l *logFiles) enabled() bool {
return l.Info != "" || l.Warn != "" || l.Error != "" || l.Trace != "" || l.Stats != ""
}
func (s *mongoX509Settings) enabled() bool {
return s.ClientCertPemFile != "" || s.ClientKeyPemFile != ""
}
func (s *mongoX509Settings) validate() error {
if s.ClientCertPemFile != "" || s.ClientKeyPemFile != "" {
if s.ClientCertPemFile == "" {
return errors.New("Client cert pem file missing for X509 authentication")
} else if s.ClientKeyPemFile == "" {
return errors.New("Client key pem file missing for X509 authentication")
}
}
return nil
}
func (ac *awsConnect) validate() error {
if ac.AccessKey == "" && ac.SecretKey == "" {
return nil
} else if ac.AccessKey != "" && ac.SecretKey != "" {
return nil
}
return errors.New("AWS connect settings must include both access-key and secret-key")
}
func (ac *awsConnect) enabled() bool {
return ac.AccessKey != "" || ac.SecretKey != ""
}
func (arg *deleteStrategy) String() string {
return fmt.Sprintf("%d", *arg)
}
func (arg *deleteStrategy) Set(value string) (err error) {
var i int
if i, err = strconv.Atoi(value); err != nil {
return
}
ds := deleteStrategy(i)
*arg = ds
return
}
func (args *stringargs) String() string {
return fmt.Sprintf("%s", *args)
}
func (args *stringargs) Set(value string) error {
*args = append(*args, value)
return nil
}
func (config *configOptions) readShards() bool {
return len(config.ChangeStreamNs) == 0 && config.MongoConfigURL != ""
}
func afterBulk(executionId int64, requests []elastic.BulkableRequest, response *elastic.BulkResponse, err error) {
if response != nil && response.Errors {
failed := response.Failed()
if failed != nil {
for _, item := range failed {
if item.Status == 409 {
// ignore version conflict since this simply means the doc
// is already in the index
continue
}
json, err := json.Marshal(item)
if err != nil {
errorLog.Printf("Unable to marshal bulk response item: %s", err)
} else {
errorLog.Printf("Bulk response item: %s", string(json))
}
}
}
}
}
func (config *configOptions) useTypeFromFuture() (use bool) {
if config.ElasticMajorVersion > 6 {
use = true
} else if config.ElasticMajorVersion == 6 && config.ElasticMinorVersion >= 2 {
use = true
}
return
}
func (config *configOptions) parseElasticsearchVersion(number string) (err error) {
if number == "" {
err = errors.New("Elasticsearch version cannot be blank")
} else {
versionParts := strings.Split(number, ".")
var majorVersion, minorVersion int
majorVersion, err = strconv.Atoi(versionParts[0])
if err == nil {
config.ElasticMajorVersion = majorVersion
if majorVersion == 0 {
err = errors.New("Invalid Elasticsearch major version 0")
}
}
if len(versionParts) > 1 {
minorVersion, err = strconv.Atoi(versionParts[1])
if err == nil {
config.ElasticMinorVersion = minorVersion
}
}
}
return
}
func (config *configOptions) newBulkProcessor(client *elastic.Client) (bulk *elastic.BulkProcessor, err error) {
bulkService := client.BulkProcessor().Name("monstache")
bulkService.Workers(config.ElasticMaxConns)
bulkService.Stats(config.Stats)
bulkService.BulkActions(config.ElasticMaxDocs)
bulkService.BulkSize(config.ElasticMaxBytes)
if config.ElasticRetry == false {
bulkService.Backoff(&elastic.StopBackoff{})
}
bulkService.After(afterBulk)
bulkService.FlushInterval(time.Duration(config.ElasticMaxSeconds) * time.Second)
return bulkService.Do(context.Background())
}
func (config *configOptions) newStatsBulkProcessor(client *elastic.Client) (bulk *elastic.BulkProcessor, err error) {
bulkService := client.BulkProcessor().Name("monstache-stats")
bulkService.Workers(1)
bulkService.Stats(false)
bulkService.BulkActions(-1)
bulkService.BulkSize(-1)
bulkService.After(afterBulk)
bulkService.FlushInterval(time.Duration(5) * time.Second)
return bulkService.Do(context.Background())
}
func (config *configOptions) needsSecureScheme() bool {
if len(config.ElasticUrls) > 0 {
for _, url := range config.ElasticUrls {
if strings.HasPrefix(url, "https") {
return true
}
}
}
return false
}
func (config *configOptions) newElasticClient() (client *elastic.Client, err error) {
var clientOptions []elastic.ClientOptionFunc
var httpClient *http.Client
clientOptions = append(clientOptions, elastic.SetSniff(false))
if config.needsSecureScheme() {
clientOptions = append(clientOptions, elastic.SetScheme("https"))
}
if len(config.ElasticUrls) > 0 {
clientOptions = append(clientOptions, elastic.SetURL(config.ElasticUrls...))
} else {
config.ElasticUrls = append(config.ElasticUrls, elastic.DefaultURL)
}
if config.Verbose {
clientOptions = append(clientOptions, elastic.SetTraceLog(traceLog))
clientOptions = append(clientOptions, elastic.SetErrorLog(errorLog))
}
if config.ElasticUser != "" {
clientOptions = append(clientOptions, elastic.SetBasicAuth(config.ElasticUser, config.ElasticPassword))
}
if config.ElasticRetry {
d1, d2 := time.Duration(50)*time.Millisecond, time.Duration(20)*time.Second
retrier := elastic.NewBackoffRetrier(elastic.NewExponentialBackoff(d1, d2))
clientOptions = append(clientOptions, elastic.SetRetrier(retrier))
}
httpClient, err = config.NewHTTPClient()
if err != nil {
return client, err
}
clientOptions = append(clientOptions, elastic.SetHttpClient(httpClient))
clientOptions = append(clientOptions,
elastic.SetHealthcheckTimeoutStartup(time.Duration(config.ElasticHealth0)*time.Second))
clientOptions = append(clientOptions,
elastic.SetHealthcheckTimeout(time.Duration(config.ElasticHealth1)*time.Second))
return elastic.NewClient(clientOptions...)
}
func (config *configOptions) testElasticsearchConn(client *elastic.Client) (err error) {
var number string
url := config.ElasticUrls[0]
number, err = client.ElasticsearchVersion(url)
if err == nil {
infoLog.Printf("Successfully connected to Elasticsearch version %s", number)
err = config.parseElasticsearchVersion(number)
}
return
}
func deleteIndexes(client *elastic.Client, db string, config *configOptions) (err error) {
index := strings.ToLower(db + "*")
for ns, m := range mapIndexTypes {
dbCol := strings.SplitN(ns, ".", 2)
if dbCol[0] == db {
if m.Index != "" {
index = strings.ToLower(m.Index + "*")
}
break
}
}
_, err = client.DeleteIndex(index).Do(context.Background())
return
}
func deleteIndex(client *elastic.Client, namespace string, config *configOptions) (err error) {
ctx := context.Background()
index := strings.ToLower(namespace)
if m := mapIndexTypes[namespace]; m != nil {
if m.Index != "" {
index = strings.ToLower(m.Index)
}
}
_, err = client.DeleteIndex(index).Do(ctx)
return err
}
func ensureFileMapping(client *elastic.Client) (err error) {
ctx := context.Background()
pipeline := map[string]interface{}{
"description": "Extract file information",
"processors": [1]map[string]interface{}{
{
"attachment": map[string]interface{}{
"field": "file",
},
},
},
}
_, err = client.IngestPutPipeline("attachment").BodyJson(pipeline).Do(ctx)
return err
}
func defaultIndexTypeMapping(config *configOptions, op *gtm.Op) *indexTypeMapping {
typeName := typeFromFuture
if !config.useTypeFromFuture() {
typeName = op.GetCollection()
}
return &indexTypeMapping{
Namespace: op.Namespace,
Index: strings.ToLower(op.Namespace),
Type: typeName,
}
}
func mapIndexType(config *configOptions, op *gtm.Op) *indexTypeMapping {
mapping := defaultIndexTypeMapping(config, op)
if m := mapIndexTypes[op.Namespace]; m != nil {
if m.Index != "" {
mapping.Index = m.Index
}
if m.Type != "" {
mapping.Type = m.Type
}
}
return mapping
}
func opIDToString(op *gtm.Op) string {
var opIDStr string
switch id := op.Id.(type) {
case bson.ObjectId:
opIDStr = id.Hex()
case bson.Binary:
opIDStr = monstachemap.EncodeBinData(monstachemap.Binary{id})
case float64:
intID := int(id)
if id == float64(intID) {
opIDStr = fmt.Sprintf("%v", intID)
} else {
opIDStr = fmt.Sprintf("%v", op.Id)
}
case float32:
intID := int(id)
if id == float32(intID) {
opIDStr = fmt.Sprintf("%v", intID)
} else {
opIDStr = fmt.Sprintf("%v", op.Id)
}
default:
opIDStr = fmt.Sprintf("%v", op.Id)
}
return opIDStr
}
func convertSliceJavascript(a []interface{}) []interface{} {
var avs []interface{}
for _, av := range a {
var avc interface{}
switch achild := av.(type) {
case map[string]interface{}:
avc = convertMapJavascript(achild)
case []interface{}:
avc = convertSliceJavascript(achild)
case bson.ObjectId:
avc = achild.Hex()
default:
avc = av
}
avs = append(avs, avc)
}
return avs
}
func convertMapJavascript(e map[string]interface{}) map[string]interface{} {
o := make(map[string]interface{})
for k, v := range e {
switch child := v.(type) {
case map[string]interface{}:
o[k] = convertMapJavascript(child)
case []interface{}:
o[k] = convertSliceJavascript(child)
case bson.ObjectId:
o[k] = child.Hex()
default:
o[k] = v
}
}
return o
}
func fixSlicePruneInvalidJSON(id string, key string, a []interface{}) []interface{} {
var avs []interface{}
for _, av := range a {
var avc interface{}
switch achild := av.(type) {
case map[string]interface{}:
avc = fixPruneInvalidJSON(id, achild)
case []interface{}:
avc = fixSlicePruneInvalidJSON(id, key, achild)
case time.Time:
year := achild.Year()
if year < 0 || year > 9999 {
// year outside of valid range
warnLog.Printf("Dropping key %s element: invalid time.Time value: %s for document _id: %s", key, achild, id)
continue
} else {
avc = av
}
case float64:
if math.IsNaN(achild) {
// causes an error in the json serializer
warnLog.Printf("Dropping key %s element: invalid float64 value: %v for document _id: %s", key, achild, id)
continue
} else if math.IsInf(achild, 0) {
// causes an error in the json serializer
warnLog.Printf("Dropping key %s element: invalid float64 value: %v for document _id: %s", key, achild, id)
continue
} else {
avc = av
}
default:
avc = av
}
avs = append(avs, avc)
}
return avs
}
func fixPruneInvalidJSON(id string, e map[string]interface{}) map[string]interface{} {
o := make(map[string]interface{})
for k, v := range e {
switch child := v.(type) {
case map[string]interface{}:
o[k] = fixPruneInvalidJSON(id, child)
case []interface{}:
o[k] = fixSlicePruneInvalidJSON(id, k, child)
case time.Time:
year := child.Year()
if year < 0 || year > 9999 {
// year outside of valid range
warnLog.Printf("Dropping key %s: invalid time.Time value: %s for document _id: %s", k, child, id)
continue
} else {
o[k] = v
}
case float64:
if math.IsNaN(child) {
// causes an error in the json serializer
warnLog.Printf("Dropping key %s: invalid float64 value: %v for document _id: %s", k, child, id)
continue
} else if math.IsInf(child, 0) {
// causes an error in the json serializer
warnLog.Printf("Dropping key %s: invalid float64 value: %v for document _id: %s", k, child, id)
continue
} else {
o[k] = v
}
default:
o[k] = v
}
}
return o
}
func deepExportValue(a interface{}) (b interface{}) {
switch t := a.(type) {
case otto.Value:
ex, err := t.Export()
if t.Class() == "Date" {
ex, err = time.Parse("Mon, 2 Jan 2006 15:04:05 MST", t.String())
}
if err == nil {
b = deepExportValue(ex)
} else {
errorLog.Printf("Error exporting from javascript: %s", err)
}
case map[string]interface{}:
b = deepExportMap(t)
case []map[string]interface{}:
b = deepExportMapSlice(t)
case []interface{}:
b = deepExportSlice(t)
default:
b = a
}
return
}
func deepExportMapSlice(a []map[string]interface{}) []interface{} {
var avs []interface{}
for _, av := range a {
avs = append(avs, deepExportMap(av))
}
return avs
}
func deepExportSlice(a []interface{}) []interface{} {
var avs []interface{}
for _, av := range a {
avs = append(avs, deepExportValue(av))
}
return avs
}
func deepExportMap(e map[string]interface{}) map[string]interface{} {
o := make(map[string]interface{})
for k, v := range e {
o[k] = deepExportValue(v)
}
return o
}
func mapDataJavascript(op *gtm.Op) error {
names := []string{"", op.Namespace}
for _, name := range names {
if env := mapEnvs[name]; env != nil {
env.lock.Lock()
defer env.lock.Unlock()
arg := convertMapJavascript(op.Data)
arg2 := op.Namespace
arg3 := convertMapJavascript(op.UpdateDescription)
val, err := env.VM.Call("module.exports", arg, arg, arg2, arg3)
if err != nil {
return err
}
if strings.ToLower(val.Class()) == "object" {
data, err := val.Export()
if err != nil {
return err
} else if data == val {
return errors.New("Exported function must return an object")
} else {
dm := data.(map[string]interface{})
op.Data = deepExportMap(dm)
}
} else {
indexed, err := val.ToBoolean()
if err != nil {
return err
} else if !indexed {
op.Data = nil
break
}
}
}
}
return nil
}
func mapDataGolang(s *mgo.Session, op *gtm.Op) error {
session := s.Copy()
defer session.Close()
input := &monstachemap.MapperPluginInput{
Document: op.Data,
Namespace: op.Namespace,
Database: op.GetDatabase(),
Collection: op.GetCollection(),
Operation: op.Operation,
Session: session,
UpdateDescription: op.UpdateDescription,
}
output, err := mapperPlugin(input)
if err != nil {
return err
}
if output != nil {
if output.Drop {
op.Data = nil
} else {
if output.Skip {
op.Data = map[string]interface{}{}
} else if output.Passthrough == false {
if output.Document == nil {
return errors.New("Map function must return a non-nil document")
}
op.Data = output.Document
}
meta := make(map[string]interface{})
if output.Skip {
meta["skip"] = true
}
if output.Index != "" {
meta["index"] = output.Index
}
if output.ID != "" {
meta["id"] = output.ID
}
if output.Type != "" {
meta["type"] = output.Type
}
if output.Routing != "" {
meta["routing"] = output.Routing
}
if output.Parent != "" {
meta["parent"] = output.Parent
}
if output.Version != 0 {
meta["version"] = output.Version
}
if output.VersionType != "" {
meta["versionType"] = output.VersionType
}
if output.Pipeline != "" {
meta["pipeline"] = output.Pipeline
}
if output.RetryOnConflict != 0 {
meta["retryOnConflict"] = output.RetryOnConflict
}
if len(meta) > 0 {
op.Data["_meta_monstache"] = meta
}
}
}
return nil
}
func mapData(session *mgo.Session, config *configOptions, op *gtm.Op) error {
if mapperPlugin != nil {
return mapDataGolang(session, op)
}
return mapDataJavascript(op)
}
func extractData(srcField string, data map[string]interface{}) (result interface{}, err error) {
var cur map[string]interface{} = data
fields := strings.Split(srcField, ".")
flen := len(fields)
for i, field := range fields {
if i+1 == flen {
result = cur[field]
} else {
if next, ok := cur[field].(map[string]interface{}); ok {
cur = next
} else {
break
}
}
}
if result == nil {
var detail interface{}
b, e := json.Marshal(data)
if e == nil {
detail = string(b)
} else {
detail = err
}
err = fmt.Errorf("Source field %s not found in document: %s", srcField, detail)
}
return
}
func buildSelector(matchField string, data interface{}) bson.M {
sel := bson.M{}
var cur bson.M = sel
fields := strings.Split(matchField, ".")
flen := len(fields)
for i, field := range fields {
if i+1 == flen {
cur[field] = data
} else {
next := bson.M{}
cur[field] = next
cur = next
}
}
return sel
}
func processRelated(session *mgo.Session, bulk *elastic.BulkProcessor, elastic *elastic.Client, config *configOptions, root *gtm.Op, out *outputChans) (err error) {
var q []*gtm.Op
batch := []*gtm.Op{root}
depth := 1
s := session.Copy()
if config.DirectReadNoTimeout {
s.SetCursorTimeout(0)
}
defer s.Close()
for len(batch) > 0 {
for _, e := range batch {
op := e
if op.Data == nil {
continue
}
rs := relates[op.Namespace]
if len(rs) == 0 {
continue
}
for _, r := range rs {
if r.MaxDepth > 0 && r.MaxDepth < depth {
continue
}
if op.IsDelete() && r.IsIdentity() {
rop := >m.Op{
Id: op.Id,
Operation: op.Operation,
Namespace: r.WithNamespace,
Source: op.Source,
Timestamp: op.Timestamp,
Data: op.Data,
}
doDelete(config, elastic, session, bulk, rop)
q = append(q, rop)
continue
}
var srcData interface{}
if srcData, err = extractData(r.SrcField, op.Data); err != nil {
processErr(err, config)
continue
}
sel := buildSelector(r.MatchField, srcData)
col := s.DB(r.db).C(r.col)
query := col.Find(sel)
iter := query.Iter()
doc := map[string]interface{}{}
for iter.Next(doc) {
now := time.Now().UTC()
tstamp := bson.MongoTimestamp(now.Unix() << 32)
offset := bson.MongoTimestamp(now.Nanosecond())
rop := >m.Op{
Id: doc["_id"],
Data: doc,
Operation: root.Operation,
Namespace: r.WithNamespace,
Source: gtm.DirectQuerySource,