/
process.go
994 lines (864 loc) · 29.1 KB
/
process.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
// =================================================================
//
// Copyright (C) 2018 Spatial Current, Inc. - All Rights Reserved
// Released as open source under the MIT License. See LICENSE file.
//
// =================================================================
package cli
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/csv"
"encoding/json"
"fmt"
"github.com/pkg/errors"
"io"
"os"
"path/filepath"
"reflect"
"strings"
"sync"
"time"
"unicode"
)
import (
"github.com/mitchellh/go-homedir"
"github.com/spatialcurrent/cobra"
"github.com/spatialcurrent/viper"
)
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/athena"
"github.com/aws/aws-sdk-go/service/s3"
)
import (
"github.com/spatialcurrent/go-dfl/dfl"
"github.com/spatialcurrent/go-reader-writer/grw"
"github.com/spatialcurrent/go-simple-serializer/gss"
//rerrors "github.com/spatialcurrent/railgun/railgun/errors"
"github.com/spatialcurrent/railgun/railgun/athenaiterator"
"github.com/spatialcurrent/railgun/railgun/config"
"github.com/spatialcurrent/railgun/railgun/logger"
"github.com/spatialcurrent/railgun/railgun/util"
)
var GO_RAILGUN_COMPRESSION_ALGORITHMS = []string{"none", "bzip2", "gzip", "snappy"}
var GO_RAILGUN_DEFAULT_SALT = "4F56C8C88B38CD8CD96BF8A9724F4BFE"
var processViper = viper.New()
//outputUri string, outputCompression string, outputAppend bool, outputPassphrase string, outputSalt string,
func processOutput(content string, output *config.Output, s3_client *s3.S3) error {
if output.Uri == "stdout" {
if output.IsEncrypted() {
return errors.New("encryption only works with file output")
}
fmt.Println(content)
} else if output.Uri == "stderr" {
if output.IsEncrypted() {
return errors.New("encryption only works with file output")
}
fmt.Fprintf(os.Stderr, content)
} else {
outputWriter, err := grw.WriteToResource(output.Uri, output.Compression, output.Append, s3_client)
if err != nil {
return errors.Wrap(err, "error opening output file")
}
if output.IsEncrypted() {
outputBlock, err := util.CreateCipher(output.Salt, output.Passphrase)
if err != nil {
return errors.New("error creating cipher for output passphrase")
}
outputPlainText := []byte(content + "\n")
outputCipherText := make([]byte, aes.BlockSize+len(outputPlainText))
iv := outputCipherText[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return errors.Wrap(err, "error generating iv")
}
outputStream := cipher.NewCFBEncrypter(outputBlock, iv)
outputStream.XORKeyStream(outputCipherText[aes.BlockSize:], outputPlainText)
_, err = outputWriter.Write(outputCipherText)
if err != nil {
return errors.Wrap(err, "error writing encrypted data to output file")
}
} else {
_, err = outputWriter.WriteLine(content)
if err != nil {
return errors.Wrap(err, "error writing string to output file")
}
}
err = outputWriter.Close()
if err != nil {
return errors.Wrap(err, "error closing output file.")
}
}
return nil
}
func processObject(object interface{}, node dfl.Node, vars map[string]interface{}) (interface{}, error) {
if node != nil {
_, o, err := node.Evaluate(
vars,
object,
dfl.DefaultFunctionMap,
[]string{"'", "\"", "`"})
if err != nil {
return "", errors.Wrap(err, "error evaluating filter")
}
return gss.StringifyMapKeys(o), nil
}
return object, nil
}
func buildOptions(inputLine []byte, inputFormat string, inputHeader []string, inputComment string, inputLazyQuotes bool) (gss.Options, error) {
options := gss.Options{
Header: inputHeader,
Comment: inputComment,
LazyQuotes: inputLazyQuotes,
SkipLines: 0,
Limit: 1,
}
if inputFormat == "csv" || inputFormat == "tsv" {
options.Format = inputFormat
options.Type = reflect.TypeOf(map[string]interface{}{})
return options, nil
}
if inputFormat == "jsonl" {
options.Format = "json"
if str := strings.TrimLeftFunc(string(inputLine), unicode.IsSpace); len(str) > 0 && str[0] == '[' {
options.Type = reflect.TypeOf([]interface{}{})
}
options.Type = reflect.TypeOf(map[string]interface{}{})
return options, nil
}
return options, errors.New("invalid input format for handleInput " + inputFormat)
}
func handleInput(inputLines chan []byte, input *config.Input, node dfl.Node, vars map[string]interface{}, outputObjects chan interface{}, outputFormat string, errorsChannel chan error, verbose bool) error {
go func() {
for inputLine := range inputLines {
options, err := buildOptions(
inputLine,
input.Format,
input.Header,
input.Comment,
input.LazyQuotes)
if err != nil {
errorsChannel <- errors.Wrap(err, "invalid options for input line "+string(inputLine))
continue
}
inputObject, err := options.DeserializeBytes(inputLine, verbose)
if err != nil {
errorsChannel <- errors.Wrap(err, "error deserializing input using options "+fmt.Sprint(options))
continue
}
outputObject, err := processObject(inputObject, node, vars)
if err != nil {
switch err.(type) {
case *gss.ErrEmptyRow:
default:
errorsChannel <- errors.Wrap(err, "error processing object")
}
} else {
switch outputObject.(type) {
case dfl.Null:
default:
outputObjects <- outputObject
}
}
}
close(outputObjects)
}()
return nil
}
func handleOutput(output *config.Output, outputVars map[string]interface{}, objects chan interface{}, errorsChannel chan error, messages chan interface{}, fileDescriptorLimit int, wg *sync.WaitGroup, s3_client *s3.S3, verbose bool) error {
if output.Uri == "stdout" {
go func() {
for object := range objects {
line, err := formatObject(object, output.Format, output.Header)
if err != nil {
errorsChannel <- errors.Wrap(err, "error formatting object")
break
}
messages <- line
}
close(messages)
wg.Done()
}()
return nil
}
if output.Uri == "stderr" {
go func() {
for object := range objects {
line, err := formatObject(object, output.Format, output.Header)
if err != nil {
errorsChannel <- errors.Wrap(err, "error formatting object")
break
}
//fmt.Fprintf(os.Stderr, line)
messages <- line
}
close(messages)
wg.Done()
}()
return nil
}
n, err := dfl.ParseCompile(output.Uri)
if err != nil {
return errors.Wrap(err, "Error parsing dfl node.")
}
outputNode := n
outputLines := make(chan struct {
Path string
Line string
}, 1000)
outputPathBuffers := map[string]struct {
Writer grw.ByteWriteCloser
Buffer *bytes.Buffer
}{}
outputPathSemaphores := map[string]chan struct{}{}
outputFileDescriptorSemaphore := make(chan struct{}, fileDescriptorLimit)
if verbose {
fmt.Println("* created semaphores using file descriptor limit " + fmt.Sprint(fileDescriptorLimit))
}
var outputPathMutex = &sync.Mutex{}
var outputBufferMutex = &sync.Mutex{}
getOutputPathSemaphore := func(outputPathString string) chan struct{} {
outputPathMutex.Lock()
if _, ok := outputPathSemaphores[outputPathString]; !ok {
outputPathSemaphores[outputPathString] = make(chan struct{}, 1)
}
outputPathMutex.Unlock()
return outputPathSemaphores[outputPathString]
}
writeToOutputMemoryBuffer := func(outputPathString string, line string) {
outputBufferMutex.Lock()
if _, ok := outputPathBuffers[outputPathString]; !ok {
outputWriter, outputBuffer, err := grw.WriteBytes(output.Compression)
if err != nil {
panic(err)
}
outputPathBuffers[outputPathString] = struct {
Writer grw.ByteWriteCloser
Buffer *bytes.Buffer
}{Writer: outputWriter, Buffer: outputBuffer}
}
_, err := outputPathBuffers[outputPathString].Writer.WriteLine(line)
if err != nil {
panic(err)
}
outputBufferMutex.Unlock()
}
go func() {
var wgLines sync.WaitGroup
for line := range outputLines {
wgLines.Add(1)
go func(w *sync.WaitGroup, line struct {
Path string
Line string
}) {
defer w.Done()
outputPathSemaphore := getOutputPathSemaphore(line.Path)
outputFileDescriptorSemaphore <- struct{}{}
outputPathSemaphore <- struct{}{}
if output.BufferMemory {
writeToOutputMemoryBuffer(line.Path, line.Line)
} else {
if output.Mkdirs {
os.MkdirAll(filepath.Dir(line.Path), 0755)
}
outputWriter, err := grw.WriteToResource(line.Path, output.Compression, true, s3_client)
if err != nil {
<-outputPathSemaphore
<-outputFileDescriptorSemaphore
errorsChannel <- errors.Wrap(err, "error opening file at path "+line.Path)
return
}
_, err = outputWriter.WriteLine(line.Line)
if err != nil {
errorsChannel <- errors.Wrap(err, "Error writing string to output file")
}
err = outputWriter.Close()
if err != nil {
errorsChannel <- errors.Wrap(err, "Error closing output file.")
}
}
<-outputPathSemaphore
<-outputFileDescriptorSemaphore
}(&wgLines, line)
}
messages <- "* waiting for wgLines to be done"
wgLines.Wait()
messages <- "* closing output path semaphores"
for _, outputPathSemaphore := range outputPathSemaphores {
close(outputPathSemaphore)
}
messages <- "* writing buffers to files"
for outputPath, outputBuffer := range outputPathBuffers {
err := outputBuffer.Writer.Close()
if err != nil {
messages <- "* error closing output buffer for " + outputPath
}
if output.Mkdirs {
os.MkdirAll(filepath.Dir(outputPath), 0755)
}
outputWriter, err := grw.WriteToResource(outputPath, "", output.Append, s3_client)
if err != nil {
messages <- "* error opening output file at " + outputPath
}
_, err = outputWriter.Write(outputBuffer.Buffer.Bytes())
if err != nil {
messages <- "* error writing buffer to output file at " + outputPath
}
err = outputWriter.Close()
if err != nil {
messages <- "* error closing output file at " + outputPath
}
}
messages <- "* closing file descriptor semaphore"
close(outputFileDescriptorSemaphore)
messages <- "* closing messages"
close(messages)
wg.Done()
}()
if verbose {
fmt.Println("* starting to process objects")
}
go func() {
for object := range objects {
outputPath, err := processObject(object, outputNode, outputVars)
if err != nil {
errorsChannel <- errors.Wrap(err, "Error writing string to output file")
break
}
if reflect.TypeOf(outputPath).Kind() != reflect.String {
errorsChannel <- errors.Wrap(err, "output path is not a string")
break
}
outputPathString, err := homedir.Expand(outputPath.(string))
if err != nil {
errorsChannel <- errors.Wrap(err, "output path cannot be expanded")
break
}
line, err := formatObject(object, output.Format, output.Header)
if err != nil {
errorsChannel <- errors.Wrap(err, "error formatting object")
break
}
getOutputPathSemaphore(outputPathString)
outputLines <- struct {
Path string
Line string
}{Path: outputPathString, Line: line}
}
messages <- "* closing output lines"
close(outputLines)
}()
return nil
}
func formatObject(object interface{}, format string, header []string) (string, error) {
if format == "jsonl" {
str, err := gss.SerializeString(object, "json", header, gss.NoLimit)
if err != nil {
return "", errors.Wrap(err, "error serializing object")
}
return str, nil
}
str, err := gss.SerializeString(object, format, header, gss.NoLimit)
if err != nil {
return "", errors.Wrap(err, "error serializing object")
}
return str, nil
}
func processAthenaInput(inputUri string, inputLimit int, tempUri string, outputFormat string, athenaClient *athena.Athena, logger *logger.Logger, verbose bool) (interface{}, error) {
if !strings.HasPrefix(tempUri, "s3://") {
return nil, errors.New("temporary uri must be an S3 object")
}
_, queryName := grw.SplitUri(inputUri)
getNamedQueryOutput, err := athenaClient.GetNamedQuery(&athena.GetNamedQueryInput{
NamedQueryId: aws.String(queryName),
})
if err != nil {
return nil, errors.Wrap(err, "error getting named athena query")
}
startQueryExecutionOutput, err := athenaClient.StartQueryExecution(&athena.StartQueryExecutionInput{
QueryExecutionContext: &athena.QueryExecutionContext{
Database: getNamedQueryOutput.NamedQuery.Database,
},
QueryString: getNamedQueryOutput.NamedQuery.QueryString,
ResultConfiguration: &athena.ResultConfiguration{
OutputLocation: aws.String(tempUri),
},
})
if err != nil {
return nil, errors.Wrap(err, "error starting athena query")
}
queryExecutionId := startQueryExecutionOutput.QueryExecutionId
if verbose {
logger.Info(fmt.Sprintf("* waiting for athena query %s to complete", *startQueryExecutionOutput.QueryExecutionId))
}
queryExecutionState := ""
queryExecutionStateReason := ""
for i := 0; i < 36; i++ {
getQueryExecutionOutput, err := athenaClient.GetQueryExecution(&athena.GetQueryExecutionInput{
QueryExecutionId: queryExecutionId,
})
if err != nil {
return nil, errors.Wrap(err, "error waiting on athena query")
}
queryExecutionState = *getQueryExecutionOutput.QueryExecution.Status.State
if getQueryExecutionOutput.QueryExecution.Status.StateChangeReason != nil {
queryExecutionStateReason = *getQueryExecutionOutput.QueryExecution.Status.StateChangeReason
}
wait := true
switch queryExecutionState {
case "QUEUED":
case "RUNNING":
case "FAILED", "SUCCEEDED", "CANCELLED":
wait = false
}
if !wait {
break
}
if verbose {
logger.Info("* sleeping for 5 seconds")
logger.Flush()
}
time.Sleep(5 * time.Second)
}
switch queryExecutionState {
case "QUEUED":
case "RUNNING":
case "FAILED", "SUCCEEDED", "CANCELLED":
logger.Info(fmt.Sprintf("* athena query result: %s: %s", queryExecutionState, queryExecutionStateReason))
}
if len(outputFormat) == 0 {
return nil, nil // just exit if no output-format is given
}
athenaIterator, err := athenaiterator.New(athenaClient, queryExecutionId, inputLimit)
if err != nil {
return nil, errors.Wrap(err, "error creating athena iterator")
}
outputObjects := make([]map[string]interface{}, 0)
for {
line, err := athenaIterator.Next()
if err != nil {
if err == io.EOF {
break
} else {
return nil, errors.Wrap(err, "error from athena iterator")
}
}
object := map[string]interface{}{}
err = json.Unmarshal(line, &object)
if err != nil {
return nil, errors.Wrap(err, "error unmarshalling value from athena results: "+string(line))
}
outputObjects = append(outputObjects, object)
}
return outputObjects, nil
}
func processFunction(cmd *cobra.Command, args []string) {
v := processViper
v.BindPFlags(cmd.PersistentFlags())
v.BindPFlags(cmd.Flags())
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.AutomaticEnv() // set environment variables to overwrite config
util.MergeConfigs(v, v.GetStringArray("config-uri"))
verbose := v.GetBool("verbose")
if verbose {
fmt.Println("=================================================")
fmt.Println("Viper:")
fmt.Println("-------------------------------------------------")
str, err := gss.SerializeString(v.AllSettings(), "properties", []string{}, gss.NoLimit)
if err != nil {
fmt.Println("error getting all settings")
os.Exit(1)
}
fmt.Println(str)
fmt.Println("=================================================")
}
fileDescriptorLimit := v.GetInt("file-descriptor-limit")
stream := v.GetBool("stream")
processConfig := &config.Process{
AWS: &config.AWS{},
Input: &config.Input{},
Output: &config.Output{},
Temp: &config.Temp{},
Dfl: &config.Dfl{},
ErrorDestination: "",
ErrorCompression: "",
LogDestination: "",
LogCompression: "",
}
config.LoadConfigFromViper(processConfig, v)
if verbose {
fmt.Println("=================================================")
fmt.Println("Configuration:")
fmt.Println("-------------------------------------------------")
str, err := gss.SerializeString(processConfig.Map(), "yaml", gss.NoHeader, gss.NoLimit)
if err != nil {
fmt.Println("error getting all settings")
os.Exit(1)
}
fmt.Println(str)
fmt.Println("=================================================")
}
var athenaClient *athena.Athena
var s3_client *s3.S3
if processConfig.HasAWSResource() {
awsSession, err := session.NewSessionWithOptions(processConfig.AWSSessionOptions())
if err != nil {
fmt.Println(errors.Wrap(err, "error connecting to AWS"))
os.Exit(1)
}
if processConfig.HasAthenaStoredQuery() {
athenaClient = athena.New(awsSession)
}
if processConfig.HasS3Bucket() {
s3_client = s3.New(awsSession)
}
}
logger := logger.NewLoggerFromConfig(
processConfig.LogDestination,
processConfig.LogCompression,
processConfig.ErrorDestination,
processConfig.ErrorCompression,
s3_client)
errorsChannel := make(chan error, 1000)
messages := make(chan interface{}, 1000)
logger.ListenInfo(messages, nil)
if processConfig.ErrorDestination == processConfig.LogDestination {
go func(errorsChannel chan error) {
for err := range errorsChannel {
messages <- err.Error()
}
}(errorsChannel)
} else {
logger.ListenError(errorsChannel)
}
processConfig.Input.Init()
var inputReader grw.ByteReadCloser
if !processConfig.Input.IsAthenaStoredQuery() {
r, inputMetadata, err := grw.ReadFromResource(
processConfig.Input.Uri,
processConfig.Input.Compression,
processConfig.Input.ReaderBufferSize,
false,
s3_client)
if err != nil {
logger.Fatal(errors.Wrap(err, "error opening resource from uri "+processConfig.Input.Uri))
}
inputReader = r
processConfig.Output.Init()
if len(processConfig.Input.Format) == 0 {
if inputMetadata != nil {
if len(inputMetadata.ContentType) > 0 {
switch inputMetadata.ContentType {
case "application/json":
processConfig.Input.Format = "json"
case "application/vnd.geo+json":
processConfig.Input.Format = "json"
case "application/toml":
processConfig.Input.Format = "toml"
}
}
}
if len(processConfig.Input.Format) == 0 && len(processConfig.Output.Format) > 0 {
logger.Fatal("Error: Provided no --input-format and could not infer from resource.")
}
}
}
if len(processConfig.Input.Format) > 0 && len(processConfig.Output.Format) == 0 {
logger.Fatal("Error: Provided input format but no output format.")
}
//fmt.Println("Output Format:", outputFormat)
//fmt.Println("Output Compression:", outputCompression)
if stream {
if !(processConfig.Output.CanStream()) {
logger.Fatal("output format " + processConfig.Output.Format + " is not compatible with streaming")
}
if processConfig.Output.IsEncrypted() {
logger.Fatal("output passphrase is not compatible with streaming because it uses a block cipher")
}
// Stream Processing with Batch Input
if processConfig.Input.IsAthenaStoredQuery() || processConfig.Input.IsEncrypted() || !(processConfig.Input.CanStream()) {
var inputObjects interface{}
if processConfig.Input.IsAthenaStoredQuery() {
objects, err := processAthenaInput(
processConfig.Input.Uri,
processConfig.Input.Limit,
processConfig.Temp.Uri,
processConfig.Output.Format,
athenaClient,
logger,
verbose)
if err != nil {
logger.Fatal(errors.Wrap(err, "error processing athena input"))
}
inputObjects = objects
} else {
inputBytes, err := util.DecryptReader(inputReader, processConfig.Input.Passphrase, processConfig.Input.Salt)
if err != nil {
logger.Fatal(errors.Wrap(err, "error decoding input"))
}
inputType, err := gss.GetType(inputBytes, processConfig.Input.Format)
if err != nil {
logger.Fatal(errors.Wrap(err, "error getting type for input"))
}
if !(inputType.Kind() == reflect.Array || inputType.Kind() == reflect.Slice) {
logger.Fatal("input type cannot be streamed as it is not an array or slice but " + fmt.Sprint(inputType))
}
options := processConfig.InputOptions()
options.Type = inputType
objects, err := options.DeserializeBytes(inputBytes, verbose)
//objects, err := gss.DeserializeBytes(inputBytesPlain, inputConfig.Format, inputConfig.Header, inputConfig.Comment, inputConfig.LazyQuotes, inputConfig.SkipLines, inputConfig.Limit, inputType, verbose)
if err != nil {
logger.Fatal(errors.Wrap(err, "error deserializing input using format "+processConfig.Input.Format))
}
inputObjects = objects
}
dflNode, err := processConfig.Dfl.Node()
if err != nil {
logger.Fatal(errors.Wrap(err, "error parsing"))
}
dflVars, err := processConfig.Dfl.Variables()
if err != nil {
logger.Fatal(err)
}
var wgObjects sync.WaitGroup
var wgMessages sync.WaitGroup
fatals := make(chan error, 1000)
outputObjects := make(chan interface{}, 1000)
//messages := make(chan interface, 1000)
wgObjects.Add(1)
wgMessages.Add(1)
logger.ListenFatal(fatals)
logger.ListenInfo(messages, &wgMessages)
handleOutput(
processConfig.Output,
dflVars,
outputObjects,
fatals,
messages,
fileDescriptorLimit,
&wgObjects,
s3_client,
verbose)
inputObjectsValue := reflect.ValueOf(inputObjects)
inputObjectsLength := inputObjectsValue.Len()
for i := 0; i < inputObjectsLength; i++ {
output, err := processObject(inputObjectsValue.Index(i).Interface(), dflNode, dflVars)
if err != nil {
logger.Fatal(errors.Wrap(err, "error processing object"))
}
switch output.(type) {
case dfl.Null:
default:
outputObjects <- output
}
}
close(outputObjects)
wgObjects.Wait()
wgMessages.Wait()
logger.Close()
return
}
//dflNode, err := util.ParseDfl(dflUri, dflExpression)
dflNode, err := processConfig.Dfl.Node()
if err != nil {
logger.Fatal(errors.Wrap(err, "error parsing"))
}
dflVars, err := processConfig.Dfl.Variables()
if err != nil {
logger.Fatal(err)
}
if len(processConfig.Input.Header) == 0 && (processConfig.Input.Format == "csv" || processConfig.Input.Format == "tsv") {
inputBytes, err := inputReader.ReadBytes('\n')
if err != nil {
logger.Fatal(errors.Wrap(err, "error reading header from resource"))
}
csvReader := csv.NewReader(bytes.NewReader(inputBytes))
if processConfig.Input.Format == "tsv" {
csvReader.Comma = '\t'
}
csvReader.LazyQuotes = processConfig.Input.LazyQuotes
if len(processConfig.Input.Comment) > 1 {
logger.Fatal("go's encoding/csv package only supports single character comment characters")
} else if len(processConfig.Input.Comment) == 1 {
csvReader.Comment = []rune(processConfig.Input.Comment)[0]
}
h, err := csvReader.Read()
if err != nil {
if err != io.EOF {
logger.Fatal(errors.Wrap(err, "Error reading header from input with format csv"))
}
}
processConfig.Input.Header = h
}
var wgObjects sync.WaitGroup
var wgMessages sync.WaitGroup
errorsChannel := make(chan error, 1000)
messages := make(chan interface{}, 1000)
inputLines := make(chan []byte, 1000)
outputObjects := make(chan interface{}, 1000)
wgObjects.Add(1)
wgMessages.Add(1)
logger.ListenFatal(errorsChannel)
logger.ListenInfo(messages, &wgMessages)
handleInput(
inputLines,
processConfig.Input,
dflNode,
dflVars,
outputObjects,
processConfig.Output.Format,
errorsChannel,
verbose)
handleOutput(
processConfig.Output,
dflVars,
outputObjects,
errorsChannel,
messages,
fileDescriptorLimit,
&wgObjects,
s3_client,
verbose)
inputCount := 0
for {
inputBytes, err := inputReader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
break
} else {
logger.Fatal("error reading line from resource")
}
}
inputLines <- inputBytes
inputCount += 1
if processConfig.Input.Limit > 0 && inputCount >= processConfig.Input.Limit {
break
}
}
err = inputReader.Close()
if err != nil {
errorsChannel <- errors.Wrap(err, "error closing input")
}
close(inputLines)
wgObjects.Wait()
wgMessages.Wait()
logger.Close()
return
}
// Batch Processing
outputString := ""
if processConfig.Input.IsAthenaStoredQuery() {
outputObjects, err := processAthenaInput(
processConfig.Input.Uri,
processConfig.Input.Limit,
processConfig.Temp.Uri,
processConfig.Output.Format,
athenaClient,
logger, verbose)
if err != nil {
logger.Fatal(errors.Wrap(err, "error processing athena input"))
}
if len(processConfig.Output.Format) == 0 {
return // just exit if no output-format is given
}
str, err := gss.SerializeString(
outputObjects,
processConfig.Output.Format,
processConfig.Output.Header,
processConfig.Output.Limit)
if err != nil {
logger.Fatal(errors.Wrap(err, "error converting input"))
}
outputString = str
} else {
dflVars, err := processConfig.Dfl.Variables()
if err != nil {
logger.Fatal(err)
}
inputBytes, err := util.DecryptReader(inputReader, processConfig.Input.Passphrase, processConfig.Input.Salt)
if err != nil {
logger.Fatal(errors.Wrap(err, "error decrypting input"))
}
if len(processConfig.Output.Format) > 0 {
dflNode, err := processConfig.Dfl.Node()
if err != nil {
logger.Fatal(errors.Wrap(err, "error parsing"))
}
inputType, err := gss.GetType(inputBytes, processConfig.Input.Format)
if err != nil {
logger.Fatal(errors.Wrap(err, "error getting type for input"))
}
options := processConfig.Input.Options()
options.Type = inputType
inputObject, err := options.DeserializeBytes(inputBytes, verbose)
if err != nil {
logger.Fatal(errors.Wrap(err, "error deserializing input using format "+processConfig.Input.Format))
}
var outputObject interface{}
if dflNode != nil {
_, filterObject, err := dflNode.Evaluate(dflVars, inputObject, dfl.DefaultFunctionMap, []string{"'", "\"", "`"})
if err != nil {
logger.Fatal(errors.Wrap(err, "error evaluating filter"))
}
outputObject = filterObject
} else {
outputObject = inputObject
}
str, err := processConfig.OutputOptions().SerializeString(gss.StringifyMapKeys(outputObject))
if err != nil {
logger.Fatal(errors.Wrap(err, "error converting input"))
}
outputString = str
} else {
outputString = string(inputBytes)
}
}
err := processOutput(outputString, processConfig.Output, s3_client)
if err != nil {
logger.Fatal(errors.Wrap(err, "error processing output"))
}
logger.Close()
}
// processCmd represents the process command
var processCmd = &cobra.Command{
Use: "process",
Short: "process input data using provided DFL expression",
Run: processFunction,
}
func init() {
rootCmd.AddCommand(processCmd)
processCmd.Flags().BoolP("dry-run", "", false, "parse and compile expression, but do not evaluate against context")
processCmd.Flags().BoolP("pretty", "p", false, "print pretty output")
processCmd.Flags().BoolP("stream", "s", false, "stream process (context == row rather than encompassing array)")
// Input Flags
processCmd.Flags().StringP("input-uri", "i", "stdin", "the input uri")
processCmd.Flags().StringP("input-compression", "", "", "the input compression: "+strings.Join(GO_RAILGUN_COMPRESSION_ALGORITHMS, ", "))
processCmd.Flags().String("input-format", "", "the input format: "+strings.Join(gss.Formats, ", "))
processCmd.Flags().StringSlice("input-header", []string{}, "the input header, if the stdin input has no header.")
processCmd.Flags().StringP("input-comment", "c", "", "the comment character for the input, e.g, #")
processCmd.Flags().Bool("input-lazy-quotes", false, "allows lazy quotes for CSV and TSV")
processCmd.Flags().String("input-passphrase", "", "input passphrase for AES-256 encryption")
processCmd.Flags().String("input-salt", GO_RAILGUN_DEFAULT_SALT, "input salt for AES-256 encryption")
processCmd.Flags().Int("input-reader-buffer-size", 4096, "the buffer size for the input reader")
processCmd.Flags().Int("input-skip-lines", gss.NoSkip, "the number of lines to skip before processing")
processCmd.Flags().Int("input-limit", gss.NoLimit, "maximum number of objects to read from input")
processCmd.Flags().String("temp-uri", "", "the temporary uri for storing results")
// Output Flags
processCmd.Flags().StringP("output-uri", "o", "stdout", "the output uri (a dfl expression itself)")
processCmd.Flags().StringP("output-compression", "", "", "the output compression: "+strings.Join(GO_RAILGUN_COMPRESSION_ALGORITHMS, ", "))
processCmd.Flags().StringP("output-format", "", "", "the output format: "+strings.Join(gss.Formats, ", "))
processCmd.Flags().StringSliceP("output-header", "", []string{}, "the output header")
processCmd.Flags().StringP("output-passphrase", "", "", "output passphrase for AES-256 encryption")
processCmd.Flags().StringP("output-salt", "", "", "output salt for AES-256 encryption")
processCmd.Flags().IntP("output-limit", "", gss.NoLimit, "maximum number of objects to send to output")
processCmd.Flags().BoolP("output-append", "", false, "append to output files")
processCmd.Flags().Bool("output-buffer-memory", false, "buffer output in memory")
processCmd.Flags().Bool("output-mkdirs", false, "make directories if missing for output files")
// DFL Flags
processCmd.Flags().StringP("dfl-expression", "", "", "DFL expression to use")
processCmd.Flags().StringP("dfl-uri", "", "", "URI to DFL file to use")
processCmd.Flags().StringP("dfl-vars", "", "", "initial variables to use when evaluating DFL expression")
}