Skip to content

Commit

Permalink
[pkg/ottl] Support for append (#33017)
Browse files Browse the repository at this point in the history
**Description:** 
Added new ottl function `append(target, Optional[single_value],
Optional[slice_value])`

Append function appends one or more values to an existing array if the
field already exists and it is an array.
It should convert scalar values into an array if the field exists but is
not an array
Creates an array containing the provided values if the field doesn’t
exist

Implemented this with few assumptions up for a discussion
- implemented this as a function modifying target rather than converter
returning merged arrays
- working with strings so far, resulting in `[]string` after concat
- merging integers, boolean... not implemented, as I haven't found use
for these use-cases, could be accomplished with retyping them later
after append produces `[]string`

**Link to tracking Issue:** [<Issue number if
applicable>](#32141)

**Testing:** 
Added unit tests with intended behavior
Tested also with this config
```yaml
receivers:
  filelog:
    include: [ system.log ]
    start_at: beginning

exporters:
  debug:
    verbosity: detailed
    sampling_initial: 10000
    sampling_thereafter: 10000

processors:
  transform:
    error_mode: ignore
    log_statements:
      - context: log
        statements: 
          - append(attributes["empty_tags"], "my empty value") # non existing field should be created
          - set(attributes["tags"], "my funky value") # init with single value
          - append(attributes["tags"], "my file value") # append to scalar value
          - set(attributes["tags_copy"], attributes["tags"]) # make a copy 
          - append(attributes["tags_copy"], "my third value") # append to slice
          - append(attributes["tags_copy"], values = ["my third value", "my last value"]) # append to slice

service:
  pipelines:
    logs:
      receivers: [filelog]
      processors: [transform]
      exporters:
        - debug
```

Expecting this result
```
Attributes:
  -> log.file.name: Str(system.log)
  -> empty_tags: Slice(["my empty value"])
  -> tags: Slice(["my funky value","my file value"])
  -> tags_copy: Slice(["my funky value","my file value","my third value"])
```

**Documentation:** updated README

---------

Co-authored-by: Tyler Helmuth <[email protected]>
Co-authored-by: Evan Bradley <[email protected]>
  • Loading branch information
3 people authored Jun 10, 2024
1 parent 431f424 commit 4b517cf
Show file tree
Hide file tree
Showing 6 changed files with 912 additions and 0 deletions.
27 changes: 27 additions & 0 deletions .chloggen/ottl_append.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: Introducing `append` function for appending items into an existing array

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

# (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]
39 changes: 39 additions & 0 deletions pkg/ottl/e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,45 @@ func Test_e2e_editors(t *testing.T) {
tCtx.GetLogRecord().Attributes().PutStr("total.string", "1")
},
},
{
statement: `append(attributes["foo"]["slice"], "sample_value")`,
want: func(tCtx ottllog.TransformContext) {
v, _ := tCtx.GetLogRecord().Attributes().Get("foo")
sv, _ := v.Map().Get("slice")
s := sv.Slice()
s.AppendEmpty().SetStr("sample_value")

},
},
{
statement: `append(attributes["foo"]["flags"], "sample_value")`,
want: func(tCtx ottllog.TransformContext) {
v, _ := tCtx.GetLogRecord().Attributes().Get("foo")
s := v.Map().PutEmptySlice("flags")
s.AppendEmpty().SetStr("pass")
s.AppendEmpty().SetStr("sample_value")

},
},
{
statement: `append(attributes["foo"]["slice"], values=[5,6])`,
want: func(tCtx ottllog.TransformContext) {
v, _ := tCtx.GetLogRecord().Attributes().Get("foo")
sv, _ := v.Map().Get("slice")
s := sv.Slice()
s.AppendEmpty().SetInt(5)
s.AppendEmpty().SetInt(6)
},
},
{
statement: `append(attributes["foo"]["new_slice"], values=[5,6])`,
want: func(tCtx ottllog.TransformContext) {
v, _ := tCtx.GetLogRecord().Attributes().Get("foo")
s := v.Map().PutEmptySlice("new_slice")
s.AppendEmpty().SetInt(5)
s.AppendEmpty().SetInt(6)
},
},
}

