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 SliceToMap function #35412

Merged
Merged
Show file tree
Hide file tree
Changes from 6 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
2 changes: 1 addition & 1 deletion cmd/opampsupervisor/examples/supervisor_darwin.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ capabilities:
reports_remote_config: true

agent:
executable: ../../bin/otelcontribcol_darwin_amd64
executable: ../../bin/otelcontribcol_darwin_arm64

storage:
directory: .
75 changes: 72 additions & 3 deletions pkg/ottl/e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ func Test_e2e_editors(t *testing.T) {
tCtx.GetLogRecord().Attributes().Remove("flags")
tCtx.GetLogRecord().Attributes().Remove("total.string")
tCtx.GetLogRecord().Attributes().Remove("foo")
tCtx.GetLogRecord().Attributes().Remove("things")
},
},
{
Expand All @@ -67,6 +68,15 @@ func Test_e2e_editors(t *testing.T) {
tCtx.GetLogRecord().Attributes().PutStr("foo.flags", "pass")
tCtx.GetLogRecord().Attributes().PutStr("foo.slice.0", "val")
tCtx.GetLogRecord().Attributes().PutStr("foo.nested.test", "pass")

tCtx.GetLogRecord().Attributes().Remove("things")
m1 := tCtx.GetLogRecord().Attributes().PutEmptyMap("things.0")
m1.PutStr("name", "foo")
m1.PutInt("value", 2)

m2 := tCtx.GetLogRecord().Attributes().PutEmptyMap("things.1")
m2.PutStr("name", "bar")
m2.PutInt("value", 5)
},
},
{
Expand All @@ -84,12 +94,29 @@ func Test_e2e_editors(t *testing.T) {
m.PutStr("test.foo.flags", "pass")
m.PutStr("test.foo.slice.0", "val")
m.PutStr("test.foo.nested.test", "pass")

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@evan-bradley @TylerHelmuth - This is not related to the function implemented in this PR, but after adding a slice of nested objects to the test attributes I found that the flatten function seems to not flatten the attributes of nested objects within a slice, but rather leaves the objects within the slice unchanged - is this intended or is this a bug in that function?

Also, when setting the depth to 0 (as in the test case below), slices at the top level of the input of the flatten function will still be flattened.

Please let me know if this behavior is intended or if this may be a bug - If it's the latter, I can create an issue for that and work on a fix

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These sound like bugs.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These sound like bugs to me, too. Could you file an issue?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have created two issues (I believe these are two distinct bugs):

#36161
#36162

m1 := m.PutEmptyMap("test.things.0")
m1.PutStr("name", "foo")
m1.PutInt("value", 2)

m2 := m.PutEmptyMap("test.things.1")
m2.PutStr("name", "bar")
m2.PutInt("value", 5)
m.CopyTo(tCtx.GetLogRecord().Attributes())
},
},
{
statement: `flatten(attributes, depth=0)`,
want: func(_ ottllog.TransformContext) {},
want: func(tCtx ottllog.TransformContext) {
tCtx.GetLogRecord().Attributes().Remove("things")
m1 := tCtx.GetLogRecord().Attributes().PutEmptyMap("things.0")
m1.PutStr("name", "foo")
m1.PutInt("value", 2)

m2 := tCtx.GetLogRecord().Attributes().PutEmptyMap("things.1")
m2.PutStr("name", "bar")
m2.PutInt("value", 5)
},
},
{
statement: `flatten(attributes, depth=1)`,
Expand All @@ -105,8 +132,17 @@ func Test_e2e_editors(t *testing.T) {
m.PutStr("foo.bar", "pass")
m.PutStr("foo.flags", "pass")
m.PutStr("foo.slice.0", "val")
m2 := m.PutEmptyMap("foo.nested")
m2.PutStr("test", "pass")

m1 := m.PutEmptyMap("things.0")
m1.PutStr("name", "foo")
m1.PutInt("value", 2)

m2 := m.PutEmptyMap("things.1")
m2.PutStr("name", "bar")
m2.PutInt("value", 5)

m3 := m.PutEmptyMap("foo.nested")
m3.PutStr("test", "pass")
m.CopyTo(tCtx.GetLogRecord().Attributes())
},
},
Expand All @@ -117,6 +153,7 @@ func Test_e2e_editors(t *testing.T) {
tCtx.GetLogRecord().Attributes().Remove("http.path")
tCtx.GetLogRecord().Attributes().Remove("http.url")
tCtx.GetLogRecord().Attributes().Remove("foo")
tCtx.GetLogRecord().Attributes().Remove("things")
},
},
{
Expand All @@ -131,6 +168,7 @@ func Test_e2e_editors(t *testing.T) {
tCtx.GetLogRecord().Attributes().Remove("http.url")
tCtx.GetLogRecord().Attributes().Remove("flags")
tCtx.GetLogRecord().Attributes().Remove("foo")
tCtx.GetLogRecord().Attributes().Remove("things")
},
},
{
Expand Down Expand Up @@ -845,6 +883,28 @@ func Test_e2e_converters(t *testing.T) {
m.PutStr("user_agent.version", "7.81.0")
},
},
{
statement: `set(attributes["test"], SliceToMap(attributes["things"], ["name"]))`,
want: func(tCtx ottllog.TransformContext) {
m := tCtx.GetLogRecord().Attributes().PutEmptyMap("test")
thing1 := m.PutEmptyMap("foo")
thing1.PutStr("name", "foo")
thing1.PutInt("value", 2)

thing2 := m.PutEmptyMap("bar")
thing2.PutStr("name", "bar")
thing2.PutInt("value", 5)
},
},
{
statement: `set(attributes["test"], SliceToMap(attributes["things"], ["name"], ["value"]))`,
want: func(tCtx ottllog.TransformContext) {
m := tCtx.GetLogRecord().Attributes().PutEmptyMap("test")
m.PutInt("foo", 2)
m.PutInt("bar", 5)

},
},
}

