Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[pkg/ottl] Add new ExtractPatterns converter that extract regex patterns from string #25878

Merged
merged 12 commits into from
Aug 21, 2023
27 changes: 27 additions & 0 deletions .chloggen/ottl-func-extract-pattern.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: pkg/ottl

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Add new `ExtractPattern` converter that extract regex pattern from string.

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [25834, 25856]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:

# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: [user]
16 changes: 16 additions & 0 deletions pkg/ottl/ottlfuncs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,7 @@ Unlike functions, they do not modify any input telemetry and always return a val
Available Converters:
- [Concat](#concat)
- [ConvertCase](#convertcase)
- [ExtractPattern](#extractpattern)
- [FNV](#fnv)
- [Duration](#duration)
- [Int](#int)
Expand Down Expand Up @@ -530,6 +531,21 @@ Examples:

- `ParseJSON(body)`

### ExtractPattern

`ExtractPattern(target, pattern)`

The `ExtractPattern` Converter returns a `pcommon.Map` struct that is a result of extracting named capture groups from the target string

`target` is a Getter that returns a string. `pattern` is a regex string.
If `target` is not a string, nil, or does not match the pattern, `ExtractPattern` will return an error.

Examples:

- `ExtractPattern(attributes["k8s.change_cause"], "GIT_SHA=(?P<git.sha>\w+)")`

- `ExtractPattern(body, "^(?P<timestamp>\\w+ \\w+ [0-9]+:[0-9]+:[0-9]+) (?P<hostname>([A-Za-z0-9-_]+)) (?P<process>\\w+)(\\[(?P<pid>\\d+)\\])?: (?P<message>.*)$")`

### SHA1

`SHA1(value)`
Expand Down
74 changes: 74 additions & 0 deletions pkg/ottl/ottlfuncs/func_extract_pattern.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package ottlfuncs

import (
"context"
"fmt"
"regexp"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
"go.opentelemetry.io/collector/pdata/pcommon"
)

type ExtractPatternArguments[K any] struct {
Target ottl.StringGetter[K] `ottlarg:"0"`
Pattern string `ottlarg:"1"`
}

func NewExtractPatternFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("ExtractPattern", &ExtractPatternArguments[K]{}, createExtractPatternFunction[K])
TylerHelmuth marked this conversation as resolved.
Show resolved Hide resolved
}

func createExtractPatternFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) {
args, ok := oArgs.(*ExtractPatternArguments[K])

if !ok {
return nil, fmt.Errorf("ExtractPatternFactory args must be of type *ExtractPatternArguments[K]")
}

return extractPattern(args.Target, args.Pattern)
}

func extractPattern[K any](target ottl.StringGetter[K], pattern string) (ottl.ExprFunc[K], error) {
r, err := regexp.Compile(pattern)
if err != nil {
return nil, fmt.Errorf("the pattern supplied to ExtractPattern is not a valid pattern: %w", err)
}

namedCaptureGroups := 0
for _, groupName := range r.SubexpNames() {
if groupName != "" {
namedCaptureGroups++
}
}

if namedCaptureGroups == 0 {
return nil, fmt.Errorf("no named capture groups in regex pattern")
TylerHelmuth marked this conversation as resolved.
Show resolved Hide resolved
}

return func(ctx context.Context, tCtx K) (interface{}, error) {
val, err := target.Get(ctx, tCtx)
if err != nil {
return nil, err
}

matches := r.FindStringSubmatch(val)
if matches == nil {
return nil, fmt.Errorf("regex pattern does not match")
TylerHelmuth marked this conversation as resolved.
Show resolved Hide resolved
}

parsedValues := map[string]interface{}{}
for i, subexp := range r.SubexpNames() {
if i == 0 {
// Skip whole match
continue
}
if subexp != "" {
parsedValues[subexp] = matches[i]
}
}

result := pcommon.NewMap()
err = result.FromRaw(parsedValues)
TylerHelmuth marked this conversation as resolved.
Show resolved Hide resolved
return result, err
}, nil
}
130 changes: 130 additions & 0 deletions pkg/ottl/ottlfuncs/func_extract_pattern_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package ottlfuncs

import (
"context"
"testing"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/pdata/pcommon"
)

func Test_extractPattern(t *testing.T) {
target := &ottl.StandardStringGetter[any]{
Getter: func(ctx context.Context, tCtx any) (interface{}, error) {
return `a=b c=d`, nil
},
}
tests := []struct {
name string
target ottl.StringGetter[any]
pattern string
want func(pcommon.Map)
}{
{
name: "parse regex",
target: target,
pattern: `^a=(?P<a>\w+)\s+c=(?P<c>\w+)$`,
want: func(expectedMap pcommon.Map) {
expectedMap.PutStr("a", "b")
expectedMap.PutStr("c", "d")
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
exprFunc, err := extractPattern(tt.target, tt.pattern)
assert.NoError(t, err)

result, err := exprFunc(context.Background(), nil)
assert.NoError(t, err)

resultMap, ok := result.(pcommon.Map)
require.True(t, ok)

expected := pcommon.NewMap()
tt.want(expected)

assert.Equal(t, expected.Len(), resultMap.Len())
expected.Range(func(k string, v pcommon.Value) bool {
ev, _ := expected.Get(k)
av, _ := resultMap.Get(k)
assert.Equal(t, ev, av)
return true
})
})
}
}

func Test_extractPattern_validation(t *testing.T) {
tests := []struct {
name string
target ottl.StringGetter[any]
pattern string
}{
{
name: "bad regex",
target: &ottl.StandardStringGetter[any]{
Getter: func(ctx context.Context, tCtx any) (interface{}, error) {
return "foobar", nil
},
},
pattern: "(",
},
{
name: "no named capture group",
target: &ottl.StandardStringGetter[any]{
Getter: func(ctx context.Context, tCtx any) (interface{}, error) {
return "foobar", nil
},
},
pattern: "(.*)",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
exprFunc, err := extractPattern[any](tt.target, tt.pattern)
assert.Error(t, err)
assert.Nil(t, exprFunc)
})
}
}

func Test_extractPattern_bad_input(t *testing.T) {
tests := []struct {
name string
target ottl.StringGetter[any]
pattern string
}{
{
name: "target is non-string",
target: &ottl.StandardStringGetter[any]{
Getter: func(ctx context.Context, tCtx any) (interface{}, error) {
return 123, nil
},
},
pattern: "(?P<line>.*)",
},
{
name: "target is nil",
target: &ottl.StandardStringGetter[any]{
Getter: func(ctx context.Context, tCtx any) (interface{}, error) {
return nil, nil
},
},
pattern: "(?P<line>.*)",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
exprFunc, err := extractPattern[any](tt.target, tt.pattern)
assert.NoError(t, err)

result, err := exprFunc(nil, nil)
assert.Error(t, err)
assert.Nil(t, result)
})
}
}
1 change: 1 addition & 0 deletions pkg/ottl/ottlfuncs/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func converters[K any]() []ottl.Factory[K] {
NewConcatFactory[K](),
NewConvertCaseFactory[K](),
NewDurationFactory[K](),
NewExtractPatternFactory[K](),
NewFnvFactory[K](),
NewIntFactory[K](),
NewIsMapFactory[K](),
Expand Down