for _, tt := range tests {
Expand Down
14 changes: 14 additions & 0 deletions pkg/ottl/ottlfuncs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Editors:

Available Editors:

- [append](#append)
- [delete_key](#delete_key)
- [delete_matching_keys](#delete_matching_keys)
- [keep_matching_keys](#keep_matching_keys)
Expand All @@ -59,6 +60,19 @@ Available Editors:
- [set](#set)
- [truncate_all](#truncate_all)

### append

`append(target, Optional[value], Optional[values])`

The `append` function appends single or multiple string values to `target`.
`append` converts scalar values into an array if the field exists but is not an array, and creates an array containing the provided values if the field doesn’t exist.

Resulting field is always of type `pcommon.Slice` and will not convert the types of existing or new items in the slice. This means that it is possible to create a slice whose elements have different types. Be careful when using `append` to set attribute values, as this will produce values that are not possible to create through OpenTelemetry APIs [according to](https://opentelemetry.io/docs/specs/otel/common/#attribute) the OpenTelemetry specification.

- `append(attributes["tags"], "prod")`
- `append(attributes["tags"], values = ["staging", "staging:east"])`
- `append(attributes["tags_copy"], attributes["tags"])`

### delete_key

`delete_key(target, key)`
Expand Down
134 changes: 134 additions & 0 deletions pkg/ottl/ottlfuncs/func_append.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// 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"
"fmt"

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

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

type AppendArguments[K any] struct {
Target ottl.GetSetter[K]
Value ottl.Optional[ottl.Getter[K]]
Values ottl.Optional[[]ottl.Getter[K]]
}

func NewAppendFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("append", &AppendArguments[K]{}, createAppendFunction[K])
}
func createAppendFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) {
args, ok := oArgs.(*AppendArguments[K])
if !ok {
return nil, fmt.Errorf("AppendFactory args must be of type *Appendrguments[K]")
}

return appendTo(args.Target, args.Value, args.Values)
}

func appendTo[K any](target ottl.GetSetter[K], value ottl.Optional[ottl.Getter[K]], values ottl.Optional[[]ottl.Getter[K]]) (ottl.ExprFunc[K], error) {
if value.IsEmpty() && values.IsEmpty() {
return nil, fmt.Errorf("at least one of the optional arguments ('value' or 'values') must be provided")
}

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

// init res with target values
var res []any

if t != nil {
switch targetType := t.(type) {
case pcommon.Slice:
res = append(res, targetType.AsRaw()...)
case pcommon.Value:
switch targetType.Type() {
case pcommon.ValueTypeEmpty:
res = append(res, targetType.Str())
case pcommon.ValueTypeStr:
res = append(res, targetType.Str())
case pcommon.ValueTypeInt:
res = append(res, targetType.Int())
case pcommon.ValueTypeDouble:
res = append(res, targetType.Double())
case pcommon.ValueTypeBool:
res = append(res, targetType.Bool())
case pcommon.ValueTypeSlice:
res = append(res, targetType.Slice().AsRaw()...)
default:
return nil, fmt.Errorf("unsupported type of target field: %q", targetType.Type())
}

case []string:
res = appendMultiple(res, targetType)
case []any:
res = append(res, targetType...)
case []int64:
res = appendMultiple(res, targetType)
case []bool:
res = appendMultiple(res, targetType)
case []float64:
res = appendMultiple(res, targetType)

case string:
res = append(res, targetType)
case int64:
res = append(res, targetType)
case bool:
res = append(res, targetType)
case float64:
res = append(res, targetType)
case any:
res = append(res, targetType)
default:
return nil, fmt.Errorf("unsupported type of target field: '%T'", t)
}
}

appendGetterFn := func(g ottl.Getter[K]) error {
v, err := g.Get(ctx, tCtx)
if err != nil {
return err
}
res = append(res, v)
return nil
}

if !value.IsEmpty() {
getter := value.Get()
if err := appendGetterFn(getter); err != nil {
return nil, err
}
}
if !values.IsEmpty() {
getters := values.Get()
for _, g := range getters {
if err := appendGetterFn(g); err != nil {
return nil, err
}
}
}

// retype []any to Slice, having []any sometimes misbehaves and nils pcommon.Value
resSlice := pcommon.NewSlice()
if err := resSlice.FromRaw(res); err != nil {
return nil, err
}

return nil, target.Set(ctx, tCtx, resSlice)
}, nil
}

func appendMultiple[K any](target []any, values []K) []any {
for _, v := range values {
target = append(target, v)
}
return target
}
Loading

0 comments on commit 4b517cf

Please sign in to comment.