-
Notifications
You must be signed in to change notification settings - Fork 2.5k
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 Sort converter #34283
Merged
Merged
Changes from 18 commits
Commits
Show all changes
27 commits
Select commit
Hold shift + click to select a range
07215d1
Add OTTL sort converter
kaisecheng 04366f5
support mixed of numeric types to sort as double
kaisecheng e2b90e1
change log
kaisecheng 73ecb89
add support to array type
kaisecheng dab7c86
Update pkg/ottl/ottlfuncs/func_sort.go
kaisecheng 2e36574
- add support to pcommon.Value
kaisecheng d43e95f
update doc
kaisecheng 447df3e
lint
kaisecheng 028744e
tidy
kaisecheng 1eb08f3
- preserve the data types in the sort result
kaisecheng a0d9791
update doc
kaisecheng d676f1a
fix unit test
kaisecheng 4568ca0
Merge branch 'main' into ottl_sort_func
kaisecheng d166048
preserve the data type for boolean array
kaisecheng 524e546
rename
kaisecheng 8f2acd1
Merge branch 'main' of github.com:open-telemetry/opentelemetry-collec…
kaisecheng a13bdbc
fix CI codegen
kaisecheng 8c0e371
Merge branch 'main' into ottl_sort_func
kaisecheng 1bb3d86
Update pkg/ottl/ottlfuncs/README.md
kaisecheng 2894981
Update pkg/ottl/ottlfuncs/func_sort.go
kaisecheng 9c22e38
Update pkg/ottl/ottlfuncs/README.md
kaisecheng 660f4fc
Update pkg/ottl/ottlfuncs/func_sort.go
kaisecheng 3325267
remove multierr dependency
kaisecheng 0a9b019
Merge branch 'main' into ottl_sort_func
kaisecheng b2f8062
Merge branch 'main' into ottl_sort_func
kaisecheng 6e0e66d
Merge branch 'main' into ottl_sort_func
kaisecheng f2145f3
add more e2e tests
kaisecheng File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 `Sort` function to sort array to ascending order or descending order | ||
|
||
# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists. | ||
issues: [34200] | ||
|
||
# (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] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,256 @@ | ||
// Copyright The OpenTelemetry Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
package ottlfuncs // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottlfuncs" | ||
|
||
import ( | ||
"cmp" | ||
"context" | ||
"fmt" | ||
"slices" | ||
"strconv" | ||
|
||
"go.opentelemetry.io/collector/pdata/pcommon" | ||
"go.uber.org/multierr" | ||
|
||
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl" | ||
) | ||
|
||
const ( | ||
sortAsc = "asc" | ||
sortDesc = "desc" | ||
) | ||
|
||
type SortArguments[K any] struct { | ||
Target ottl.Getter[K] | ||
Order ottl.Optional[string] | ||
} | ||
|
||
func NewSortFactory[K any]() ottl.Factory[K] { | ||
return ottl.NewFactory("Sort", &SortArguments[K]{}, createSortFunction[K]) | ||
} | ||
|
||
func createSortFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) { | ||
args, ok := oArgs.(*SortArguments[K]) | ||
|
||
if !ok { | ||
return nil, fmt.Errorf("SortFactory args must be of type *SortArguments[K]") | ||
} | ||
|
||
order := sortAsc | ||
if !args.Order.IsEmpty() { | ||
o := args.Order.Get() | ||
switch o { | ||
case sortAsc, sortDesc: | ||
order = o | ||
default: | ||
return nil, fmt.Errorf("invalid arguments: %s. Order should be either \"%s\" or \"%s\"", o, sortAsc, sortDesc) | ||
} | ||
} | ||
|
||
return sort(args.Target, order), nil | ||
} | ||
|
||
func sort[K any](target ottl.Getter[K], order string) ottl.ExprFunc[K] { | ||
return func(ctx context.Context, tCtx K) (any, error) { | ||
val, err := target.Get(ctx, tCtx) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
switch v := val.(type) { | ||
case pcommon.Slice: | ||
evan-bradley marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return sortSlice(v, order) | ||
case pcommon.Value: | ||
if v.Type() == pcommon.ValueTypeSlice { | ||
return sortSlice(v.Slice(), order) | ||
} | ||
return nil, fmt.Errorf("sort with unsupported type: '%s'. Target is not a list", v.Type().String()) | ||
case []any: | ||
// handle Sort([1,2,3]) | ||
slice := pcommon.NewValueSlice().SetEmptySlice() | ||
if err := slice.FromRaw(v); err != nil { | ||
errs := multierr.Append(err, fmt.Errorf("sort with unsupported type: '%T'. Target is not a list of primitive types", v)) | ||
return nil, errs | ||
kaisecheng marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
return sortSlice(slice, order) | ||
case []string: | ||
// handle value from Split() | ||
kaisecheng marked this conversation as resolved.
Show resolved
Hide resolved
|
||
dup := makeCopy(v) | ||
return sortTypedSlice(dup, order), nil | ||
case []int64: | ||
dup := makeCopy(v) | ||
return sortTypedSlice(dup, order), nil | ||
case []float64: | ||
dup := makeCopy(v) | ||
return sortTypedSlice(dup, order), nil | ||
case []bool: | ||
var strings []string | ||
for _, b := range v { | ||
strings = append(strings, strconv.FormatBool(b)) | ||
} | ||
|
||
sortTypedSlice(strings, order) | ||
|
||
bools := make([]bool, len(strings)) | ||
for i, s := range strings { | ||
boolValue, _ := strconv.ParseBool(s) | ||
bools[i] = boolValue | ||
} | ||
return bools, nil | ||
TylerHelmuth marked this conversation as resolved.
Show resolved
Hide resolved
|
||
default: | ||
return nil, fmt.Errorf("sort with unsupported type: '%T'. Target is not a list", v) | ||
} | ||
} | ||
} | ||
|
||
// sortSlice sorts a pcommon.Slice based on the specified order. | ||
// It gets the common type for all elements in the slice and converts all elements to this common type, creating a new copy | ||
// Parameters: | ||
// - slice: The pcommon.Slice to be sorted | ||
// - order: The sort order. "asc" for ascending, "desc" for descending | ||
// | ||
// Returns: | ||
// - A sorted slice as []any or the original pcommon.Slice | ||
// - An error if an unsupported type is encountered | ||
func sortSlice(slice pcommon.Slice, order string) (any, error) { | ||
length := slice.Len() | ||
if length == 0 { | ||
return slice, nil | ||
} | ||
|
||
commonType, ok := findCommonValueType(slice) | ||
if !ok { | ||
return slice, nil | ||
} | ||
|
||
switch commonType { | ||
case pcommon.ValueTypeInt: | ||
arr := makeConvertedCopy(slice, func(idx int) int64 { | ||
return slice.At(idx).Int() | ||
}) | ||
return sortConvertedSlice(arr, order), nil | ||
case pcommon.ValueTypeDouble: | ||
arr := makeConvertedCopy(slice, func(idx int) float64 { | ||
s := slice.At(idx) | ||
if s.Type() == pcommon.ValueTypeInt { | ||
return float64(s.Int()) | ||
} | ||
|
||
return s.Double() | ||
}) | ||
return sortConvertedSlice(arr, order), nil | ||
case pcommon.ValueTypeStr: | ||
arr := makeConvertedCopy(slice, func(idx int) string { | ||
return slice.At(idx).AsString() | ||
}) | ||
return sortConvertedSlice(arr, order), nil | ||
default: | ||
return nil, fmt.Errorf("sort with unsupported type: '%T'", commonType) | ||
} | ||
} | ||
|
||
type targetType interface { | ||
~int64 | ~float64 | ~string | ||
} | ||
|
||
// findCommonValueType determines the most appropriate common type for all elements in a pcommon.Slice. | ||
// It returns two values: | ||
// - A pcommon.ValueType representing the desired common type for all elements. | ||
// Mixed Numeric types return ValueTypeDouble. Integer type returns ValueTypeInt. Double type returns ValueTypeDouble. | ||
// String, Bool, Empty and mixed of the mentioned types return ValueTypeStr, as they require string conversion for comparison. | ||
// - A boolean indicating whether a common type could be determined (true) or not (false). | ||
// returns false for ValueTypeMap, ValueTypeSlice and ValueTypeBytes. They are unsupported types for sort. | ||
func findCommonValueType(slice pcommon.Slice) (pcommon.ValueType, bool) { | ||
length := slice.Len() | ||
if length == 0 { | ||
return pcommon.ValueTypeEmpty, false | ||
} | ||
|
||
wantType := slice.At(0).Type() | ||
wantStr := false | ||
wantDouble := false | ||
|
||
for i := 0; i < length; i++ { | ||
value := slice.At(i) | ||
currType := value.Type() | ||
|
||
switch currType { | ||
case pcommon.ValueTypeInt: | ||
if wantType == pcommon.ValueTypeDouble { | ||
wantDouble = true | ||
} | ||
case pcommon.ValueTypeDouble: | ||
if wantType == pcommon.ValueTypeInt { | ||
wantDouble = true | ||
} | ||
case pcommon.ValueTypeStr, pcommon.ValueTypeBool, pcommon.ValueTypeEmpty: | ||
wantStr = true | ||
default: | ||
return pcommon.ValueTypeEmpty, false | ||
} | ||
} | ||
|
||
if wantStr { | ||
wantType = pcommon.ValueTypeStr | ||
} else if wantDouble { | ||
wantType = pcommon.ValueTypeDouble | ||
} | ||
|
||
return wantType, true | ||
} | ||
|
||
func makeCopy[T targetType](src []T) []T { | ||
dup := make([]T, len(src)) | ||
copy(dup, src) | ||
return dup | ||
} | ||
|
||
func sortTypedSlice[T targetType](arr []T, order string) []T { | ||
if len(arr) == 0 { | ||
return arr | ||
} | ||
|
||
slices.SortFunc(arr, func(a, b T) int { | ||
if order == sortDesc { | ||
return cmp.Compare(b, a) | ||
} | ||
return cmp.Compare(a, b) | ||
}) | ||
|
||
return arr | ||
} | ||
|
||
type convertedValue[T targetType] struct { | ||
value T | ||
originalValue any | ||
} | ||
|
||
func makeConvertedCopy[T targetType](slice pcommon.Slice, converter func(idx int) T) []convertedValue[T] { | ||
length := slice.Len() | ||
var out []convertedValue[T] | ||
for i := 0; i < length; i++ { | ||
cv := convertedValue[T]{ | ||
value: converter(i), | ||
originalValue: slice.At(i).AsRaw(), | ||
} | ||
out = append(out, cv) | ||
} | ||
return out | ||
} | ||
|
||
func sortConvertedSlice[T targetType](cvs []convertedValue[T], order string) []any { | ||
slices.SortFunc(cvs, func(a, b convertedValue[T]) int { | ||
if order == sortDesc { | ||
return cmp.Compare(b.value, a.value) | ||
} | ||
return cmp.Compare(a.value, b.value) | ||
}) | ||
|
||
var out []any | ||
for _, cv := range cvs { | ||
out = append(out, cv.originalValue) | ||
} | ||
|
||
return out | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you add a test for a mixed-type slice?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a pretty complex function, I'd like to see more e2e tests that cover the different type scenarios it supports
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
added more e2e test covering unit types and mixed types