forked from rwynn/monstache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
monstache.go
2841 lines (2700 loc) · 82.8 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"
"github.com/BurntSushi/toml"
"github.com/coreos/go-systemd/daemon"
"github.com/evanphx/json-patch"
"github.com/globalsign/mgo"
"github.com/globalsign/mgo/bson"
"github.com/olivere/elastic"
"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"
"io"
"io/ioutil"
"log"
"math"
"net"
"net/http"
"os"
"os/signal"
"plugin"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
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 mapEnvs map[string]*executionEnv = make(map[string]*executionEnv)
var filterEnvs map[string]*executionEnv = make(map[string]*executionEnv)
var mapIndexTypes map[string]*indexTypeMapping = make(map[string]*indexTypeMapping)
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 chunksRegex = regexp.MustCompile("\\.chunks$")
var systemsRegex = regexp.MustCompile("system\\..+$")
const version = "4.6.4"
const mongoURLDefault string = "localhost"
const resumeNameDefault string = "default"
const elasticMaxConnsDefault int = 4
const elasticClientTimeoutDefault int = 60
const elasticMaxDocsDefault int = -1
const elasticMaxBytesDefault int = 8 * 1024 * 1024
const gtmChannelSizeDefault int = 512
const typeFromFuture string = "_doc"
const fileDownloadersDefault = 10
type deleteStrategy int
const (
statelessDeleteStrategy deleteStrategy = iota
statefulDeleteStrategy
ignoreDeleteStrategy
)
type stringargs []string
type executionEnv struct {
VM *otto.Otto
Script string
lock *sync.Mutex
}
type javascript struct {
Namespace string
Script string
Path string
Routing bool
}
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
}
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
}
type mongoDialSettings struct {
Timeout int
Ssl bool
}
type mongoSessionSettings struct {
SocketTimeout int `toml:"socket-timeout"`
SyncTimeout int `toml:"sync-timeout"`
}
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
}
type configOptions struct {
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"`
MongoCursorTimeout string `toml:"mongo-cursor-timeout"`
MongoDialSettings mongoDialSettings `toml:"mongo-dial-settings"`
MongoSessionSettings mongoSessionSettings `toml:"mongo-session-settings"`
GtmSettings gtmSettings `toml:"gtm-settings"`
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"`
ResumeName string `toml:"resume-name"`
NsRegex string `toml:"namespace-regex"`
NsExcludeRegex string `toml:"namespace-exclude-regex"`
ClusterName string `toml:"cluster-name"`
Print bool `toml:"print-config"`
Version bool
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"`
FileHighlighting bool `toml:"file-highlighting"`
EnablePatches bool `toml:"enable-patches"`
FailFast bool `toml:"fail-fast"`
IndexOplogTime bool `toml:"index-oplog-time"`
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
Mapping []indexTypeMapping
FileNamespaces stringargs `toml:"file-namespaces"`
PatchNamespaces stringargs `toml:"patch-namespaces"`
Workers stringargs
Worker string
DirectReadNs stringargs `toml:"direct-read-namespaces"`
DirectReadSplitMax int `toml:"direct-read-split-max"`
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"`
RoutingNamespaces stringargs `toml:"routing-namespaces"`
DeleteStrategy deleteStrategy `toml:"delete-strategy"`
DeleteIndexPattern string `toml:"delete-index-pattern"`
FileDownloaders int `toml:"file-downloaders"`
PruneInvalidJSON bool `toml:"prune-invalid-json"`
}
func (arg *deleteStrategy) String() string {
return fmt.Sprintf("%d", *arg)
}
func (arg *deleteStrategy) Set(value string) error {
if i, err := strconv.Atoi(value); err != nil {
return err
} else {
ds := deleteStrategy(i)
*arg = ds
return nil
}
}
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) isSharded() bool {
return config.MongoConfigURL != ""
}
func afterBulk(executionId int64, requests []elastic.BulkableRequest, response *elastic.BulkResponse, err error) {
if err != nil {
errorLog.Printf("Bulk index request with execution ID %d failed: %s", executionId, err)
}
if response != nil && response.Errors {
failed := response.Failed()
if failed != nil {
errorLog.Printf("Bulk index request with execution ID %d has %d line failure/warning(s)", executionId, len(failed))
for i, item := range failed {
json, err := json.Marshal(item)
if err != nil {
errorLog.Printf("Unable to marshall failed request line #%d: %s", i, err)
} else {
if item.Status == 409 {
warnLog.Printf("Conflict request line #%d details: %s", i, string(json))
} else {
errorLog.Printf("Failed request line #%d details: %s", i, 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.FlushInterval(time.Duration(5) * time.Second)
bulkService.After(afterBulk)
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.SetErrorLog(errorLog))
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))
}
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))
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 op.Id.(type) {
case bson.ObjectId:
opIDStr = op.Id.(bson.ObjectId).Hex()
case float64:
intID := int(op.Id.(float64))
if op.Id.(float64) == float64(intID) {
opIDStr = fmt.Sprintf("%v", intID)
} else {
opIDStr = fmt.Sprintf("%v", op.Id)
}
case float32:
intID := int(op.Id.(float32))
if op.Id.(float32) == 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, 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, achild)
case time.Time:
year := achild.Year()
if year < 0 || year > 9999 {
// year outside of valid range
errorLog.Printf("Dropping invalid time.Time value: %s for document _id: %s", achild, id)
continue
} else {
avc = av
}
case float64:
if math.IsNaN(achild) {
// causes an error in the json serializer
errorLog.Printf("Dropping invalid float64 value: %v for document _id: %s", achild, id)
continue
} else if math.IsInf(achild, 0) {
// causes an error in the json serializer
errorLog.Printf("Dropping invalid float64 value: %v for document _id: %s", 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, child)
case time.Time:
year := child.Year()
if year < 0 || year > 9999 {
// year outside of valid range
errorLog.Printf("Dropping invalid time.Time value: %s for document _id: %s", child, id)
continue
} else {
o[k] = v
}
case float64:
if math.IsNaN(child) {
// causes an error in the json serializer
errorLog.Printf("Dropping invalid float64 value: %v for document _id: %s", child, id)
continue
} else if math.IsInf(child, 0) {
// causes an error in the json serializer
errorLog.Printf("Dropping invalid float64 value: %v for document _id: %s", 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 []interface{}:
b = deepExportSlice(t)
default:
b = a
}
return
}
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 {
arg := convertMapJavascript(op.Data)
val, err := env.VM.Call("module.exports", arg, arg, op.Namespace)
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,
}
output, err := mapperPlugin(input)
if err != nil {
return err
}
if output != nil {
if output.Drop {
op.Data = nil
} else {
if output.Passthrough == false {
op.Data = output.Document
}
meta := make(map[string]interface{})
if output.Index != "" {
meta["index"] = output.Index
}
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 config.MapperPluginPath != "" {
return mapDataGolang(session, op)
}
return mapDataJavascript(op)
}
func prepareDataForIndexing(config *configOptions, op *gtm.Op) {
data := op.Data
if config.IndexOplogTime {
secs := int64(op.Timestamp >> 32)
t := time.Unix(secs, 0).UTC()
data["_oplog_ts"] = op.Timestamp
data["_oplog_date"] = t.Format("2006/01/02 15:04:05")
}
delete(data, "_id")
delete(data, "_meta_monstache")
if config.PruneInvalidJSON {
op.Data = fixPruneInvalidJSON(opIDToString(op), data)
}
}
func parseIndexMeta(op *gtm.Op) (meta *indexingMeta) {
meta = &indexingMeta{
Version: int64(op.Timestamp),
VersionType: "external",
}
if m, ok := op.Data["_meta_monstache"]; ok {
switch m.(type) {
case map[string]interface{}:
metaAttrs := m.(map[string]interface{})
meta.load(metaAttrs)
case otto.Value:
ex, err := m.(otto.Value).Export()
if err == nil && ex != m {
switch ex.(type) {
case map[string]interface{}:
metaAttrs := ex.(map[string]interface{})
meta.load(metaAttrs)
default:
errorLog.Println("Invalid indexing metadata")
}
}
default:
errorLog.Println("Invalid indexing metadata")
}
}
return meta
}
func addFileContent(s *mgo.Session, op *gtm.Op, config *configOptions) (err error) {
session := s.Copy()
defer session.Close()
op.Data["file"] = ""
var gridByteBuffer bytes.Buffer
db, bucket :=
session.DB(op.GetDatabase()),
strings.SplitN(op.GetCollection(), ".", 2)[0]
encoder := base64.NewEncoder(base64.StdEncoding, &gridByteBuffer)
file, err := db.GridFS(bucket).OpenId(op.Id)
if err != nil {
return
}
defer file.Close()
if config.MaxFileSize > 0 {
if file.Size() > config.MaxFileSize {
warnLog.Printf("File %s md5(%s) exceeds max file size. file content omitted.",
file.Name(), file.MD5())
return
}
}
if _, err = io.Copy(encoder, file); err != nil {
return
}
if err = encoder.Close(); err != nil {
return
}
op.Data["file"] = string(gridByteBuffer.Bytes())
return
}
func notMonstache(op *gtm.Op) bool {
return op.GetDatabase() != "monstache"
}
func notChunks(op *gtm.Op) bool {
return !chunksRegex.MatchString(op.GetCollection())
}
func notConfig(op *gtm.Op) bool {
return op.GetDatabase() != "config"
}
func notSystem(op *gtm.Op) bool {
return !systemsRegex.MatchString(op.GetCollection())
}
func filterWithRegex(regex string) gtm.OpFilter {
var validNameSpace = regexp.MustCompile(regex)
return func(op *gtm.Op) bool {
return validNameSpace.MatchString(op.Namespace)
}
}
func filterWithPlugin() gtm.OpFilter {
return func(op *gtm.Op) bool {
var keep bool = true
if (op.IsInsert() || op.IsUpdate()) && op.Data != nil {
keep = false
input := &monstachemap.MapperPluginInput{
Document: op.Data,
Namespace: op.Namespace,
Database: op.GetDatabase(),
Collection: op.GetCollection(),
Operation: op.Operation,
}
if ok, err := filterPlugin(input); err == nil {
keep = ok
} else {
errorLog.Println(err)
}
}
return keep
}
}
func filterWithScript() gtm.OpFilter {
return func(op *gtm.Op) bool {
var keep bool = true
if (op.IsInsert() || op.IsUpdate()) && op.Data != nil {
nss := []string{"", op.Namespace}
for _, ns := range nss {
if env := filterEnvs[ns]; env != nil {
keep = false
arg := convertMapJavascript(op.Data)
env.lock.Lock()
val, err := env.VM.Call("module.exports", arg, arg, op.Namespace)
if err != nil {
errorLog.Println(err)
} else {
if ok, err := val.ToBoolean(); err == nil {
keep = ok
} else {
errorLog.Println(err)
}
}
env.lock.Unlock()
}
if !keep {
break
}
}
}
return keep
}
}
func filterInverseWithRegex(regex string) gtm.OpFilter {
var invalidNameSpace = regexp.MustCompile(regex)
return func(op *gtm.Op) bool {
return !invalidNameSpace.MatchString(op.Namespace)
}
}
func ensureClusterTTL(session *mgo.Session) error {
col := session.DB("monstache").C("cluster")
return col.EnsureIndex(mgo.Index{
Key: []string{"expireAt"},
Background: true,
ExpireAfter: time.Duration(30) * time.Second,
})
}
func enableProcess(s *mgo.Session, config *configOptions) (bool, error) {
session := s.Copy()
defer session.Close()
col := session.DB("monstache").C("cluster")
doc := make(map[string]interface{})
doc["_id"] = config.ResumeName
doc["expireAt"] = time.Now().UTC()
doc["pid"] = os.Getpid()
if host, err := os.Hostname(); err == nil {
doc["host"] = host
} else {
return false, err
}
err := col.Insert(doc)
if err == nil {
return true, nil
}
if mgo.IsDup(err) {
return false, nil
}
return false, err
}
func resetClusterState(session *mgo.Session, config *configOptions) error {
col := session.DB("monstache").C("cluster")
return col.RemoveId(config.ResumeName)
}
func ensureEnabled(s *mgo.Session, config *configOptions) (enabled bool, err error) {
session := s.Copy()
defer session.Close()
col := session.DB("monstache").C("cluster")
doc := make(map[string]interface{})
if err = col.FindId(config.ResumeName).One(doc); err == nil {
if doc["pid"] != nil && doc["host"] != nil {
var hostname string
pid := doc["pid"].(int)
host := doc["host"].(string)
if hostname, err = os.Hostname(); err == nil {
enabled = (pid == os.Getpid() && host == hostname)
if enabled {
err = col.UpdateId(config.ResumeName,
bson.M{"$set": bson.M{"expireAt": time.Now().UTC()}})
}
}
}
}
return
}
func resumeWork(ctx *gtm.OpCtxMulti, session *mgo.Session, config *configOptions) {
col := session.DB("monstache").C("monstache")
doc := make(map[string]interface{})
col.FindId(config.ResumeName).One(doc)
if doc["ts"] != nil {
ts := doc["ts"].(bson.MongoTimestamp)
ctx.Since(ts)
}
ctx.Resume()
}
func saveTimestamp(s *mgo.Session, ts bson.MongoTimestamp, config *configOptions) error {
session := s.Copy()
session.SetSocketTimeout(time.Duration(5) * time.Second)
session.SetSyncTimeout(time.Duration(5) * time.Second)
if config.ResumeWriteUnsafe {
session.SetSafe(nil)
}
defer session.Close()
col := session.DB("monstache").C("monstache")
doc := make(map[string]interface{})
doc["ts"] = ts
_, err := col.UpsertId(config.ResumeName, bson.M{"$set": doc})
return err
}
func (config *configOptions) parseCommandLineFlags() *configOptions {
flag.BoolVar(&config.Print, "print-config", false, "Print the configuration and then exit")
flag.StringVar(&config.MongoURL, "mongo-url", "", "MongoDB server or router server connection URL")
flag.StringVar(&config.MongoConfigURL, "mongo-config-url", "", "MongoDB config server connection URL")
flag.StringVar(&config.MongoPemFile, "mongo-pem-file", "", "Path to a PEM file for secure connections to MongoDB")
flag.BoolVar(&config.MongoValidatePemFile, "mongo-validate-pem-file", true, "Set to boolean false to not validate the MongoDB PEM file")
flag.StringVar(&config.MongoOpLogDatabaseName, "mongo-oplog-database-name", "", "Override the database name which contains the mongodb oplog")
flag.StringVar(&config.MongoOpLogCollectionName, "mongo-oplog-collection-name", "", "Override the collection name which contains the mongodb oplog")
flag.StringVar(&config.MongoCursorTimeout, "mongo-cursor-timeout", "", "Override the duration before a cursor timeout occurs when tailing the oplog")
flag.StringVar(&config.GraylogAddr, "graylog-addr", "", "Send logs to a Graylog server at this address")
flag.StringVar(&config.ElasticVersion, "elasticsearch-version", "", "Specify elasticsearch version directly instead of getting it from the server")
flag.StringVar(&config.ElasticUser, "elasticsearch-user", "", "The elasticsearch user name for basic auth")
flag.StringVar(&config.ElasticPassword, "elasticsearch-password", "", "The elasticsearch password for basic auth")
flag.StringVar(&config.ElasticPemFile, "elasticsearch-pem-file", "", "Path to a PEM file for secure connections to elasticsearch")
flag.BoolVar(&config.ElasticValidatePemFile, "elasticsearch-validate-pem-file", true, "Set to boolean false to not validate the Elasticsearch PEM file")
flag.IntVar(&config.ElasticMaxConns, "elasticsearch-max-conns", 0, "Elasticsearch max connections")
flag.IntVar(&config.FileDownloaders, "file-downloaders", 0, "GridFs download go routines")