Skip to content

OTTL Index function implementation. #40393

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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/ottl-index-function.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 an `Index(source, value)` OTTL function which returns the index of the first occurrence of `value` in `source`. The accepted source type is either `string` or `Slice`.

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

# (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: []
31 changes: 31 additions & 0 deletions pkg/ottl/e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1206,6 +1206,31 @@ func Test_e2e_converters(t *testing.T) {
tCtx.GetLogRecord().Attributes().PutInt("test", 2)
},
},
{
statement: `set(attributes["indexof"], Index("opentelemetry", "telemetry"))`,
want: func(tCtx ottllog.TransformContext) {
tCtx.GetLogRecord().Attributes().PutInt("indexof", 4)
},
},
{
statement: `set(attributes["indexof"], Index(attributes["slices"], "name"))`,
want: func(tCtx ottllog.TransformContext) {
tCtx.GetLogRecord().Attributes().PutInt("indexof", -1)
},
},
{
statement: `set(attributes["indexof"], Index(attributes["slices"], "slice2"))`,
want: func(tCtx ottllog.TransformContext) {
tCtx.GetLogRecord().Attributes().PutInt("indexof", 1)
},
},
{
// slice contains a map
statement: `set(attributes["indexof"], Index(attributes["slices"], attributes["slices"][2]))`,
want: func(tCtx ottllog.TransformContext) {
tCtx.GetLogRecord().Attributes().PutInt("indexof", 2)
},
},
}

for _, tt := range tests {
Expand Down Expand Up @@ -1706,6 +1731,12 @@ func constructLogTransformContext() ottllog.TransformContext {
thing2.PutStr("name", "bar")
thing2.PutInt("value", 5)

s3 := logRecord.Attributes().PutEmptySlice("slices")
s3.AppendEmpty().SetStr("slice1")
s3.AppendEmpty().SetStr("slice2")
s3m1 := s3.AppendEmpty().SetEmptyMap()
s3m1.PutStr("name", "foo")

return ottllog.NewTransformContext(logRecord, scope, resource, plog.NewScopeLogs(), plog.NewResourceLogs())
}

Expand Down
71 changes: 71 additions & 0 deletions pkg/ottl/ottlfuncs/func_index.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// 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"

"go.opentelemetry.io/collector/pdata/pcommon"

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

type IndexArguments[K any] struct {
Source ottl.Getter[K]
Value ottl.Getter[K]
}

func NewIndexFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("Index", &IndexArguments[K]{}, createIndexFunction[K])
}

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

if !ok {
return nil, errors.New("IndexFactory args must be of type *IndexArguments[K]")
}
return index(args.Source, args.Value), nil
}

func index[K any](source ottl.Getter[K], value ottl.Getter[K]) ottl.ExprFunc[K] {
return func(ctx context.Context, tCtx K) (any, error) {
sourceVal, err := source.Get(ctx, tCtx)
if err != nil {
return nil, err
}

valueVal, err := value.Get(ctx, tCtx)
if err != nil {
return nil, err
}

switch s := sourceVal.(type) {
case string:
// For string source, the value must be string
v, ok := valueVal.(string)
if !ok {
return nil, errors.New("when source is string, value must also be string")
}
return int64(strings.Index(s, v)), nil
case pcommon.Slice:
return findIndexInSlice(s, valueVal), nil
default:
return nil, errors.New("source must be string or slice type")
}
}
}

func findIndexInSlice(slice pcommon.Slice, value any) int64 {
comparator := ottl.NewValueComparator()
for i := 0; i < slice.Len(); i++ {
sliceValue := slice.At(i).AsRaw()
if comparator.Equal(sliceValue, value) {
return int64(i)
}
}
return -1
}
246 changes: 246 additions & 0 deletions pkg/ottl/ottlfuncs/func_index_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
// 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_index_string(t *testing.T) {
tests := []struct {
name string
source string
value string
expected int64
}{
{
name: "find substring in middle",
source: "hello world",
value: "world",
expected: 6,
},
{
name: "find substring at beginning",
source: "hello world",
value: "hello",
expected: 0,
},
{
name: "substring not found",
source: "hello world",
value: "universe",
expected: -1,
},
{
name: "empty substring",
source: "hello world",
value: "",
expected: 0, // Empty string is always found at index 0
},
{
name: "case sensitive search",
source: "Hello World",
value: "world",
expected: -1, // Case-sensitive, so 'world' isn't in 'Hello World'
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sourceExpr := ottl.StandardGetSetter[any]{
Getter: func(context.Context, any) (any, error) {
return tt.source, nil
},
}
valueExpr := ottl.StandardGetSetter[any]{
Getter: func(context.Context, any) (any, error) {
return tt.value, nil
},
}

indexFn := index(sourceExpr, valueExpr)
result, err := indexFn(context.Background(), nil)
assert.NoError(t, err)
assert.Equal(t, tt.expected, result)
})
}
}

