-
Notifications
You must be signed in to change notification settings - Fork 183
/
monstache.go
5378 lines (5113 loc) · 153 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"
"context"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"math"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"path/filepath"
"plugin"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"text/template"
"time"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/rwynn/monstache/v6/pkg/oplog"
"github.com/BurntSushi/toml"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/defaults"
"github.com/coreos/go-systemd/daemon"
jsonpatch "github.com/evanphx/json-patch"
"github.com/fsnotify/fsnotify"
"github.com/olivere/elastic/v7"
aws "github.com/olivere/elastic/v7/aws/v4"
"github.com/robertkrimen/otto"
_ "github.com/robertkrimen/otto/underscore"
"github.com/rwynn/gtm/v2"
"github.com/rwynn/gtm/v2/consistent"
"github.com/rwynn/monstache/v6/monstachemap"
"go.mongodb.org/mongo-driver/bson"
"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/gridfs"
"go.mongodb.org/mongo-driver/mongo/options"
mongoversion "go.mongodb.org/mongo-driver/version"
"go.mongodb.org/mongo-driver/x/bsonx/bsoncore"
"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 = make(map[string]*executionEnv)
var filterEnvs = make(map[string]*executionEnv)
var pipeEnvs = make(map[string]*executionEnv)
var mapIndexTypes = make(map[string]*indexMapping)
var relates = make(map[string][]*relation)
var fileNamespaces = make(map[string]bool)
var patchNamespaces = make(map[string]bool)
var tmNamespaces = make(map[string]bool)
var routingNamespaces = make(map[string]bool)
var mux sync.Mutex
var chunksRegex = regexp.MustCompile(`\.chunks$`)
var systemsRegex = regexp.MustCompile(`system\..+$`)
var exitStatus = 0
const version = "6.7.19"
const mongoURLDefault string = "mongodb://localhost:27017"
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 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 awsCredentialStrategy int
const (
awsCredentialStrategyStatic = iota
awsCredentialStrategyFile
awsCredentialStrategyEnv
awsCredentialStrategyEndpoint
awsCredentialStrategyChained
awsCredentialStrategyWebIdentity
)
type deleteStrategy int
const (
statelessDeleteStrategy deleteStrategy = iota
statefulDeleteStrategy
ignoreDeleteStrategy
)
type resumeStrategy int
const (
timestampResumeStrategy resumeStrategy = iota
tokenResumeStrategy
)
type buildInfo struct {
Version string
VersionArray []int `bson:"versionArray"`
}
type stringargs []string
type indexClient struct {
gtmCtx *gtm.OpCtxMulti
config *configOptions
mongo *mongo.Client
mongoWriter *mongo.Client
mongoConfig *mongo.Client
bulk *elastic.BulkProcessor
bulkStats *elastic.BulkProcessor
client *elastic.Client
hsc *httpServerCtx
fileWg *sync.WaitGroup
indexWg *sync.WaitGroup
processWg *sync.WaitGroup
relateWg *sync.WaitGroup
opsConsumed chan bool
closeC chan bool
doneC chan int
enabled bool
lastTs primitive.Timestamp
lastTsSaved primitive.Timestamp
tokens bson.M
indexC chan *gtm.Op
processC chan *gtm.Op
fileC chan *gtm.Op
relateC chan *gtm.Op
filter gtm.OpFilter
statusReqC chan *statusRequest
sigH *sigHandler
oplogTsResolver oplog.TimestampResolver
directReadsPending bool
externalShutdown bool
rwmutex sync.RWMutex
bulkErrs atomic.Int64
bulkBackoff elastic.Backoff
bulkBackoffC chan time.Duration
bulkBackoffMax time.Duration
}
type sigHandler struct {
clientStartedC chan *indexClient
}
type awsConnect struct {
Strategy awsCredentialStrategy
AccessKey string `toml:"access-key"`
SecretKey string `toml:"secret-key"`
Region string
Profile string
CredentialsFile string `toml:"credentials-file"`
CredentialsWatchDir string `toml:"credentials-watch-dir"`
WatchCredentials bool `toml:"watch-credentials"`
ForceExpire string `toml:"force-expire"`
creds *credentials.Credentials
}
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"`
DotNotation bool `toml:"dot-notation"`
KeepSrc bool `toml:"keep-src"`
MaxDepth int `toml:"max-depth"`
MatchFieldType string `toml:"match-field-type"`
db string
col string
}
type indexMapping struct {
Namespace string
Index string
Pipeline string
}
type findConf struct {
vm *otto.Otto
ns string
name string
client *mongo.Client
byID bool
multi bool
pipe bool
pipeAllowDisk bool
}
type findCall struct {
config *findConf
client *mongo.Client
query interface{}
db string
col string
limit int
sort map[string]int
sel map[string]int
}
type logRotate struct {
MaxSize int `toml:"max-size"`
MaxAge int `toml:"max-age"`
MaxBackups int `toml:"max-backups"`
LocalTime bool `toml:"localtime"`
Compress bool `toml:"compress"`
}
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 gtmSettings struct {
ChannelSize int `toml:"channel-size"`
BufferSize int `toml:"buffer-size"`
BufferDuration string `toml:"buffer-duration"`
MaxAwaitTime string `toml:"max-await-time"`
}
type elasticPKIAuth struct {
CertFile string `toml:"cert-file"`
KeyFile string `toml:"key-file"`
}
type httpServerCtx struct {
httpServer *http.Server
bulk *elastic.BulkProcessor
config *configOptions
shutdown bool
started time.Time
statusReqC chan *statusRequest
}
type instanceStatus struct {
Enabled bool `json:"enabled"`
Pid int `json:"pid"`
Hostname string `json:"hostname"`
ClusterName string `json:"cluster"`
ResumeName string `json:"resumeName"`
LastTs primitive.Timestamp `json:"lastTs"`
LastTsFormat string `json:"lastTsFormat,omitempty"`
Backoff bool `json:"inBackoff,omitempty"`
}
type statusResponse struct {
enabled bool
lastTs primitive.Timestamp
backoff bool
}
type statusRequest struct {
responseC chan *statusResponse
}
type configOptions struct {
EnableTemplate bool
EnvDelimiter string
MongoURL string `toml:"mongo-url"`
MongoWriteURL string `toml:"mongo-write-url"`
MongoConfigURL string `toml:"mongo-config-url"`
MongoOpLogDatabaseName string `toml:"mongo-oplog-database-name"`
MongoOpLogCollectionName string `toml:"mongo-oplog-collection-name"`
GtmSettings gtmSettings `toml:"gtm-settings"`
AWSConnect awsConnect `toml:"aws-connect"`
LogRotate logRotate `toml:"log-rotate"`
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"`
ElasticPKIAuth elasticPKIAuth `toml:"elasticsearch-pki-auth"`
ElasticAPIKey string `toml:"elasticsearch-api-key"`
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
EnableOplog bool `toml:"enable-oplog"`
DisableChangeEvents bool `toml:"disable-change-events"`
DisableDeleteProtection bool `toml:"disable-delete-protection"`
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
ResumeStrategy resumeStrategy `toml:"resume-strategy"`
ResumeWriteUnsafe bool `toml:"resume-write-unsafe"`
ResumeFromTimestamp int64 `toml:"resume-from-timestamp"`
ResumeFromEarliestTimestamp bool `toml:"resume-from-earliest-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"`
DisableFilePipelinePut bool `toml:"disable-file-pipeline-put"`
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 []indexMapping
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"`
DirectReadBounded bool `toml:"direct-read-bounded"`
DirectReadStateful bool `toml:"direct-read-stateful"`
DirectReadExcludeRegex string `toml:"direct-read-dynamic-exclude-regex"`
DirectReadIncludeRegex string `toml:"direct-read-dynamic-include-regex"`
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
mongoClientOptions *options.ClientOptions
}
type ElasticAPIKeyTransport struct {
apiKey string
next http.RoundTripper
}
func (tr *ElasticAPIKeyTransport) RoundTrip(r *http.Request) (*http.Response, error) {
r.Header.Set("Authorization", fmt.Sprintf("ApiKey %s", tr.apiKey))
return tr.next.RoundTrip(r)
}
func (eca elasticPKIAuth) enabled() bool {
return eca.CertFile != "" || eca.KeyFile != ""
}
func (eca elasticPKIAuth) validate() error {
if eca.CertFile != "" && eca.KeyFile == "" {
return errors.New("Elasticsearch client auth key file is empty")
}
if eca.CertFile == "" && eca.KeyFile != "" {
return errors.New("Elasticsearch client auth cert file is empty")
}
return nil
}
func (rel *relation) IsIdentity() bool {
if rel.SrcField == "_id" && rel.MatchField == "_id" {
return true
}
return false
}
func (l *logFiles) enabled() bool {
return l.Info != "" || l.Warn != "" || l.Error != "" || l.Trace != "" || l.Stats != ""
}
func (ac *awsConnect) validate() error {
if ac.Strategy == awsCredentialStrategyStatic {
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")
}
return nil
}
func (ac *awsConnect) enabled() bool {
if ac.Strategy == awsCredentialStrategyStatic {
return ac.AccessKey != "" || ac.SecretKey != ""
}
return true
}
func (ac *awsConnect) forceExpireCreds() bool {
return ac.enabled() && ac.ForceExpire != "" && ac.creds != nil
}
func (ac *awsConnect) watchCreds() bool {
if ac.enabled() && ac.creds != nil && ac.WatchCredentials {
return ac.Strategy == awsCredentialStrategyFile || ac.Strategy == awsCredentialStrategyChained
}
return false
}
func (ac *awsConnect) watchFilePath() string {
if ac.CredentialsWatchDir != "" {
return ac.CredentialsWatchDir
}
var homeDir string
if runtime.GOOS == "windows" { // Windows
homeDir = os.Getenv("USERPROFILE")
} else {
homeDir = os.Getenv("HOME")
}
return filepath.Join(homeDir, ".aws")
}
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 (arg *resumeStrategy) String() string {
return fmt.Sprintf("%d", *arg)
}
func (arg *resumeStrategy) Set(value string) (err error) {
var i int
if i, err = strconv.Atoi(value); err != nil {
return
}
rs := resumeStrategy(i)
*arg = rs
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 (config *configOptions) dynamicDirectReadList() bool {
return len(config.DirectReadNs) == 1 && config.DirectReadNs[0] == ""
}
func (config *configOptions) ignoreDatabaseForDirectReads(db string) bool {
return db == "local" || db == "admin" || db == "config" || db == config.ConfigDatabaseName
}
func (config *configOptions) ignoreCollectionForDirectReads(col string) bool {
return strings.HasPrefix(col, "system.")
}
func (ic *indexClient) afterBulk() func(int64, []elastic.BulkableRequest, *elastic.BulkResponse, error) {
return func(executionID int64, requests []elastic.BulkableRequest, response *elastic.BulkResponse, err error) {
if response == nil || !response.Errors {
ic.bulkErrs.Store(0)
return
}
if failed := response.Failed(); failed != nil {
backoff := false
for _, item := range failed {
if item.Status == http.StatusConflict {
// ignore version conflict since this simply means the doc
// is already in the index
continue
}
logFailedResponseItem(item)
if item.Status == http.StatusNotFound {
// status not found should not initiate back off
continue
}
backoff = true
}
if backoff {
wait := ic.backoffDuration()
infoLog.Printf("Backing off for %.1f minutes after bulk indexing failures.", wait.Minutes())
// signal the event loop to pause pulling new events for a duration
ic.bulkBackoffC <- wait
// pause the bulk worker for a duration
ic.backoff(wait)
ic.bulkErrs.Add(1)
}
}
}
}
func logFailedResponseItem(item *elastic.BulkResponseItem) {
if encoded, err := json.Marshal(item); err == nil {
errorLog.Printf("Bulk response item: %s", string(encoded))
} else {
errorLog.Printf("Unable to marshal bulk response item: %s", err)
}
}
func (ic *indexClient) backoffDuration() time.Duration {
consecutiveErrors := int(ic.bulkErrs.Load())
wait, ok := ic.bulkBackoff.Next(consecutiveErrors)
if !ok {
wait = ic.bulkBackoffMax
}
return wait
}
func (ic *indexClient) backoff(wait time.Duration) {
timer := time.NewTimer(wait)
defer timer.Stop()
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigs)
for {
select {
case <-timer.C:
return
case <-sigs:
return
case req := <-ic.statusReqC:
enabled, lastTs := ic.enabled, ic.lastTs
statusResp := &statusResponse{
enabled: enabled,
lastTs: lastTs,
backoff: true,
}
req.responseC <- statusResp
}
}
}
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 (ic *indexClient) newBulkProcessor(client *elastic.Client) (bulk *elastic.BulkProcessor, err error) {
config := ic.config
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(ic.afterBulk())
bulkService.FlushInterval(time.Duration(config.ElasticMaxSeconds) * time.Second)
return bulkService.Do(context.Background())
}
func (ic *indexClient) 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(ic.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 (ic *indexClient) deleteIndexes(db string) (err error) {
var indices = []string{strings.ToLower(db + ".*")}
for ns, m := range mapIndexTypes {
dbCol := strings.SplitN(ns, ".", 2)
if dbCol[0] == db && m.Index != "" {
index := strings.ToLower(m.Index)
for _, cur := range indices {
if cur == index {
index = ""
break
}
}
if index != "" {
indices = append(indices, index)
}
}
}
_, err = ic.client.DeleteIndex(indices...).Do(context.Background())
return
}
func (ic *indexClient) deleteIndex(namespace string) (err error) {
ctx := context.Background()
index := strings.ToLower(namespace)
if m := mapIndexTypes[namespace]; m != nil {
if m.Index != "" {
index = strings.ToLower(m.Index)
}
}
_, err = ic.client.DeleteIndex(index).Do(ctx)
return err
}
func (ic *indexClient) ensureFileMapping() (err error) {
config := ic.config
if config.DisableFilePipelinePut {
return nil
}
ctx := context.Background()
pipeline := map[string]interface{}{
"description": "Extract file information",
"processors": [1]map[string]interface{}{
{
"attachment": map[string]interface{}{
"field": "file",
},
},
},
}
_, err = ic.client.IngestPutPipeline("attachment").BodyJson(pipeline).Do(ctx)
return err
}
func (ic *indexClient) defaultIndexMapping(op *gtm.Op) *indexMapping {
return &indexMapping{
Namespace: op.Namespace,
Index: strings.ToLower(op.Namespace),
}
}
func (ic *indexClient) mapIndex(op *gtm.Op) *indexMapping {
mapping := ic.defaultIndexMapping(op)
if m := mapIndexTypes[op.Namespace]; m != nil {
if m.Index != "" {
mapping.Index = m.Index
}
if m.Pipeline != "" {
mapping.Pipeline = m.Pipeline
}
}
return mapping
}
func opIDToString(op *gtm.Op) string {
var opIDStr string
switch id := op.Id.(type) {
case primitive.ObjectID:
opIDStr = id.Hex()
case primitive.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{} {
avs := make([]interface{}, 0, len(a))
for _, av := range a {
var avc interface{}
switch achild := av.(type) {
case map[string]interface{}:
avc = convertMapJavascript(achild)
case []interface{}:
avc = convertSliceJavascript(achild)
case primitive.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{}, len(e))
for k, v := range e {
switch child := v.(type) {
case map[string]interface{}:
o[k] = convertMapJavascript(child)
case []interface{}:
o[k] = convertSliceJavascript(child)
case primitive.ObjectID:
o[k] = child.Hex()
default:
o[k] = v
}
}
return o
}
func fixSlicePruneInvalidJSON(id string, key string, a []interface{}) []interface{} {
avs := make([]interface{}, 0, len(a))
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{}, len(e))
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{} {
avs := make([]interface{}, 0, len(a))
for _, av := range a {
avs = append(avs, deepExportMap(av))
}
return avs
}
func deepExportSlice(a []interface{}) []interface{} {
avs := make([]interface{}, 0, len(a))
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{}, len(e))
for k, v := range e {
o[k] = deepExportValue(v)
}
return o
}