-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextractor.go
More file actions
1711 lines (1515 loc) · 50.9 KB
/
Copy pathextractor.go
File metadata and controls
1711 lines (1515 loc) · 50.9 KB
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 spl
import (
"fmt"
"strings"
"time"
"github.com/antlr4-go/antlr/v4"
)
// MaxParseTime is the maximum time allowed for parsing a single query.
// Queries that exceed this are returned with an error.
var MaxParseTime = 5 * time.Second
// Condition represents a field condition extracted from an SPL query
type Condition struct {
Field string `json:"field"`
Operator string `json:"operator"`
Value string `json:"value"`
Negated bool `json:"negated"`
PipeStage int `json:"pipe_stage"`
LogicalOp string `json:"logical_op"` // "AND" or "OR" connecting to previous condition
Alternatives []string `json:"alternatives,omitempty"` // For OR conditions on same field
IsComputed bool `json:"is_computed,omitempty"` // True if field was created by eval/rex
SourceField string `json:"source_field,omitempty"` // Original field before transformation (for computed fields)
}
// ParseResult contains all conditions extracted from the query
type ParseResult struct {
Conditions []Condition `json:"conditions"`
GroupByFields []string `json:"group_by_fields,omitempty"` // Fields from stats/eventstats/streamstats BY clauses
ComputedFields map[string]string `json:"computed_fields,omitempty"` // Map of computed field name -> source field (from eval/rex)
FieldAliases map[string]string `json:"field_aliases,omitempty"` // Map of new name -> original name (from rename)
Commands []string `json:"commands,omitempty"` // List of commands used in the query (stats, eventstats, etc.)
Joins []JoinInfo `json:"joins,omitempty"` // Extracted join/append info
Subsearches []*ParseResult `json:"subsearches,omitempty"` // Recursively parsed direct subsearches
Errors []string `json:"errors,omitempty"`
}
// FieldProvenance indicates where a field originates relative to a join
type FieldProvenance string
const (
ProvenanceMain FieldProvenance = "main" // Field exists in main query before join
ProvenanceJoined FieldProvenance = "joined" // Field comes from the joined subsearch
ProvenanceJoinKey FieldProvenance = "join_key" // Field is used as a join key (both sides)
ProvenanceAmbiguous FieldProvenance = "ambiguous" // Cannot determine provenance
)
// JoinInfo captures the structured decomposition of a JOIN or APPEND command
type JoinInfo struct {
Type string `json:"type"` // "inner", "left", "outer" (default: "inner")
JoinFields []string `json:"join_fields,omitempty"` // Fields to join ON (from fieldList)
Options map[string]string `json:"options,omitempty"` // All joinOption key=value pairs
Subsearch *ParseResult `json:"subsearch"` // Recursively parsed subsearch
PipeStage int `json:"pipe_stage"` // Pipeline stage where join appears
IsAppend bool `json:"is_append,omitempty"` // True if this is an APPEND, not JOIN
ExposedFields []string `json:"exposed_fields,omitempty"` // Fields the subsearch makes available
}
// SearchScopeMetadata are fields that define WHERE to search, not WHAT to match
// These are Splunk infrastructure metadata, not part of event data
// Note: "host" is NOT included because it's a meaningful field that appears in event data
// and is commonly used in detection rules (unlike index/sourcetype/source which are routing metadata)
var SearchScopeMetadata = map[string]bool{
"index": true, // Which index to search
"sourcetype": true, // Data format type
"source": true, // File path of the data
"earliest": true, // Time range start
"latest": true, // Time range end
"splunk_server": true, // Server to search
}
// splCommandKeywords are SPL command keywords that should be excluded
// These are not field names
var splCommandKeywords = map[string]bool{
"count": true, "sum": true, "avg": true, "min": true, "max": true,
"search": true, "where": true, "eval": true, "stats": true,
"table": true, "fields": true, "rename": true, "sort": true,
"head": true, "tail": true, "dedup": true, "by": true,
"as": true, "and": true, "or": true, "not": true,
"span": true,
}
// isExcludedField returns true if a field should be excluded from condition extraction
// Note: This excludes time-range modifiers but NOT index/sourcetype/source which provide
// useful context for rules. For test data generation filtering, use IsSearchScopeMetadata.
func isExcludedField(fieldLower string) bool {
return fieldLower == "earliest" || fieldLower == "latest" || fieldLower == "splunk_server" ||
splCommandKeywords[fieldLower]
}
// IsSearchScopeMetadata returns true if the field is search scope metadata
// (index, sourcetype, source, etc.) rather than event data.
// Use this to filter fields when determining what fields to include in test data.
func IsSearchScopeMetadata(field string) bool {
return SearchScopeMetadata[strings.ToLower(field)]
}
// IsCommandKeyword returns true if the string is a SPL command keyword
func IsCommandKeyword(field string) bool {
return splCommandKeywords[strings.ToLower(field)]
}
// conditionExtractor walks the parse tree to extract conditions
type conditionExtractor struct {
*BaseSPLParserListener
conditions []Condition
groupByFields []string // Fields from stats BY clauses
computedFields map[string]string // Fields created by eval commands: computed field -> source field
fieldAliases map[string]string // Rename mappings: new name -> original name
commands []string // Commands used in the query (stats, eventstats, etc.)
joins []JoinInfo // Extracted join info
subsearches []*ParseResult // Direct subsearch parse results
currentStage int
inSubsearch int // depth of subsearch nesting
inFunctionCall int // depth of function call nesting (eval, count, etc.)
inStatsFunction int // depth of stats function nesting (count(), sum(), etc.)
negated bool
lastLogicalOp string
errors []string
tokenStream *antlr.CommonTokenStream // Needed to extract subsearch text
originalQuery string // Original query string for text extraction
}
// errorListener collects parse errors
type errorListener struct {
*antlr.DefaultErrorListener
errors []string
}
func (l *errorListener) SyntaxError(recognizer antlr.Recognizer, offendingSymbol interface{}, line, column int, msg string, e antlr.RecognitionException) {
l.errors = append(l.errors, msg)
}
// ExtractConditions parses an SPL query and extracts all field conditions.
// Uses a timeout (MaxParseTime) to abort queries that cause the parser to hang
// on deeply nested expressions. Recovers from panics.
func ExtractConditions(query string) *ParseResult {
ch := make(chan *ParseResult, 1)
go func() {
ch <- extractConditionsInternal(query)
}()
select {
case result := <-ch:
return result
case <-time.After(MaxParseTime):
return &ParseResult{
Conditions: []Condition{},
Commands: []string{},
Errors: []string{fmt.Sprintf("parser timeout: query took longer than %s to parse", MaxParseTime)},
}
}
}
func extractConditionsInternal(query string) (result *ParseResult) {
defer func() {
if r := recover(); r != nil {
result = &ParseResult{
Conditions: []Condition{},
Commands: []string{},
Errors: []string{fmt.Sprintf("parser panic: %v", r)},
}
}
}()
input := antlr.NewInputStream(query)
lexer := NewSPLLexer(input)
// Remove default error listener and add our own
lexer.RemoveErrorListeners()
lexerErrors := &errorListener{}
lexer.AddErrorListener(lexerErrors)
stream := antlr.NewCommonTokenStream(lexer, antlr.TokenDefaultChannel)
parser := NewSPLParser(stream)
// Remove default error listener and add our own
parser.RemoveErrorListeners()
parserErrors := &errorListener{}
parser.AddErrorListener(parserErrors)
// Parse the query
tree := parser.Query()
// Walk the tree to extract conditions
extractor := &conditionExtractor{
conditions: make([]Condition, 0),
computedFields: make(map[string]string), // computed field -> source field
fieldAliases: make(map[string]string), // rename mappings: new name -> original name
commands: make([]string, 0),
joins: make([]JoinInfo, 0),
subsearches: make([]*ParseResult, 0),
lastLogicalOp: "AND", // default
tokenStream: stream,
originalQuery: query,
}
antlr.ParseTreeWalkerDefault.Walk(extractor, tree)
// Combine errors
allErrors := append(lexerErrors.errors, parserErrors.errors...)
allErrors = append(allErrors, extractor.errors...)
// Post-process to group OR conditions on same field
conditions := groupORConditions(extractor.conditions)
return &ParseResult{
Conditions: conditions,
GroupByFields: extractor.groupByFields,
ComputedFields: extractor.computedFields,
FieldAliases: extractor.fieldAliases,
Commands: extractor.commands,
Joins: extractor.joins,
Subsearches: extractor.subsearches,
Errors: allErrors,
}
}
// ExitPipelineStage increments the stage counter after processing each stage
func (e *conditionExtractor) ExitPipelineStage(ctx *PipelineStageContext) {
e.currentStage++
}
// EnterSubsearch tracks when we enter a subsearch
func (e *conditionExtractor) EnterSubsearch(ctx *SubsearchContext) {
if e.inSubsearch == 0 {
subText := strings.TrimSpace(e.extractSubsearchText(ctx))
if subText != "" {
e.subsearches = append(e.subsearches, ExtractConditions(subText))
}
}
e.inSubsearch++
}
// ExitSubsearch tracks when we exit a subsearch
func (e *conditionExtractor) ExitSubsearch(ctx *SubsearchContext) {
e.inSubsearch--
}
// extractSubsearchText extracts the raw query text inside a subsearch's brackets
// using character positions from the original query string. We use the original
// query rather than GetTextFromTokens because the latter strips whitespace
// (WS tokens are on the HIDDEN channel).
func (e *conditionExtractor) extractSubsearchText(ctx *SubsearchContext) string {
if ctx == nil || ctx.Query() == nil {
return ""
}
queryCtx := ctx.Query()
start := queryCtx.GetStart()
stop := queryCtx.GetStop()
if start == nil || stop == nil {
return queryCtx.GetText()
}
startPos := start.GetStart()
stopPos := stop.GetStop()
if startPos >= 0 && stopPos >= startPos && stopPos < len(e.originalQuery) {
return e.originalQuery[startPos : stopPos+1]
}
return queryCtx.GetText()
}
// EnterJoinCommand extracts join metadata and recursively parses the subsearch
func (e *conditionExtractor) EnterJoinCommand(ctx *JoinCommandContext) {
e.commands = append(e.commands, "join")
info := JoinInfo{
Type: "inner", // SPL default
Options: make(map[string]string),
PipeStage: e.currentStage,
}
// Extract join options (e.g., type=left, max=1)
for _, opt := range ctx.AllJoinOption() {
if opt.IDENTIFIER() != nil && opt.EQ() != nil {
key := strings.ToLower(opt.IDENTIFIER().GetText())
var val string
if opt.QUOTED_STRING() != nil {
val = strings.Trim(opt.QUOTED_STRING().GetText(), "\"'")
} else if opt.FieldName() != nil {
val = opt.FieldName().GetText()
} else if opt.NUMBER() != nil {
val = opt.NUMBER().GetText()
}
info.Options[key] = val
if key == "type" {
info.Type = strings.ToLower(val)
}
}
}
// Extract join fields (the ON fields from fieldList)
if ctx.FieldList() != nil {
for _, foq := range ctx.FieldList().AllFieldOrQuoted() {
if foq.FieldName() != nil {
info.JoinFields = append(info.JoinFields, foq.FieldName().GetText())
} else if foq.QUOTED_STRING() != nil {
info.JoinFields = append(info.JoinFields, strings.Trim(foq.QUOTED_STRING().GetText(), "\"'"))
}
}
}
// Recursively parse the subsearch
if ctx.Subsearch() != nil {
subText := e.extractSubsearchText(ctx.Subsearch().(*SubsearchContext))
if subText != "" {
info.Subsearch = ExtractConditions(subText)
info.ExposedFields = deriveExposedFields(info.Subsearch, info.JoinFields)
}
}
e.joins = append(e.joins, info)
}
// EnterAppendCommand extracts append subsearch info
func (e *conditionExtractor) EnterAppendCommand(ctx *AppendCommandContext) {
e.commands = append(e.commands, "append")
info := JoinInfo{
Type: "append",
IsAppend: true,
PipeStage: e.currentStage,
}
if ctx.Subsearch() != nil {
subText := e.extractSubsearchText(ctx.Subsearch().(*SubsearchContext))
if subText != "" {
info.Subsearch = ExtractConditions(subText)
info.ExposedFields = deriveExposedFields(info.Subsearch, nil)
}
}
e.joins = append(e.joins, info)
}
// deriveExposedFields determines which fields a subsearch makes available
// after the join. Uses a fallback chain:
// 1. Explicit output commands (table/fields) -> exact field list
// 2. Condition fields from the subsearch
// 3. Computed fields from eval/rex in the subsearch
func deriveExposedFields(subResult *ParseResult, joinFields []string) []string {
if subResult == nil {
return nil
}
fieldSet := make(map[string]bool)
// Check if subsearch has table/fields command — if so, those are the explicit outputs
hasExplicitOutput := false
for _, cmd := range subResult.Commands {
if cmd == "table" || cmd == "fields" {
hasExplicitOutput = true
break
}
}
if hasExplicitOutput {
// When table/fields is present, use those as the definitive output field list
for _, f := range subResult.GroupByFields {
fieldSet[f] = true
}
} else {
// No explicit output — fall back to condition fields and computed fields
for _, c := range subResult.Conditions {
if !IsSearchScopeMetadata(c.Field) {
fieldSet[c.Field] = true
}
}
for computed := range subResult.ComputedFields {
fieldSet[computed] = true
}
}
// Include join fields (they exist on both sides by definition)
for _, f := range joinFields {
fieldSet[f] = true
}
result := make([]string, 0, len(fieldSet))
for f := range fieldSet {
result = append(result, f)
}
return result
}
// ClassifyFieldProvenance determines where a field originates relative to
// the first join in the query.
// Returns ProvenanceAmbiguous if no joins exist or provenance can't be determined.
func ClassifyFieldProvenance(result *ParseResult, field string) FieldProvenance {
if result == nil || len(result.Joins) == 0 {
return ProvenanceAmbiguous
}
fieldLower := strings.ToLower(field)
// Check join keys first (they exist on both sides)
for _, j := range result.Joins {
for _, jf := range j.JoinFields {
if strings.ToLower(jf) == fieldLower {
return ProvenanceJoinKey
}
}
}
// Check if field is in exposed fields from any join's subsearch
for _, j := range result.Joins {
for _, ef := range j.ExposedFields {
if strings.ToLower(ef) == fieldLower {
return ProvenanceJoined
}
}
}
// Check if field is in main query conditions (before any join)
firstJoinStage := -1
for _, j := range result.Joins {
if firstJoinStage == -1 || j.PipeStage < firstJoinStage {
firstJoinStage = j.PipeStage
}
}
for _, c := range result.Conditions {
if strings.ToLower(c.Field) == fieldLower && c.PipeStage < firstJoinStage {
return ProvenanceMain
}
}
// Field exists in conditions but after join — check if it's from main query scope
// by seeing if it appears in pre-join computed fields
if _, ok := result.ComputedFields[fieldLower]; ok {
return ProvenanceMain
}
return ProvenanceAmbiguous
}
// EnterFunctionCall handles function calls.
// - For cidrmatch, match, and like: extract as conditions
// - For other functions (eval, count, sum, etc.): track depth to skip nested conditions
func (e *conditionExtractor) EnterFunctionCall(ctx *FunctionCallContext) {
// Skip function calls inside subsearches
if e.inSubsearch > 0 {
e.inFunctionCall++
return
}
// Check for cidrmatch(cidr, field) - extracts a CIDR match condition
if ctx.CIDRMATCH() != nil {
args := ctx.ArgumentList()
if args != nil {
allArgs := args.AllExpression()
if len(allArgs) >= 2 {
// First arg is CIDR, second is field
cidr := strings.Trim(allArgs[0].GetText(), "\"'")
field := allArgs[1].GetText()
cond := Condition{
Field: field,
Operator: "cidrmatch",
Value: cidr,
Negated: e.negated,
PipeStage: e.currentStage,
LogicalOp: e.lastLogicalOp,
}
e.conditions = append(e.conditions, cond)
e.lastLogicalOp = "AND"
}
}
return // Don't increment inFunctionCall for these
}
// Check for match(field, regex) - extracts a regex match condition
if ctx.MATCH() != nil {
args := ctx.ArgumentList()
if args != nil {
allArgs := args.AllExpression()
if len(allArgs) >= 2 {
// First arg is field, second is regex
field := allArgs[0].GetText()
regex := strings.Trim(allArgs[1].GetText(), "\"'")
cond := Condition{
Field: field,
Operator: "matches",
Value: regex,
Negated: e.negated,
PipeStage: e.currentStage,
LogicalOp: e.lastLogicalOp,
}
e.conditions = append(e.conditions, cond)
e.lastLogicalOp = "AND"
}
}
return // Don't increment inFunctionCall for these
}
// Check for like(field, pattern) - extracts a like pattern condition
if ctx.LIKE() != nil {
args := ctx.ArgumentList()
if args != nil {
allArgs := args.AllExpression()
if len(allArgs) >= 2 {
// First arg is field, second is pattern
field := allArgs[0].GetText()
pattern := strings.Trim(allArgs[1].GetText(), "\"'")
// Convert SQL LIKE pattern to wildcard
pattern = strings.ReplaceAll(pattern, "%", "*")
pattern = strings.ReplaceAll(pattern, "_", "?")
cond := Condition{
Field: field,
Operator: "like",
Value: pattern,
Negated: e.negated,
PipeStage: e.currentStage,
LogicalOp: e.lastLogicalOp,
}
e.conditions = append(e.conditions, cond)
e.lastLogicalOp = "AND"
}
}
return // Don't increment inFunctionCall for these
}
// Check for isnotnull(field) - extracts an exists condition
if ctx.ISNOTNULL() != nil {
args := ctx.ArgumentList()
if args != nil {
allArgs := args.AllExpression()
if len(allArgs) >= 1 {
field := allArgs[0].GetText()
cond := Condition{
Field: field,
Operator: "isnotnull",
Value: "",
Negated: e.negated,
PipeStage: e.currentStage,
LogicalOp: e.lastLogicalOp,
}
e.conditions = append(e.conditions, cond)
e.lastLogicalOp = "AND"
}
}
return
}
// Check for isnull(field) - extracts a null check condition
if ctx.ISNULL() != nil {
args := ctx.ArgumentList()
if args != nil {
allArgs := args.AllExpression()
if len(allArgs) >= 1 {
field := allArgs[0].GetText()
cond := Condition{
Field: field,
Operator: "isnull",
Value: "",
Negated: e.negated,
PipeStage: e.currentStage,
LogicalOp: e.lastLogicalOp,
}
e.conditions = append(e.conditions, cond)
e.lastLogicalOp = "AND"
}
}
return
}
// For other function calls, track depth to skip nested conditions
e.inFunctionCall++
}
// ExitFunctionCall tracks when we exit a function call
func (e *conditionExtractor) ExitFunctionCall(ctx *FunctionCallContext) {
e.inFunctionCall--
}
// EnterStatsFunction tracks when we enter a stats function (count(), sum(), etc.)
// Conditions inside stats functions are aggregation expressions, not filter conditions
func (e *conditionExtractor) EnterStatsFunction(ctx *StatsFunctionContext) {
e.inStatsFunction++
}
// ExitStatsFunction tracks when we exit a stats function.
// It also registers any "AS alias" as a computed field so that post-aggregation
// filters (e.g. | where events > 5) are recognized as operating on computed fields.
func (e *conditionExtractor) ExitStatsFunction(ctx *StatsFunctionContext) {
e.inStatsFunction--
// If this stats function has an AS alias, register it as a computed field
if ctx.AS() != nil && ctx.FieldName() != nil {
alias := strings.ToLower(ctx.FieldName().GetText())
// The source is the expression inside the function, or the function name itself
sourceField := ""
if ctx.Expression() != nil {
sourceField = extractFirstFieldFromExpression(ctx.Expression())
}
if sourceField == "" {
// For functions like count (no expression), use the function name as source marker
sourceField = strings.ToLower(ctx.IDENTIFIER().GetText())
}
e.computedFields[alias] = sourceField
}
}
// EnterTstatsCommand extracts group-by fields, datamodel reference, and commands from tstats
func (e *conditionExtractor) EnterTstatsCommand(ctx *TstatsCommandContext) {
e.commands = append(e.commands, "tstats")
// Extract BY/GROUPBY fields from fieldOrQuoted elements
for _, foq := range ctx.AllFieldOrQuoted() {
if foq.FieldName() != nil {
field := foq.FieldName().GetText()
fieldLower := strings.ToLower(field)
if !isExcludedField(fieldLower) {
e.groupByFields = append(e.groupByFields, field)
}
} else if foq.QUOTED_STRING() != nil {
field := strings.Trim(foq.QUOTED_STRING().GetText(), `"'`)
fieldLower := strings.ToLower(field)
if !isExcludedField(fieldLower) {
e.groupByFields = append(e.groupByFields, field)
}
}
}
// Extract datamodel reference
if ctx.TstatsDatamodel() != nil {
dm := ctx.TstatsDatamodel()
ids := dm.AllIDENTIFIER()
if dm.EQ() != nil && len(ids) >= 2 {
// "datamodel=Endpoint.Processes" — skip "datamodel" keyword
parts := make([]string, 0, len(ids)-1)
for _, id := range ids[1:] {
parts = append(parts, id.GetText())
}
e.computedFields["_datamodel"] = strings.Join(parts, ".")
} else {
// Plain "Endpoint.Processes"
parts := make([]string, 0, len(ids))
for _, id := range ids {
parts = append(parts, id.GetText())
}
e.computedFields["_datamodel"] = strings.Join(parts, ".")
}
}
}
// EnterMstatsCommand extracts group-by fields from mstats commands (metrics store)
func (e *conditionExtractor) EnterMstatsCommand(ctx *MstatsCommandContext) {
e.commands = append(e.commands, "mstats")
// Extract BY/GROUPBY fields from fieldOrQuoted elements
for _, foq := range ctx.AllFieldOrQuoted() {
if foq.FieldName() != nil {
field := foq.FieldName().GetText()
fieldLower := strings.ToLower(field)
if !isExcludedField(fieldLower) {
e.groupByFields = append(e.groupByFields, field)
}
} else if foq.QUOTED_STRING() != nil {
field := strings.Trim(foq.QUOTED_STRING().GetText(), `"'`)
fieldLower := strings.ToLower(field)
if !isExcludedField(fieldLower) {
e.groupByFields = append(e.groupByFields, field)
}
}
}
}
// EnterInputlookupCommand extracts the command name for inputlookup
func (e *conditionExtractor) EnterInputlookupCommand(ctx *InputlookupCommandContext) {
e.commands = append(e.commands, "inputlookup")
}
// EnterStatsCommand extracts group-by fields from stats commands
func (e *conditionExtractor) EnterStatsCommand(ctx *StatsCommandContext) {
e.commands = append(e.commands, "stats")
e.extractByFields(ctx.FieldList())
}
// EnterEventstatsCommand extracts group-by fields from eventstats commands
func (e *conditionExtractor) EnterEventstatsCommand(ctx *EventstatsCommandContext) {
e.commands = append(e.commands, "eventstats")
e.extractByFields(ctx.FieldList())
}
// EnterStreamstatsCommand extracts group-by fields from streamstats commands
func (e *conditionExtractor) EnterStreamstatsCommand(ctx *StreamstatsCommandContext) {
e.commands = append(e.commands, "streamstats")
e.extractByFields(ctx.FieldList())
}
// EnterTimechartCommand extracts group-by fields from timechart commands
func (e *conditionExtractor) EnterTimechartCommand(ctx *TimechartCommandContext) {
e.commands = append(e.commands, "timechart")
if ctx.FieldName() != nil {
field := ctx.FieldName().GetText()
if !isExcludedField(strings.ToLower(field)) {
e.groupByFields = append(e.groupByFields, field)
}
}
}
// EnterChartCommand extracts group-by fields from chart commands
func (e *conditionExtractor) EnterChartCommand(ctx *ChartCommandContext) {
e.commands = append(e.commands, "chart")
e.extractByFields(ctx.FieldList())
// Also extract the OVER field if present
if ctx.FieldName() != nil {
field := ctx.FieldName().GetText()
if !isExcludedField(strings.ToLower(field)) {
e.groupByFields = append(e.groupByFields, field)
}
}
}
// extractByFields extracts field names from a FieldList context (used in BY clauses)
func (e *conditionExtractor) extractByFields(fieldList IFieldListContext) {
if fieldList == nil {
return
}
// FieldList contains FieldOrQuoted elements, each of which has a FieldName
for _, fieldOrQuoted := range fieldList.AllFieldOrQuoted() {
if fieldOrQuoted.FieldName() != nil {
field := fieldOrQuoted.FieldName().GetText()
fieldLower := strings.ToLower(field)
if !isExcludedField(fieldLower) {
e.groupByFields = append(e.groupByFields, field)
}
} else if fieldOrQuoted.QUOTED_STRING() != nil {
// Handle quoted field name
field := fieldOrQuoted.QUOTED_STRING().GetText()
// Remove quotes
field = strings.Trim(field, `"'`)
fieldLower := strings.ToLower(field)
if !isExcludedField(fieldLower) {
e.groupByFields = append(e.groupByFields, field)
}
}
}
}
// EnterDedupCommand extracts fields from dedup commands
func (e *conditionExtractor) EnterDedupCommand(ctx *DedupCommandContext) {
e.extractByFields(ctx.FieldList())
}
// EnterFieldsCommand extracts fields from fields commands (field selection)
func (e *conditionExtractor) EnterFieldsCommand(ctx *FieldsCommandContext) {
e.commands = append(e.commands, "fields")
e.extractByFields(ctx.FieldList())
}
// EnterTableCommand extracts fields from table commands (display fields)
func (e *conditionExtractor) EnterTableCommand(ctx *TableCommandContext) {
e.commands = append(e.commands, "table")
e.extractByFields(ctx.FieldList())
}
// EnterTopCommand extracts fields from top commands
func (e *conditionExtractor) EnterTopCommand(ctx *TopCommandContext) {
for _, fieldList := range ctx.AllFieldList() {
e.extractByFields(fieldList)
}
}
// EnterRareCommand extracts fields from rare commands
func (e *conditionExtractor) EnterRareCommand(ctx *RareCommandContext) {
for _, fieldList := range ctx.AllFieldList() {
e.extractByFields(fieldList)
}
}
// EnterSortCommand extracts fields from sort commands
func (e *conditionExtractor) EnterSortCommand(ctx *SortCommandContext) {
for _, sortField := range ctx.AllSortField() {
if sortField.FieldName() != nil {
field := sortField.FieldName().GetText()
fieldLower := strings.ToLower(field)
if !isExcludedField(fieldLower) {
e.groupByFields = append(e.groupByFields, field)
}
}
}
}
// EnterEvalCommand tracks eval commands
func (e *conditionExtractor) EnterEvalCommand(ctx *EvalCommandContext) {
e.commands = append(e.commands, "eval")
}
// EnterWhereCommand tracks where commands
func (e *conditionExtractor) EnterWhereCommand(ctx *WhereCommandContext) {
e.commands = append(e.commands, "where")
}
// EnterTransactionCommand tracks transaction commands and marks computed fields.
// The transaction command computes several fields that don't exist in raw events:
// - duration: seconds between first and last event in the transaction
// - eventcount: number of events in the transaction
// - closed_txn: 1 if the transaction was properly closed, 0 otherwise
// These should not be expected in test data as they're computed by the command.
func (e *conditionExtractor) EnterTransactionCommand(ctx *TransactionCommandContext) {
e.commands = append(e.commands, "transaction")
// Mark transaction-computed fields
// The source marker "_transaction" indicates these are computed by the transaction command
e.computedFields["duration"] = "_transaction"
e.computedFields["eventcount"] = "_transaction"
e.computedFields["closed_txn"] = "_transaction"
// Extract the grouping fields from transaction (these are the fields used to group events)
if ctx.FieldList() != nil {
e.extractByFields(ctx.FieldList())
}
}
// EnterRexCommand tracks rex commands and extracts computed fields from named capture groups
// rex field=CommandLine "(?<script>[^\s]+\.ps1)" creates computed field "script" from "CommandLine"
func (e *conditionExtractor) EnterRexCommand(ctx *RexCommandContext) {
e.commands = append(e.commands, "rex")
// Skip rex in subsearches
if e.inSubsearch > 0 {
return
}
// Find the source field from field=XXX option
sourceField := "_raw" // Default source is _raw
for _, opt := range ctx.AllRexOption() {
if opt.IDENTIFIER() != nil && strings.ToLower(opt.IDENTIFIER().GetText()) == "field" {
// Get the field value
if opt.FieldName() != nil {
sourceField = opt.FieldName().GetText()
} else if opt.QUOTED_STRING() != nil {
sourceField = strings.Trim(opt.QUOTED_STRING().GetText(), "\"'")
}
break
}
}
// Get the regex pattern and extract named capture groups
if ctx.QUOTED_STRING() != nil {
pattern := ctx.QUOTED_STRING().GetText()
captureGroups := extractNamedCaptureGroups(pattern)
// Map each captured field to the source field
for _, captured := range captureGroups {
e.computedFields[strings.ToLower(captured)] = sourceField
}
}
}
// EnterRenameCommand tracks rename commands: | rename OldField AS NewField
// Records field aliases so downstream consumers can resolve renamed fields.
func (e *conditionExtractor) EnterRenameCommand(ctx *RenameCommandContext) {
e.commands = append(e.commands, "rename")
if e.inSubsearch > 0 {
return
}
for _, spec := range ctx.AllRenameSpec() {
fields := spec.AllFieldName()
// renameSpec: fieldName AS (fieldName | QUOTED_STRING)
if len(fields) >= 1 {
oldName := fields[0].GetText()
var newName string
if len(fields) >= 2 {
newName = fields[1].GetText()
} else if spec.QUOTED_STRING() != nil {
newName = strings.Trim(spec.QUOTED_STRING().GetText(), "\"'")
}
if newName != "" && oldName != "" {
e.fieldAliases[strings.ToLower(newName)] = oldName
// Also track as computed field so downstream conditions
// on the renamed field are marked as computed.
e.computedFields[strings.ToLower(newName)] = oldName
}
}
}
}
// extractNamedCaptureGroups extracts named capture group names from a regex pattern
// Pattern: (?<name>...) or (?P<name>...) returns ["name", ...]
func extractNamedCaptureGroups(pattern string) []string {
var groups []string
// Look for (?<name> or (?P<name> patterns
i := 0
for i < len(pattern)-4 {
if pattern[i] == '(' && pattern[i+1] == '?' {
start := i + 2
// Check for (?<name> or (?P<name>
if start < len(pattern) && pattern[start] == '<' {
start++ // skip '<'
} else if start < len(pattern) && pattern[start] == 'P' && start+1 < len(pattern) && pattern[start+1] == '<' {
start += 2 // skip 'P<'
} else {
i++
continue
}
// Extract the group name until '>'
end := start
for end < len(pattern) && pattern[end] != '>' {
end++
}
if end > start && end < len(pattern) {
groups = append(groups, pattern[start:end])
}
}
i++
}
return groups
}
// EnterEvalAssignment tracks computed fields from eval commands
func (e *conditionExtractor) EnterEvalAssignment(ctx *EvalAssignmentContext) {
// Skip eval assignments in subsearches
if e.inSubsearch > 0 {
return
}
// Extract the field name being assigned to and try to find the source field
if ctx.FieldName() != nil {
computedField := ctx.FieldName().GetText()
sourceField := ""
// Try to extract the source field from the expression
// Expression is typically: function(sourceField) or function(sourceField, ...)
if ctx.Expression() != nil {
sourceField = extractFirstFieldFromExpression(ctx.Expression())
}
e.computedFields[strings.ToLower(computedField)] = sourceField
}
}
// extractFirstFieldFromExpression tries to extract the first field name from an expression
// This handles patterns like:
// - Function calls: lower(CommandLine), coalesce(field1, field2)
// - String concatenation: Process."-".CommandLine (SPL uses . for concat)
// - Simple identifiers: fieldName
func extractFirstFieldFromExpression(ctx IExpressionContext) string {
if ctx == nil {
return ""
}
text := ctx.GetText()
if text == "" {
return ""
}
// Extract all potential field names from the expression
fields := extractFieldNamesFromText(text)
if len(fields) > 0 {
return fields[0]
}
return ""
}
// extractFieldNamesFromText extracts all field name identifiers from expression text
// Returns field names in order of appearance, filtering out SPL keywords and literals
func extractFieldNamesFromText(text string) []string {
var fields []string
var current strings.Builder
inQuote := false
quoteChar := rune(0)
// Track if we're inside a function name (before the opening paren)
// We want to skip function names but include their arguments
for i, ch := range text {
// Handle quoted strings - skip their contents
if (ch == '"' || ch == '\'') && (i == 0 || text[i-1] != '\\') {
if !inQuote {
inQuote = true
quoteChar = ch
} else if ch == quoteChar {
inQuote = false
quoteChar = 0
}
continue
}
if inQuote {
continue
}
// Check if this is a valid identifier character
isIdentChar := (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') || ch == '_'
if isIdentChar {
current.WriteRune(ch)
} else {
// End of identifier
if current.Len() > 0 {
identifier := current.String()
current.Reset()