for _, tt := range tests {
Expand Down Expand Up @@ -1036,6 +1096,15 @@ func constructLogTransformContext() ottllog.TransformContext {
m2 := m.PutEmptyMap("nested")
m2.PutStr("test", "pass")

s2 := logRecord.Attributes().PutEmptySlice("things")
thing1 := s2.AppendEmpty().SetEmptyMap()
thing1.PutStr("name", "foo")
thing1.PutInt("value", 2)

thing2 := s2.AppendEmpty().SetEmptyMap()
thing2.PutStr("name", "bar")
thing2.PutInt("value", 5)

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

Expand Down
54 changes: 54 additions & 0 deletions pkg/ottl/ottlfuncs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,7 @@ Available Converters:
- [SHA1](#sha1)
- [SHA256](#sha256)
- [SHA512](#sha512)
- [SliceToMap](#slicetomap)
- [Sort](#sort)
- [SpanID](#spanid)
- [Split](#split)
Expand Down Expand Up @@ -1357,6 +1358,59 @@ Examples:

- `SHA512("name")`

### SliceToMap

`SliceToMap(target, keyPath, Optional[valuePath])`
TylerHelmuth marked this conversation as resolved.
Show resolved Hide resolved

The `SliceToMap` converter converts a slice of objects to a map. The name of the keys for the map entries
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we describe how this could be used to address slice items? I think we should highlight the fact that this allows limited list manipulation in OTTL.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have added a small sample for how the converted map could be used afterwards now.

is determined by `keyPath`, which points to the value of an attribute within each slice item. Note that
the `keyPath` must resolve to a string value, otherwise the converter will not be able to convert the item
to a map entry.
The optional `valuePath` determines which attribute should be used as the value for the map entry. If no
`valuePath` is defined, the value of the map entry will be the same as the original slice item.

Examples:

The examples below will convert the following input:

```yaml
attributes:
hello: world
things:
- name: foo
value: 2
- name: bar
value: 5
```

- `SliceToMap(attributes["things"], ["name"])`:

This converts the input above to the following:

```yaml
attributes:
hello: world
things:
foo:
name: foo
value: 2
bar:
name: bar
value: 5
```

- `Associate(attributes["things"], ["name"], ["details", "value"])`:
bacherfl marked this conversation as resolved.
Show resolved Hide resolved

This converts the input above to the following:

```yaml
attributes:
hello: world
things:
foo: 2
bar: 5
```

### Sort

`Sort(target, Optional[order])`
Expand Down
111 changes: 111 additions & 0 deletions pkg/ottl/ottlfuncs/func_slice_to_map.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

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

"go.opentelemetry.io/collector/pdata/pcommon"
"golang.org/x/net/context"

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

type SliceToMapArguments[K any] struct {
Target ottl.Getter[K]
TylerHelmuth marked this conversation as resolved.
Show resolved Hide resolved
KeyPath []string
ValuePath ottl.Optional[[]string]
}

func NewSliceToMapFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("SliceToMap", &SliceToMapArguments[K]{}, sliceToMapFunction[K])
}

func sliceToMapFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) {
args, ok := oArgs.(*SliceToMapArguments[K])
if !ok {
return nil, fmt.Errorf("AssociateFactory args must be of type *SliceToMapArguments[K")
bacherfl marked this conversation as resolved.
Show resolved Hide resolved
}

return SliceToMap(args.Target, args.KeyPath, args.ValuePath)
}

func SliceToMap[K any](target ottl.Getter[K], keyPath []string, valuePath ottl.Optional[[]string]) (ottl.ExprFunc[K], error) {
bacherfl marked this conversation as resolved.
Show resolved Hide resolved
return func(ctx context.Context, tCtx K) (any, error) {
if len(keyPath) == 0 {
return nil, fmt.Errorf("key path must contain at least one element")
}
djaglowski marked this conversation as resolved.
Show resolved Hide resolved
val, err := target.Get(ctx, tCtx)
if err != nil {
return nil, err
}

switch v := val.(type) {
case []any:
return sliceToMap(v, keyPath, valuePath)
case pcommon.Slice:
return sliceToMap(v.AsRaw(), keyPath, valuePath)
default:
return nil, fmt.Errorf("unsupported type provided to SliceToMap function: %T", v)
}
}, nil
}

func sliceToMap(v []any, keyPath []string, valuePath ottl.Optional[[]string]) (any, error) {
result := make(map[string]any, len(v))
for _, elem := range v {
switch e := elem.(type) {
case map[string]any:
bacherfl marked this conversation as resolved.
Show resolved Hide resolved
obj, err := extractValue(e, keyPath)
if err != nil {
continue
}

var key string
switch k := obj.(type) {
case string:
key = k
default:
continue
}
bacherfl marked this conversation as resolved.
Show resolved Hide resolved

if valuePath.IsEmpty() {
result[key] = e
continue
}
obj, err = extractValue(e, valuePath.Get())
djaglowski marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
continue
}
result[key] = obj
default:
continue
}
}
m := pcommon.NewMap()
if err := m.FromRaw(result); err != nil {
return nil, fmt.Errorf("could not create pcommon.Map from result: %w", err)
}

return m, nil
}

func extractValue(v map[string]any, path []string) (any, error) {
if len(path) == 0 {
return nil, fmt.Errorf("must provide at least one path item")
}
obj, ok := v[path[0]]
if !ok {
return nil, fmt.Errorf("provided object does not contain the path %v", path)
}
if len(path) == 1 {
return obj, nil
}

switch o := obj.(type) {
case map[string]any:
return extractValue(o, path[1:])
default:
return nil, fmt.Errorf("provided object does not contain the path %v", path)
}
bacherfl marked this conversation as resolved.
Show resolved Hide resolved
}
Loading
Loading