func Test_index_pcommon_slice(t *testing.T) {
tests := []struct {
name string
setup func() pcommon.Slice
value any
expected int64
}{
{
name: "string slice with string value",
setup: func() pcommon.Slice {
slice := pcommon.NewSlice()
slice.AppendEmpty().SetStr("hello")
slice.AppendEmpty().SetStr("world")
slice.AppendEmpty().SetStr("opentelemetry")
return slice
},
value: "world",
expected: 1,
},
{
name: "int slice with int value",
setup: func() pcommon.Slice {
slice := pcommon.NewSlice()
slice.AppendEmpty().SetInt(1)
slice.AppendEmpty().SetInt(2)
slice.AppendEmpty().SetInt(3)
return slice
},
value: int64(2),
expected: 1,
},
{
name: "mixed type slice with bool value",
setup: func() pcommon.Slice {
slice := pcommon.NewSlice()
slice.AppendEmpty().SetStr("hello")
slice.AppendEmpty().SetInt(42)
slice.AppendEmpty().SetBool(true)
return slice
},
value: true,
expected: 2,
},
{
name: "value not found in slice",
setup: func() pcommon.Slice {
slice := pcommon.NewSlice()
slice.AppendEmpty().SetInt(1)
slice.AppendEmpty().SetInt(2)
slice.AppendEmpty().SetInt(3)
return slice
},
value: int64(5),
expected: -1,
},
{
name: "empty slice",
setup: pcommon.NewSlice,
value: "anything",
expected: -1,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
slice := tt.setup()

sourceExpr := ottl.StandardGetSetter[any]{
Getter: func(context.Context, any) (any, error) {
return slice, nil
},
}
valueExpr := ottl.StandardGetSetter[any]{
Getter: func(context.Context, any) (any, error) {
return tt.value, nil
},
}

indexFn := index(sourceExpr, valueExpr)
result, err := indexFn(context.Background(), nil)
assert.NoError(t, err)
assert.Equal(t, tt.expected, result)
})
}
}

func Test_index_error_cases(t *testing.T) {
tests := []struct {
name string
source any
value any
expectedErr string
}{
{
name: "source not string or pcommon.Slice",
source: 123,
value: "test",
expectedErr: "source must be string or slice type",
},
{
name: "string source with non-string value",
source: "hello world",
value: 123,
expectedErr: "when source is string, value must also be string",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sourceExpr := ottl.StandardGetSetter[any]{
Getter: func(context.Context, any) (any, error) {
return tt.source, nil
},
}
valueExpr := ottl.StandardGetSetter[any]{
Getter: func(context.Context, any) (any, error) {
return tt.value, nil
},
}

indexFn := index(sourceExpr, valueExpr)
_, err := indexFn(context.Background(), nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), tt.expectedErr)
})
}
}

func Test_IndexFactory(t *testing.T) {
t.Run("factory creation", func(t *testing.T) {
factory := NewIndexFactory[any]()
assert.Equal(t, "Index", factory.Name())
})

t.Run("default arguments", func(t *testing.T) {
factory := NewIndexFactory[any]()
args := factory.CreateDefaultArguments()

assert.IsType(t, &IndexArguments[any]{}, args)
})

t.Run("function creation", func(t *testing.T) {
factory := NewIndexFactory[any]()
args := factory.CreateDefaultArguments()
// Set up the arguments appropriately
indexArgs, ok := args.(*IndexArguments[any])
require.True(t, ok)
indexArgs.Source = ottl.StandardGetSetter[any]{
Getter: func(context.Context, any) (any, error) {
return "test source", nil
},
}
indexArgs.Value = ottl.StandardGetSetter[any]{
Getter: func(context.Context, any) (any, error) {
return "test", nil
},
}

fn, err := factory.CreateFunction(ottl.FunctionContext{}, args)
assert.NoError(t, err)
assert.NotNil(t, fn)
})

t.Run("invalid arguments type", func(t *testing.T) {
// This tests the error case in createIndexFunction
_, err := createIndexFunction[any](ottl.FunctionContext{}, "invalid args")
assert.Error(t, err)
assert.Contains(t, err.Error(), "IndexFactory args must be of type *IndexArguments[K]")
})
}
1 change: 1 addition & 0 deletions pkg/ottl/ottlfuncs/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ func converters[K any]() []ottl.Factory[K] {
NewHasSuffixFactory[K](),
NewHourFactory[K](),
NewHoursFactory[K](),
NewIndexFactory[K](),
NewInsertXMLFactory[K](),
NewIntFactory[K](),
NewIsBoolFactory[K](),
Expand Down