forked from cihub/seelog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cfg_parser.go
1238 lines (1049 loc) · 36.5 KB
/
cfg_parser.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
// Copyright (c) 2012 - Cloud Instruments Co., Ltd.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package seelog
import (
"crypto/tls"
"encoding/xml"
"errors"
"fmt"
"io"
"strconv"
"strings"
"time"
)
// Names of elements of seelog config.
const (
seelogConfigID = "seelog"
outputsID = "outputs"
formatsID = "formats"
minLevelID = "minlevel"
maxLevelID = "maxlevel"
levelsID = "levels"
exceptionsID = "exceptions"
exceptionID = "exception"
funcPatternID = "funcpattern"
filePatternID = "filepattern"
formatID = "format"
formatAttrID = "format"
formatKeyAttrID = "id"
outputFormatID = "formatid"
pathID = "path"
fileWriterID = "file"
smtpWriterID = "smtp"
senderaddressID = "senderaddress"
senderNameID = "sendername"
recipientID = "recipient"
mailHeaderID = "header"
mailHeaderNameID = "name"
mailHeaderValueID = "value"
addressID = "address"
hostNameID = "hostname"
hostPortID = "hostport"
userNameID = "username"
userPassID = "password"
cACertDirpathID = "cacertdirpath"
subjectID = "subject"
splitterDispatcherID = "splitter"
consoleWriterID = "console"
customReceiverID = "custom"
customNameAttrID = "name"
customNameDataAttrPrefix = "data-"
filterDispatcherID = "filter"
filterLevelsAttrID = "levels"
rollingfileWriterID = "rollingfile"
rollingFileTypeAttr = "type"
rollingFilePathAttr = "filename"
rollingFileMaxSizeAttr = "maxsize"
rollingFileMaxRollsAttr = "maxrolls"
rollingFileNameModeAttr = "namemode"
rollingFileDataPatternAttr = "datepattern"
rollingFileArchiveAttr = "archivetype"
rollingFileArchivePathAttr = "archivepath"
bufferedWriterID = "buffered"
bufferedSizeAttr = "size"
bufferedFlushPeriodAttr = "flushperiod"
loggerTypeFromStringAttr = "type"
asyncLoggerIntervalAttr = "asyncinterval"
adaptLoggerMinIntervalAttr = "mininterval"
adaptLoggerMaxIntervalAttr = "maxinterval"
adaptLoggerCriticalMsgCountAttr = "critmsgcount"
predefinedPrefix = "std:"
connWriterID = "conn"
connWriterAddrAttr = "addr"
connWriterNetAttr = "net"
connWriterReconnectOnMsgAttr = "reconnectonmsg"
connWriterUseTLSAttr = "tls"
connWriterInsecureSkipVerifyAttr = "insecureskipverify"
)
// CustomReceiverProducer is the signature of the function cfgParseParams needs to create
// custom receivers.
type CustomReceiverProducer func(CustomReceiverInitArgs) (CustomReceiver, error)
// cfgParseParams represent specific parse options or flags used by parser. It is used if seelog parser needs
// some special directives or additional info to correctly parse a config.
type cfgParseParams struct {
// CustomReceiverProducers expose the same functionality as RegisterReceiver func
// but only in the scope (context) of the config parse func instead of a global package scope.
//
// It means that if you use custom receivers in your code, you may either register them globally once with
// RegisterReceiver or you may call funcs like LoggerFromParamConfigAsFile (with 'ParamConfig')
// and use CustomReceiverProducers to provide custom producer funcs.
//
// A producer func is called when config parser processes a '<custom>' element. It takes the 'name' attribute
// of the element and tries to find a match in two places:
// 1) cfgParseParams.CustomReceiverProducers map
// 2) Global type map, filled by RegisterReceiver
//
// If a match is found in the CustomReceiverProducers map, parser calls the corresponding producer func
// passing the init args to it. The func takes exactly the same args as CustomReceiver.AfterParse.
// The producer func must return a correct receiver or an error. If case of error, seelog will behave
// in the same way as with any other config error.
//
// You may use this param to set custom producers in case you need to pass some context when instantiating
// a custom receiver or if you frequently change custom receivers with different parameters or in any other
// situation where package-level registering (RegisterReceiver) is not an option for you.
CustomReceiverProducers map[string]CustomReceiverProducer
}
func (cfg *cfgParseParams) String() string {
return fmt.Sprintf("CfgParams: {custom_recs=%d}", len(cfg.CustomReceiverProducers))
}
type elementMapEntry struct {
constructor func(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *cfgParseParams) (interface{}, error)
}
var elementMap map[string]elementMapEntry
var predefinedFormats map[string]*formatter
func init() {
elementMap = map[string]elementMapEntry{
fileWriterID: {createfileWriter},
splitterDispatcherID: {createSplitter},
customReceiverID: {createCustomReceiver},
filterDispatcherID: {createFilter},
consoleWriterID: {createConsoleWriter},
rollingfileWriterID: {createRollingFileWriter},
bufferedWriterID: {createbufferedWriter},
smtpWriterID: {createSMTPWriter},
connWriterID: {createconnWriter},
}
err := fillPredefinedFormats()
if err != nil {
panic(fmt.Sprintf("Seelog couldn't start: predefined formats creation failed. Error: %s", err.Error()))
}
}
func fillPredefinedFormats() error {
predefinedFormatsWithoutPrefix := map[string]string{
"xml-debug": `<time>%Ns</time><lev>%Lev</lev><msg>%Msg</msg><path>%RelFile</path><func>%Func</func><line>%Line</line>`,
"xml-debug-short": `<t>%Ns</t><l>%l</l><m>%Msg</m><p>%RelFile</p><f>%Func</f>`,
"xml": `<time>%Ns</time><lev>%Lev</lev><msg>%Msg</msg>`,
"xml-short": `<t>%Ns</t><l>%l</l><m>%Msg</m>`,
"json-debug": `{"time":%Ns,"lev":"%Lev","msg":"%Msg","path":"%RelFile","func":"%Func","line":"%Line"}`,
"json-debug-short": `{"t":%Ns,"l":"%Lev","m":"%Msg","p":"%RelFile","f":"%Func"}`,
"json": `{"time":%Ns,"lev":"%Lev","msg":"%Msg"}`,
"json-short": `{"t":%Ns,"l":"%Lev","m":"%Msg"}`,
"debug": `[%LEVEL] %RelFile:%Func.%Line %Date %Time %Msg%n`,
"debug-short": `[%LEVEL] %Date %Time %Msg%n`,
"fast": `%Ns %l %Msg%n`,
}
predefinedFormats = make(map[string]*formatter)
for formatKey, format := range predefinedFormatsWithoutPrefix {
formatter, err := NewFormatter(format)
if err != nil {
return err
}
predefinedFormats[predefinedPrefix+formatKey] = formatter
}
return nil
}
// configFromXMLDecoder parses data from a given XML decoder.
// Returns parsed config which can be used to create logger in case no errors occured.
// Returns error if format is incorrect or anything happened.
func configFromXMLDecoder(xmlParser *xml.Decoder, rootNode xml.Token) (*configForParsing, error) {
return configFromXMLDecoderWithConfig(xmlParser, rootNode, nil)
}
// configFromXMLDecoderWithConfig parses data from a given XML decoder.
// Returns parsed config which can be used to create logger in case no errors occured.
// Returns error if format is incorrect or anything happened.
func configFromXMLDecoderWithConfig(xmlParser *xml.Decoder, rootNode xml.Token, cfg *cfgParseParams) (*configForParsing, error) {
_, ok := rootNode.(xml.StartElement)
if !ok {
return nil, errors.New("rootNode must be XML startElement")
}
config, err := unmarshalNode(xmlParser, rootNode)
if err != nil {
return nil, err
}
if config == nil {
return nil, errors.New("xml has no content")
}
return configFromXMLNodeWithConfig(config, cfg)
}
// configFromReader parses data from a given reader.
// Returns parsed config which can be used to create logger in case no errors occured.
// Returns error if format is incorrect or anything happened.
func configFromReader(reader io.Reader) (*configForParsing, error) {
return configFromReaderWithConfig(reader, nil)
}
// configFromReaderWithConfig parses data from a given reader.
// Returns parsed config which can be used to create logger in case no errors occured.
// Returns error if format is incorrect or anything happened.
func configFromReaderWithConfig(reader io.Reader, cfg *cfgParseParams) (*configForParsing, error) {
config, err := unmarshalConfig(reader)
if err != nil {
return nil, err
}
if config.name != seelogConfigID {
return nil, errors.New("root xml tag must be '" + seelogConfigID + "'")
}
return configFromXMLNodeWithConfig(config, cfg)
}
func configFromXMLNodeWithConfig(config *xmlNode, cfg *cfgParseParams) (*configForParsing, error) {
err := checkUnexpectedAttribute(
config,
minLevelID,
maxLevelID,
levelsID,
loggerTypeFromStringAttr,
asyncLoggerIntervalAttr,
adaptLoggerMinIntervalAttr,
adaptLoggerMaxIntervalAttr,
adaptLoggerCriticalMsgCountAttr,
)
if err != nil {
return nil, err
}
err = checkExpectedElements(config, optionalElement(outputsID), optionalElement(formatsID), optionalElement(exceptionsID))
if err != nil {
return nil, err
}
constraints, err := getConstraints(config)
if err != nil {
return nil, err
}
exceptions, err := getExceptions(config)
if err != nil {
return nil, err
}
err = checkDistinctExceptions(exceptions)
if err != nil {
return nil, err
}
formats, err := getFormats(config)
if err != nil {
return nil, err
}
dispatcher, err := getOutputsTree(config, formats, cfg)
if err != nil {
// If we open several files, but then fail to parse the config, we should close
// those files before reporting that config is invalid.
if dispatcher != nil {
dispatcher.Close()
}
return nil, err
}
loggerType, logData, err := getloggerTypeFromStringData(config)
if err != nil {
return nil, err
}
return newFullLoggerConfig(constraints, exceptions, dispatcher, loggerType, logData, cfg)
}
func getConstraints(node *xmlNode) (logLevelConstraints, error) {
minLevelStr, isMinLevel := node.attributes[minLevelID]
maxLevelStr, isMaxLevel := node.attributes[maxLevelID]
levelsStr, isLevels := node.attributes[levelsID]
if isLevels && (isMinLevel && isMaxLevel) {
return nil, errors.New("for level declaration use '" + levelsID + "'' OR '" + minLevelID +
"', '" + maxLevelID + "'")
}
offString := LogLevel(Off).String()
if (isLevels && strings.TrimSpace(levelsStr) == offString) ||
(isMinLevel && !isMaxLevel && minLevelStr == offString) {
return NewOffConstraints()
}
if isLevels {
levels, err := parseLevels(levelsStr)
if err != nil {
return nil, err
}
return NewListConstraints(levels)
}
var minLevel = LogLevel(TraceLvl)
if isMinLevel {
found := true
minLevel, found = LogLevelFromString(minLevelStr)
if !found {
return nil, errors.New("declared " + minLevelID + " not found: " + minLevelStr)
}
}
var maxLevel = LogLevel(CriticalLvl)
if isMaxLevel {
found := true
maxLevel, found = LogLevelFromString(maxLevelStr)
if !found {
return nil, errors.New("declared " + maxLevelID + " not found: " + maxLevelStr)
}
}
return NewMinMaxConstraints(minLevel, maxLevel)
}
func parseLevels(str string) ([]LogLevel, error) {
levelsStrArr := strings.Split(strings.Replace(str, " ", "", -1), ",")
var levels []LogLevel
for _, levelStr := range levelsStrArr {
level, found := LogLevelFromString(levelStr)
if !found {
return nil, errors.New("declared level not found: " + levelStr)
}
levels = append(levels, level)
}
return levels, nil
}
func getExceptions(config *xmlNode) ([]*LogLevelException, error) {
var exceptions []*LogLevelException
var exceptionsNode *xmlNode
for _, child := range config.children {
if child.name == exceptionsID {
exceptionsNode = child
break
}
}
if exceptionsNode == nil {
return exceptions, nil
}
err := checkUnexpectedAttribute(exceptionsNode)
if err != nil {
return nil, err
}
err = checkExpectedElements(exceptionsNode, multipleMandatoryElements("exception"))
if err != nil {
return nil, err
}
for _, exceptionNode := range exceptionsNode.children {
if exceptionNode.name != exceptionID {
return nil, errors.New("incorrect nested element in exceptions section: " + exceptionNode.name)
}
err := checkUnexpectedAttribute(exceptionNode, minLevelID, maxLevelID, levelsID, funcPatternID, filePatternID)
if err != nil {
return nil, err
}
constraints, err := getConstraints(exceptionNode)
if err != nil {
return nil, errors.New("incorrect " + exceptionsID + " node: " + err.Error())
}
funcPattern, isFuncPattern := exceptionNode.attributes[funcPatternID]
filePattern, isFilePattern := exceptionNode.attributes[filePatternID]
if !isFuncPattern {
funcPattern = "*"
}
if !isFilePattern {
filePattern = "*"
}
exception, err := NewLogLevelException(funcPattern, filePattern, constraints)
if err != nil {
return nil, errors.New("incorrect exception node: " + err.Error())
}
exceptions = append(exceptions, exception)
}
return exceptions, nil
}
func checkDistinctExceptions(exceptions []*LogLevelException) error {
for i, exception := range exceptions {
for j, exception1 := range exceptions {
if i == j {
continue
}
if exception.FuncPattern() == exception1.FuncPattern() &&
exception.FilePattern() == exception1.FilePattern() {
return fmt.Errorf("there are two or more duplicate exceptions. Func: %v, file %v",
exception.FuncPattern(), exception.FilePattern())
}
}
}
return nil
}
func getFormats(config *xmlNode) (map[string]*formatter, error) {
formats := make(map[string]*formatter, 0)
var formatsNode *xmlNode
for _, child := range config.children {
if child.name == formatsID {
formatsNode = child
break
}
}
if formatsNode == nil {
return formats, nil
}
err := checkUnexpectedAttribute(formatsNode)
if err != nil {
return nil, err
}
err = checkExpectedElements(formatsNode, multipleMandatoryElements("format"))
if err != nil {
return nil, err
}
for _, formatNode := range formatsNode.children {
if formatNode.name != formatID {
return nil, errors.New("incorrect nested element in " + formatsID + " section: " + formatNode.name)
}
err := checkUnexpectedAttribute(formatNode, formatKeyAttrID, formatID)
if err != nil {
return nil, err
}
id, isID := formatNode.attributes[formatKeyAttrID]
formatStr, isFormat := formatNode.attributes[formatAttrID]
if !isID {
return nil, errors.New("format has no '" + formatKeyAttrID + "' attribute")
}
if !isFormat {
return nil, errors.New("format[" + id + "] has no '" + formatAttrID + "' attribute")
}
formatter, err := NewFormatter(formatStr)
if err != nil {
return nil, err
}
formats[id] = formatter
}
return formats, nil
}
func getloggerTypeFromStringData(config *xmlNode) (logType loggerTypeFromString, logData interface{}, err error) {
logTypeStr, loggerTypeExists := config.attributes[loggerTypeFromStringAttr]
if !loggerTypeExists {
return defaultloggerTypeFromString, nil, nil
}
logType, found := getLoggerTypeFromString(logTypeStr)
if !found {
return 0, nil, fmt.Errorf("unknown logger type: %s", logTypeStr)
}
if logType == asyncTimerloggerTypeFromString {
intervalStr, intervalExists := config.attributes[asyncLoggerIntervalAttr]
if !intervalExists {
return 0, nil, newMissingArgumentError(config.name, asyncLoggerIntervalAttr)
}
interval, err := strconv.ParseUint(intervalStr, 10, 32)
if err != nil {
return 0, nil, err
}
logData = asyncTimerLoggerData{uint32(interval)}
} else if logType == adaptiveLoggerTypeFromString {
// Min interval
minIntStr, minIntExists := config.attributes[adaptLoggerMinIntervalAttr]
if !minIntExists {
return 0, nil, newMissingArgumentError(config.name, adaptLoggerMinIntervalAttr)
}
minInterval, err := strconv.ParseUint(minIntStr, 10, 32)
if err != nil {
return 0, nil, err
}
// Max interval
maxIntStr, maxIntExists := config.attributes[adaptLoggerMaxIntervalAttr]
if !maxIntExists {
return 0, nil, newMissingArgumentError(config.name, adaptLoggerMaxIntervalAttr)
}
maxInterval, err := strconv.ParseUint(maxIntStr, 10, 32)
if err != nil {
return 0, nil, err
}
// Critical msg count
criticalMsgCountStr, criticalMsgCountExists := config.attributes[adaptLoggerCriticalMsgCountAttr]
if !criticalMsgCountExists {
return 0, nil, newMissingArgumentError(config.name, adaptLoggerCriticalMsgCountAttr)
}
criticalMsgCount, err := strconv.ParseUint(criticalMsgCountStr, 10, 32)
if err != nil {
return 0, nil, err
}
logData = adaptiveLoggerData{uint32(minInterval), uint32(maxInterval), uint32(criticalMsgCount)}
}
return logType, logData, nil
}
func getOutputsTree(config *xmlNode, formats map[string]*formatter, cfg *cfgParseParams) (dispatcherInterface, error) {
var outputsNode *xmlNode
for _, child := range config.children {
if child.name == outputsID {
outputsNode = child
break
}
}
if outputsNode != nil {
err := checkUnexpectedAttribute(outputsNode, outputFormatID)
if err != nil {
return nil, err
}
formatter, err := getCurrentFormat(outputsNode, DefaultFormatter, formats)
if err != nil {
return nil, err
}
output, err := createSplitter(outputsNode, formatter, formats, cfg)
if err != nil {
return nil, err
}
dispatcher, ok := output.(dispatcherInterface)
if ok {
return dispatcher, nil
}
}
console, err := NewConsoleWriter()
if err != nil {
return nil, err
}
return NewSplitDispatcher(DefaultFormatter, []interface{}{console})
}
func getCurrentFormat(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter) (*formatter, error) {
formatID, isFormatID := node.attributes[outputFormatID]
if !isFormatID {
return formatFromParent, nil
}
format, ok := formats[formatID]
if ok {
return format, nil
}
// Test for predefined format match
pdFormat, pdOk := predefinedFormats[formatID]
if !pdOk {
return nil, errors.New("formatid = '" + formatID + "' doesn't exist")
}
return pdFormat, nil
}
func createInnerReceivers(node *xmlNode, format *formatter, formats map[string]*formatter, cfg *cfgParseParams) ([]interface{}, error) {
var outputs []interface{}
for _, childNode := range node.children {
entry, ok := elementMap[childNode.name]
if !ok {
return nil, errors.New("unnknown tag '" + childNode.name + "' in outputs section")
}
output, err := entry.constructor(childNode, format, formats, cfg)
if err != nil {
return nil, err
}
outputs = append(outputs, output)
}
return outputs, nil
}
func createSplitter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *cfgParseParams) (interface{}, error) {
err := checkUnexpectedAttribute(node, outputFormatID)
if err != nil {
return nil, err
}
if !node.hasChildren() {
return nil, errNodeMustHaveChildren
}
currentFormat, err := getCurrentFormat(node, formatFromParent, formats)
if err != nil {
return nil, err
}
receivers, err := createInnerReceivers(node, currentFormat, formats, cfg)
if err != nil {
return nil, err
}
return NewSplitDispatcher(currentFormat, receivers)
}
func createCustomReceiver(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *cfgParseParams) (interface{}, error) {
dataCustomPrefixes := make(map[string]string)
// Expecting only 'formatid', 'name' and 'data-' attrs
for attr, attrval := range node.attributes {
isExpected := false
if attr == outputFormatID ||
attr == customNameAttrID {
isExpected = true
}
if strings.HasPrefix(attr, customNameDataAttrPrefix) {
dataCustomPrefixes[attr[len(customNameDataAttrPrefix):]] = attrval
isExpected = true
}
if !isExpected {
return nil, newUnexpectedAttributeError(node.name, attr)
}
}
if node.hasChildren() {
return nil, errNodeCannotHaveChildren
}
customName, hasCustomName := node.attributes[customNameAttrID]
if !hasCustomName {
return nil, newMissingArgumentError(node.name, customNameAttrID)
}
currentFormat, err := getCurrentFormat(node, formatFromParent, formats)
if err != nil {
return nil, err
}
args := CustomReceiverInitArgs{
XmlCustomAttrs: dataCustomPrefixes,
}
if cfg != nil && cfg.CustomReceiverProducers != nil {
if prod, ok := cfg.CustomReceiverProducers[customName]; ok {
rec, err := prod(args)
if err != nil {
return nil, err
}
creceiver, err := NewCustomReceiverDispatcherByValue(currentFormat, rec, customName, args)
if err != nil {
return nil, err
}
err = rec.AfterParse(args)
if err != nil {
return nil, err
}
return creceiver, nil
}
}
return NewCustomReceiverDispatcher(currentFormat, customName, args)
}
func createFilter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *cfgParseParams) (interface{}, error) {
err := checkUnexpectedAttribute(node, outputFormatID, filterLevelsAttrID)
if err != nil {
return nil, err
}
if !node.hasChildren() {
return nil, errNodeMustHaveChildren
}
currentFormat, err := getCurrentFormat(node, formatFromParent, formats)
if err != nil {
return nil, err
}
levelsStr, isLevels := node.attributes[filterLevelsAttrID]
if !isLevels {
return nil, newMissingArgumentError(node.name, filterLevelsAttrID)
}
levels, err := parseLevels(levelsStr)
if err != nil {
return nil, err
}
receivers, err := createInnerReceivers(node, currentFormat, formats, cfg)
if err != nil {
return nil, err
}
return NewFilterDispatcher(currentFormat, receivers, levels...)
}
func createfileWriter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *cfgParseParams) (interface{}, error) {
err := checkUnexpectedAttribute(node, outputFormatID, pathID)
if err != nil {
return nil, err
}
if node.hasChildren() {
return nil, errNodeCannotHaveChildren
}
currentFormat, err := getCurrentFormat(node, formatFromParent, formats)
if err != nil {
return nil, err
}
path, isPath := node.attributes[pathID]
if !isPath {
return nil, newMissingArgumentError(node.name, pathID)
}
fileWriter, err := NewFileWriter(path)
if err != nil {
return nil, err
}
return NewFormattedWriter(fileWriter, currentFormat)
}
// Creates new SMTP writer if encountered in the config file.
func createSMTPWriter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *cfgParseParams) (interface{}, error) {
err := checkUnexpectedAttribute(node, outputFormatID, senderaddressID, senderNameID, hostNameID, hostPortID, userNameID, userPassID, subjectID)
if err != nil {
return nil, err
}
// Node must have children.
if !node.hasChildren() {
return nil, errNodeMustHaveChildren
}
currentFormat, err := getCurrentFormat(node, formatFromParent, formats)
if err != nil {
return nil, err
}
senderAddress, ok := node.attributes[senderaddressID]
if !ok {
return nil, newMissingArgumentError(node.name, senderaddressID)
}
senderName, ok := node.attributes[senderNameID]
if !ok {
return nil, newMissingArgumentError(node.name, senderNameID)
}
// Process child nodes scanning for recipient email addresses and/or CA certificate paths.
var recipientAddresses []string
var caCertDirPaths []string
var mailHeaders []string
for _, childNode := range node.children {
switch childNode.name {
// Extract recipient address from child nodes.
case recipientID:
address, ok := childNode.attributes[addressID]
if !ok {
return nil, newMissingArgumentError(childNode.name, addressID)
}
recipientAddresses = append(recipientAddresses, address)
// Extract CA certificate file path from child nodes.
case cACertDirpathID:
path, ok := childNode.attributes[pathID]
if !ok {
return nil, newMissingArgumentError(childNode.name, pathID)
}
caCertDirPaths = append(caCertDirPaths, path)
// Extract email headers from child nodes.
case mailHeaderID:
headerName, ok := childNode.attributes[mailHeaderNameID]
if !ok {
return nil, newMissingArgumentError(childNode.name, mailHeaderNameID)
}
headerValue, ok := childNode.attributes[mailHeaderValueID]
if !ok {
return nil, newMissingArgumentError(childNode.name, mailHeaderValueID)
}
// Build header line
mailHeaders = append(mailHeaders, fmt.Sprintf("%s: %s", headerName, headerValue))
default:
return nil, newUnexpectedChildElementError(childNode.name)
}
}
hostName, ok := node.attributes[hostNameID]
if !ok {
return nil, newMissingArgumentError(node.name, hostNameID)
}
hostPort, ok := node.attributes[hostPortID]
if !ok {
return nil, newMissingArgumentError(node.name, hostPortID)
}
// Check if the string can really be converted into int.
if _, err := strconv.Atoi(hostPort); err != nil {
return nil, errors.New("invalid host port number")
}
userName, ok := node.attributes[userNameID]
if !ok {
return nil, newMissingArgumentError(node.name, userNameID)
}
userPass, ok := node.attributes[userPassID]
if !ok {
return nil, newMissingArgumentError(node.name, userPassID)
}
// subject is optionally set by configuration.
// default value is defined by DefaultSubjectPhrase constant in the writers_smtpwriter.go
var subjectPhrase = DefaultSubjectPhrase
subject, ok := node.attributes[subjectID]
if ok {
subjectPhrase = subject
}
smtpWriter := NewSMTPWriter(
senderAddress,
senderName,
recipientAddresses,
hostName,
hostPort,
userName,
userPass,
caCertDirPaths,
subjectPhrase,
mailHeaders,
)
return NewFormattedWriter(smtpWriter, currentFormat)
}
func createConsoleWriter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *cfgParseParams) (interface{}, error) {
err := checkUnexpectedAttribute(node, outputFormatID)
if err != nil {
return nil, err
}
if node.hasChildren() {
return nil, errNodeCannotHaveChildren
}
currentFormat, err := getCurrentFormat(node, formatFromParent, formats)
if err != nil {
return nil, err
}
consoleWriter, err := NewConsoleWriter()
if err != nil {
return nil, err
}
return NewFormattedWriter(consoleWriter, currentFormat)
}
func createconnWriter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *cfgParseParams) (interface{}, error) {
if node.hasChildren() {
return nil, errNodeCannotHaveChildren
}
err := checkUnexpectedAttribute(node, outputFormatID, connWriterAddrAttr, connWriterNetAttr, connWriterReconnectOnMsgAttr, connWriterUseTLSAttr, connWriterInsecureSkipVerifyAttr)
if err != nil {
return nil, err
}
currentFormat, err := getCurrentFormat(node, formatFromParent, formats)
if err != nil {
return nil, err
}
addr, isAddr := node.attributes[connWriterAddrAttr]
if !isAddr {
return nil, newMissingArgumentError(node.name, connWriterAddrAttr)
}
net, isNet := node.attributes[connWriterNetAttr]
if !isNet {
return nil, newMissingArgumentError(node.name, connWriterNetAttr)
}
reconnectOnMsg := false
reconnectOnMsgStr, isReconnectOnMsgStr := node.attributes[connWriterReconnectOnMsgAttr]
if isReconnectOnMsgStr {
if reconnectOnMsgStr == "true" {
reconnectOnMsg = true
} else if reconnectOnMsgStr == "false" {
reconnectOnMsg = false
} else {
return nil, errors.New("node '" + node.name + "' has incorrect '" + connWriterReconnectOnMsgAttr + "' attribute value")
}
}
useTLS := false
useTLSStr, isUseTLSStr := node.attributes[connWriterUseTLSAttr]
if isUseTLSStr {
if useTLSStr == "true" {
useTLS = true
} else if useTLSStr == "false" {
useTLS = false
} else {
return nil, errors.New("node '" + node.name + "' has incorrect '" + connWriterUseTLSAttr + "' attribute value")
}
if useTLS {
insecureSkipVerify := false
insecureSkipVerifyStr, isInsecureSkipVerify := node.attributes[connWriterInsecureSkipVerifyAttr]
if isInsecureSkipVerify {
if insecureSkipVerifyStr == "true" {
insecureSkipVerify = true
} else if insecureSkipVerifyStr == "false" {
insecureSkipVerify = false
} else {
return nil, errors.New("node '" + node.name + "' has incorrect '" + connWriterInsecureSkipVerifyAttr + "' attribute value")
}
}
config := tls.Config{InsecureSkipVerify: insecureSkipVerify}
connWriter := newTLSWriter(net, addr, reconnectOnMsg, &config)
return NewFormattedWriter(connWriter, currentFormat)
}
}
connWriter := NewConnWriter(net, addr, reconnectOnMsg)
return NewFormattedWriter(connWriter, currentFormat)
}
func createRollingFileWriter(node *xmlNode, formatFromParent *formatter, formats map[string]*formatter, cfg *cfgParseParams) (interface{}, error) {
if node.hasChildren() {
return nil, errNodeCannotHaveChildren
}
rollingTypeStr, isRollingType := node.attributes[rollingFileTypeAttr]
if !isRollingType {
return nil, newMissingArgumentError(node.name, rollingFileTypeAttr)
}
rollingType, ok := rollingTypeFromString(rollingTypeStr)
if !ok {
return nil, errors.New("unknown rolling file type: " + rollingTypeStr)
}
currentFormat, err := getCurrentFormat(node, formatFromParent, formats)
if err != nil {
return nil, err
}