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] Conflict resolution strategy for set function #32020

Closed
wants to merge 12 commits into from
27 changes: 27 additions & 0 deletions .chloggen/set-conflicts.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: Added a conflict resolution strategy argument for `set` function

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

# (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]
11 changes: 10 additions & 1 deletion pkg/ottl/ottlfuncs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -332,14 +332,23 @@ If using OTTL outside of collector configuration, `$` should not be escaped and

### set

`set(target, value)`
`set(target, value, Optional[conflict_resolution_strategy])`

The `set` function allows users to set a telemetry field using a value.

`target` is a path expression to a telemetry field. `value` is any value type. If `value` resolves to `nil`, e.g. it references an unset map value, there will be no action.

How the underlying telemetry field is updated is decided by the path expression implementation provided by the user to the `ottl.ParseStatements`.

`conflict_resolution_strategy` specifies behavior in case of conflict and can fall into following cases:

- **upsert**: Is the default behavior. This setting results in creating field in case it's missing or updating existing value.
- **update**: This setting updates only existing value. In case value is missing no action is taken.
- **insert**: Creates a new field in case it's not present. In case field is already present no action is taken.
- **fail**: Similar to `insert` creates a field in case it's missing but returns an error otherwise.

> In case field is preset but contains a zero value (e.g empty string, 0 for int64) it is considered missing.

Examples:

- `set(attributes["http.path"], "/foo")`
Expand Down
122 changes: 118 additions & 4 deletions pkg/ottl/ottlfuncs/func_set.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,28 @@ package ottlfuncs // import "github.com/open-telemetry/opentelemetry-collector-c

import (
"context"
"errors"
"fmt"

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

var (
ErrValueAlreadyPresent = errors.New("value already present")
)

const (
setConflictUpsert = "upsert"
setConflictFail = "fail"
setConflictInsert = "insert"
setConflictUpdate = "update"
)

type SetArguments[K any] struct {
Target ottl.Setter[K]
Value ottl.Getter[K]
Target ottl.GetSetter[K]
Value ottl.Getter[K]
ConflictStrategy ottl.Optional[string]
}

func NewSetFactory[K any]() ottl.Factory[K] {
Expand All @@ -26,10 +40,22 @@ func createSetFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ott
return nil, fmt.Errorf("SetFactory args must be of type *SetArguments[K]")
}

return set(args.Target, args.Value), nil
return set(args.Target, args.Value, args.ConflictStrategy)
}

func set[K any](target ottl.Setter[K], value ottl.Getter[K]) ottl.ExprFunc[K] {
func set[K any](target ottl.GetSetter[K], value ottl.Getter[K], strategy ottl.Optional[string]) (ottl.ExprFunc[K], error) {
conflictStrategy := setConflictUpsert
if !strategy.IsEmpty() {
conflictStrategy = strategy.Get()
}

if conflictStrategy != setConflictUpsert &&
conflictStrategy != setConflictUpdate &&
conflictStrategy != setConflictFail &&
conflictStrategy != setConflictInsert {
return nil, fmt.Errorf("invalid value for conflict strategy, %v, must be %q, %q, %q or %q", conflictStrategy, setConflictUpsert, setConflictUpdate, setConflictFail, setConflictUpsert)
}

return func(ctx context.Context, tCtx K) (any, error) {
val, err := value.Get(ctx, tCtx)
if err != nil {
Expand All @@ -38,11 +64,99 @@ func set[K any](target ottl.Setter[K], value ottl.Getter[K]) ottl.ExprFunc[K] {

// No fields currently support `null` as a valid type.
if val != nil {
oldVal, err := target.Get(ctx, tCtx)
if err != nil {
return nil, err
}

valueMissing := oldVal == nil || isDefaultValue(oldVal)
switch conflictStrategy {
case setConflictUpsert:
// overwrites if present or create when missing
case setConflictUpdate:
// update existing field with a new value. If the field does not exist, then no action will be taken
if valueMissing {
return nil, nil
}
case setConflictFail:
// fail if target field present
if !valueMissing {
return nil, ErrValueAlreadyPresent
}
case setConflictInsert:
// noop if target field present
if !valueMissing {
return nil, nil
}
}

err = target.Set(ctx, tCtx, val)
if err != nil {
return nil, err
}
}
return nil, nil
}, nil
}

func isDefaultValue(val any) bool {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

if we have something better for this please let me know. i see following pattern repeated for many use cases

switch v := val.(type) {
case string:
return len(v) == 0
case bool:
return !v
case float64:
return v == 0
case int64:
return v == 0

case []byte:
return len(v) == 0
case []string:
return len(v) == 0
case []int64:
return len(v) == 0
case []float64:
return len(v) == 0
case [][]byte:
return len(v) == 0
case []any:
return len(v) == 0

case pcommon.ByteSlice:
return v.Len() == 0
case pcommon.Float64Slice:
return v.Len() == 0
case pcommon.UInt64Slice:
return v.Len() == 0
case pcommon.Slice:
return v.Len() == 0

case pcommon.Value:
if v.Type() == pcommon.ValueTypeStr ||
v.Type() == pcommon.ValueTypeBytes ||
v.Type() == pcommon.ValueTypeSlice {
return v.Bytes().Len() == 0
}
if v.Type() == pcommon.ValueTypeBool {
return !v.Bool()
}
if v.Type() == pcommon.ValueTypeDouble {
return v.Double() == 0
}
if v.Type() == pcommon.ValueTypeInt {
return v.Int() == 0
}

if v.Type() == pcommon.ValueTypeEmpty {
return true
}

case pcommon.Map:
return v.Len() == 0
case map[string]any:
return v == nil
}

return false
}
Loading
Loading