Skip to content

[pkg/ottl] Add support for HasPrefix and HasSuffix #39825

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

Merged
merged 1 commit into from
May 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .chloggen/has-suffix-prefix.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 support for HasPrefix and HasSuffix functions

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

# (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: []
14 changes: 14 additions & 0 deletions pkg/ottl/e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1263,6 +1263,20 @@ func Test_e2e_ottl_features(t *testing.T) {
tCtx.GetLogRecord().SetSeverityNumber(2)
},
},
{
name: "Using HasPrefix",
statement: `set(attributes["test"], "pass") where HasPrefix(body, "operation")`,
want: func(tCtx ottllog.TransformContext) {
tCtx.GetLogRecord().Attributes().PutStr("test", "pass")
},
},
{
name: "Using HasSuffix",
statement: `set(attributes["test"], "pass") where HasSuffix(body, "tionA")`,
want: func(tCtx ottllog.TransformContext) {
tCtx.GetLogRecord().Attributes().PutStr("test", "pass")
},
},
{
name: "Using hex",
statement: `set(attributes["test"], "pass") where trace_id == TraceID(0x0102030405060708090a0b0c0d0e0f10)`,
Expand Down
40 changes: 40 additions & 0 deletions pkg/ottl/ottlfuncs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,8 @@ Available Converters:
- [Format](#format)
- [FormatTime](#formattime)
- [GetXML](#getxml)
- [HasPrefix](#hasprefix)
- [HasSuffix](#hassuffix)
- [Hex](#hex)
- [Hour](#hour)
- [Hours](#hours)
Expand Down Expand Up @@ -959,6 +961,44 @@ Get `bar` from `<a foo="bar"/>`

- `GetXML(log.body, "/a/@foo")`

### HasPrefix

`HasPrefix(value, prefix)`

The `HasPrefix` function returns a boolean value indicating whether a given string `value` begins with a given `prefix`.

The returned type is `bool`.

If the `value` is not a string or does not exist, the `HasPrefix` converter will return an error.

The `value` is either a path expression to a telemetry field to retrieve or a literal.

Examples:

- `HasPrefix(resource.attributes["service.name"], "ingest_")`


- `HasPrefix("ingest_service", "ingest_")`

### HasSuffix

`HasSuffix(value, suffix)`

The `HasSuffix` function returns a boolean value indicating whether a given string `value` ends with a given `suffix`.

The returned type is `bool`.

If the `value` is not a string or does not exist, the `HasSuffix` converter will return an error.

The `value` is either a path expression to a telemetry field to retrieve or a literal.

Examples:

- `HasSuffix(resource.attributes["service.name"], "_service")`


- `HasSuffix("ingest_service", "_service")`

### Hex

`Hex(value)`
Expand Down
41 changes: 41 additions & 0 deletions pkg/ottl/ottlfuncs/func_has_prefix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ottlfuncs // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottlfuncs"

import (
"context"
"errors"
"strings"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
)

type HasPrefixArguments[K any] struct {
Target ottl.StringGetter[K]
Prefix string
}

func NewHasPrefixFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("HasPrefix", &HasPrefixArguments[K]{}, createHasPrefixFunction[K])
}

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

if !ok {
return nil, errors.New("HasPrefixFactory args must be of type *HasPrefixArguments[K]")
}

return HasPrefix(args.Target, args.Prefix)
}

func HasPrefix[K any](target ottl.StringGetter[K], prefix string) (ottl.ExprFunc[K], error) {
return func(ctx context.Context, tCtx K) (any, error) {
val, err := target.Get(ctx, tCtx)
if err != nil {
return nil, err
}
return strings.HasPrefix(val, prefix), nil
}, nil
}
74 changes: 74 additions & 0 deletions pkg/ottl/ottlfuncs/func_has_prefix_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ottlfuncs

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/pdata/pcommon"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
)

func Test_HasPrefix(t *testing.T) {
tests := []struct {
name string
target any
prefix string
expected bool
}{
{
name: "has prefix true",
target: "hello world",
prefix: "hello ",
expected: true,
},
{
name: "has prefix false",
target: "hello world",
prefix: " world",
expected: false,
},
{
name: "target pcommon.Value",
target: pcommon.NewValueStr("hello world"),
prefix: `hello`,
expected: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
factory := NewHasPrefixFactory[any]()
exprFunc, err := factory.CreateFunction(
ottl.FunctionContext{},
&HasPrefixArguments[any]{
Target: ottl.StandardStringGetter[any]{
Getter: func(_ context.Context, _ any) (any, error) {
return tt.target, nil
},
},
Prefix: tt.prefix,
})
assert.NoError(t, err)
result, err := exprFunc(context.Background(), nil)
require.NoError(t, err)
assert.Equal(t, tt.expected, result)
})
}
}

func Test_HasPrefix_Error(t *testing.T) {
target := &ottl.StandardStringGetter[any]{
Getter: func(_ context.Context, _ any) (any, error) {
return true, nil
},
}
exprFunc, err := HasPrefix[any](target, "test")
assert.NoError(t, err)
_, err = exprFunc(context.Background(), nil)
require.Error(t, err)
}
41 changes: 41 additions & 0 deletions pkg/ottl/ottlfuncs/func_has_suffix.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ottlfuncs // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottlfuncs"

import (
"context"
"errors"
"strings"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
)

type HasSuffixArguments[K any] struct {
Target ottl.StringGetter[K]
Suffix string
}

func NewHasSuffixFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("HasSuffix", &HasSuffixArguments[K]{}, createHasSuffixFunction[K])
}

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

if !ok {
return nil, errors.New("HasSuffixFactory args must be of type *HasSuffixArguments[K]")
}

return HasSuffix(args.Target, args.Suffix)
}

func HasSuffix[K any](target ottl.StringGetter[K], suffix string) (ottl.ExprFunc[K], error) {
return func(ctx context.Context, tCtx K) (any, error) {
val, err := target.Get(ctx, tCtx)
if err != nil {
return nil, err
}
return strings.HasSuffix(val, suffix), nil
}, nil
}
74 changes: 74 additions & 0 deletions pkg/ottl/ottlfuncs/func_has_suffix_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ottlfuncs

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/pdata/pcommon"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
)

func Test_HasSuffix(t *testing.T) {
tests := []struct {
name string
target any
suffix string
expected bool
}{
{
name: "has suffix true",
target: "hello world",
suffix: " world",
expected: true,
},
{
name: "has suffix false",
target: "hello world",
suffix: "hello ",
expected: false,
},
{
name: "target pcommon.Value",
target: pcommon.NewValueStr("hello world"),
suffix: `world`,
expected: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
factory := NewHasSuffixFactory[any]()
exprFunc, err := factory.CreateFunction(
ottl.FunctionContext{},
&HasSuffixArguments[any]{
Target: ottl.StandardStringGetter[any]{
Getter: func(_ context.Context, _ any) (any, error) {
return tt.target, nil
},
},
Suffix: tt.suffix,
})
assert.NoError(t, err)
result, err := exprFunc(context.Background(), nil)
require.NoError(t, err)
assert.Equal(t, tt.expected, result)
})
}
}

func Test_HasSuffix_Error(t *testing.T) {
target := &ottl.StandardStringGetter[any]{
Getter: func(_ context.Context, _ any) (any, error) {
return true, nil
},
}
exprFunc, err := HasSuffix[any](target, "test")
assert.NoError(t, err)
_, err = exprFunc(context.Background(), nil)
require.Error(t, err)
}
2 changes: 2 additions & 0 deletions pkg/ottl/ottlfuncs/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ func converters[K any]() []ottl.Factory[K] {
NewExtractGrokPatternsFactory[K](),
NewFnvFactory[K](),
NewGetXMLFactory[K](),
NewHasPrefixFactory[K](),
NewHasSuffixFactory[K](),
NewHourFactory[K](),
NewHoursFactory[K](),
NewInsertXMLFactory[K](),
Expand Down
Loading