Skip to content

Commit

Permalink
[pkg/ottl] Add Double converter (#27457)
Browse files Browse the repository at this point in the history
**Description:** Adding a Double converter to pkg/ottl

**Link to tracking Issue:** closes #22056
  • Loading branch information
gord02 authored Oct 19, 2023
1 parent b0f0dda commit c482aa7
Show file tree
Hide file tree
Showing 5 changed files with 187 additions and 0 deletions.
27 changes: 27 additions & 0 deletions .chloggen/double-converter.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: doubleconverter

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: "Adding a double converter into pkg/ottl"

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

# (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]
24 changes: 24 additions & 0 deletions pkg/ottl/ottlfuncs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,7 @@ Available Converters:
- [ExtractPatterns](#extractpatterns)
- [FNV](#fnv)
- [Hours](#hours)
- [Double](#double)
- [Duration](#duration)
- [Int](#int)
- [IsMap](#ismap)
Expand Down Expand Up @@ -365,6 +366,29 @@ Examples:

- `ConvertCase(metric.name, "snake")`

### Double

The `Double` Converter converts an inputted `value` into a double.

The returned type is float64.

The input `value` types:
* float64. returns the `value` without changes.
* string. Tries to parse a double from string. If it fails then nil will be returned.
* bool. If `value` is true, then the function will return 1 otherwise 0.
* int64. The function converts the integer to a double.

If `value` is another type or parsing failed nil is always returned.

The `value` is either a path expression to a telemetry field to retrieve or a literal.

Examples:

- `Double(attributes["http.status_code"])`


- `Double("2.0")`

### Duration

`Duration(duration)`
Expand Down
42 changes: 42 additions & 0 deletions pkg/ottl/ottlfuncs/func_double.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// 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"

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

type DoubleArguments[K any] struct {
Target ottl.FloatLikeGetter[K]
}

func NewDoubleFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("Double", &DoubleArguments[K]{}, createDoubleFunction[K])
}

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

if !ok {
return nil, fmt.Errorf("DoubleFactory args must be of type *DoubleArguments[K]")
}

return doubleFunc(args.Target), nil
}

func doubleFunc[K any](target ottl.FloatLikeGetter[K]) ottl.ExprFunc[K] {
return func(ctx context.Context, tCtx K) (interface{}, error) {
value, err := target.Get(ctx, tCtx)
if err != nil {
return nil, err
}
if value == nil {
return nil, nil
}
return *value, nil
}
}
93 changes: 93 additions & 0 deletions pkg/ottl/ottlfuncs/func_double_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ottlfuncs

import (
"context"
"testing"

"github.com/stretchr/testify/assert"

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

func Test_Double(t *testing.T) {
tests := []struct {
name string
value interface{}
expected interface{}
err bool
}{
{
name: "string",
value: "50",
expected: float64(50),
},
{
name: "empty string",
value: "",
expected: nil,
err: true,
},
{
name: "not a number string",
value: "test",
expected: nil,
err: true,
},
{
name: "int64",
value: int64(333),
expected: float64(333),
},
{
name: "float64",
value: float64(2.7),
expected: float64(2.7),
},
{
name: "float64 without decimal",
value: float64(55),
expected: float64(55),
},
{
name: "true",
value: true,
expected: float64(1),
},
{
name: "false",
value: false,
expected: float64(0),
},
{
name: "nil",
value: nil,
expected: nil,
},
{
name: "some struct",
value: struct{}{},
expected: nil,
err: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
exprFunc := doubleFunc[interface{}](&ottl.StandardFloatLikeGetter[interface{}]{

Getter: func(context.Context, interface{}) (interface{}, error) {
return test.value, nil
},
})
result, err := exprFunc(nil, nil)
if test.err {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
assert.Equal(t, test.expected, result)
})
}
}
1 change: 1 addition & 0 deletions pkg/ottl/ottlfuncs/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ func converters[K any]() []ottl.Factory[K] {
// Converters
NewConcatFactory[K](),
NewConvertCaseFactory[K](),
NewDoubleFactory[K](),
NewDurationFactory[K](),
NewExtractPatternsFactory[K](),
NewFnvFactory[K](),
Expand Down

0 comments on commit c482aa7

Please sign in to comment.