diff --git a/.chloggen/issue-27897-IsBool-Converter.yaml b/.chloggen/issue-27897-IsBool-Converter.yaml new file mode 100755 index 000000000000..e0ac3f0687d7 --- /dev/null +++ b/.chloggen/issue-27897-IsBool-Converter.yaml @@ -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 IsBool function into OTTL + +# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists. +issues: [27897] + +# (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] diff --git a/pkg/ottl/README.md b/pkg/ottl/README.md index 82d97db70495..49aca8a48a08 100644 --- a/pkg/ottl/README.md +++ b/pkg/ottl/README.md @@ -77,6 +77,8 @@ The following types are supported for single-value parameters in OTTL functions: - `StringLikeGetter` - `IntGetter` - `IntLikeGetter` +- `BoolGetter` +- `BoolLikeGetter` - `Enum` - `string` - `float64` diff --git a/pkg/ottl/expression.go b/pkg/ottl/expression.go index 26da44c6c073..1c5ac3f69b17 100644 --- a/pkg/ottl/expression.go +++ b/pkg/ottl/expression.go @@ -247,6 +247,41 @@ func (g StandardFloatGetter[K]) Get(ctx context.Context, tCtx K) (float64, error } } +// BoolGetter is a Getter that must return a bool. +type BoolGetter[K any] interface { + // Get retrieves a bool value. + Get(ctx context.Context, tCtx K) (bool, error) +} + +// StandardBoolGetter is a basic implementation of BoolGetter +type StandardBoolGetter[K any] struct { + Getter func(ctx context.Context, tCtx K) (any, error) +} + +// Get retrieves a bool value. +// If the value is not a bool a new TypeError is returned. +// If there is an error getting the value it will be returned. +func (g StandardBoolGetter[K]) Get(ctx context.Context, tCtx K) (bool, error) { + val, err := g.Getter(ctx, tCtx) + if err != nil { + return false, fmt.Errorf("error getting value in %T: %w", g, err) + } + if val == nil { + return false, TypeError("expected bool but got nil") + } + switch v := val.(type) { + case bool: + return v, nil + case pcommon.Value: + if v.Type() == pcommon.ValueTypeBool { + return v.Bool(), nil + } + return false, TypeError(fmt.Sprintf("expected bool but got %v", v.Type())) + default: + return false, TypeError(fmt.Sprintf("expected bool but got %T", val)) + } +} + // FunctionGetter uses a function factory to return an instantiated function as an Expr. type FunctionGetter[K any] interface { Get(args Arguments) (Expr[K], error) @@ -507,6 +542,64 @@ func (g StandardIntLikeGetter[K]) Get(ctx context.Context, tCtx K) (*int64, erro return &result, nil } +// BoolLikeGetter is a Getter that returns a bool by converting the underlying value to a bool if necessary. +type BoolLikeGetter[K any] interface { + // Get retrieves a bool value. + // Unlike `BoolGetter`, the expectation is that the underlying value is converted to a bool if possible. + // If the value cannot be converted to a bool, nil and an error are returned. + // If the value is nil, nil is returned without an error. + Get(ctx context.Context, tCtx K) (*bool, error) +} + +type StandardBoolLikeGetter[K any] struct { + Getter func(ctx context.Context, tCtx K) (any, error) +} + +func (g StandardBoolLikeGetter[K]) Get(ctx context.Context, tCtx K) (*bool, error) { + val, err := g.Getter(ctx, tCtx) + if err != nil { + return nil, fmt.Errorf("error getting value in %T: %w", g, err) + } + if val == nil { + return nil, nil + } + var result bool + switch v := val.(type) { + case bool: + result = v + case int: + result = v != 0 + case int64: + result = v != 0 + case string: + result, err = strconv.ParseBool(v) + if err != nil { + return nil, err + } + case float64: + result = v != 0.0 + case pcommon.Value: + switch v.Type() { + case pcommon.ValueTypeBool: + result = v.Bool() + case pcommon.ValueTypeInt: + result = v.Int() != 0 + case pcommon.ValueTypeStr: + result, err = strconv.ParseBool(v.Str()) + if err != nil { + return nil, err + } + case pcommon.ValueTypeDouble: + result = v.Double() != 0.0 + default: + return nil, TypeError(fmt.Sprintf("unsupported value type: %v", v.Type())) + } + default: + return nil, TypeError(fmt.Sprintf("unsupported type: %T", val)) + } + return &result, nil +} + func (p *Parser[K]) newGetter(val value) (Getter[K], error) { if val.IsNil != nil && *val.IsNil { return &literal[K]{value: nil}, nil diff --git a/pkg/ottl/expression_test.go b/pkg/ottl/expression_test.go index d99c44f92fb9..478d56defead 100644 --- a/pkg/ottl/expression_test.go +++ b/pkg/ottl/expression_test.go @@ -1449,6 +1449,239 @@ func Test_StandardIntLikeGetter_WrappedError(t *testing.T) { assert.False(t, ok) } +func Test_StandardBoolGetter(t *testing.T) { + tests := []struct { + name string + getter StandardBoolGetter[any] + want bool + valid bool + expectedErrorMsg string + }{ + { + name: "primitive bool type", + getter: StandardBoolGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return true, nil + }, + }, + want: true, + valid: true, + }, + { + name: "ValueTypeBool type", + getter: StandardBoolGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return pcommon.NewValueBool(true), nil + }, + }, + want: true, + valid: true, + }, + { + name: "Incorrect type", + getter: StandardBoolGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return 1, nil + }, + }, + valid: false, + expectedErrorMsg: "expected bool but got int", + }, + { + name: "nil", + getter: StandardBoolGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return nil, nil + }, + }, + valid: false, + expectedErrorMsg: "expected bool but got nil", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + val, err := tt.getter.Get(context.Background(), nil) + if tt.valid { + assert.NoError(t, err) + assert.Equal(t, tt.want, val) + } else { + assert.IsType(t, TypeError(""), err) + assert.EqualError(t, err, tt.expectedErrorMsg) + } + }) + } +} + +// nolint:errorlint +func Test_StandardBoolGetter_WrappedError(t *testing.T) { + getter := StandardBoolGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return nil, TypeError("") + }, + } + _, err := getter.Get(context.Background(), nil) + assert.Error(t, err) + _, ok := err.(TypeError) + assert.False(t, ok) +} + +func Test_StandardBoolLikeGetter(t *testing.T) { + tests := []struct { + name string + getter BoolLikeGetter[any] + want any + valid bool + expectedErrorMsg string + }{ + { + name: "string type true", + getter: StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return "true", nil + }, + }, + want: true, + valid: true, + }, + { + name: "string type false", + getter: StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return "false", nil + }, + }, + want: false, + valid: true, + }, + { + name: "int type", + getter: StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return 0, nil + }, + }, + want: false, + valid: true, + }, + { + name: "float64 type", + getter: StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return float64(0.0), nil + }, + }, + want: false, + valid: true, + }, + { + name: "pcommon.value type int", + getter: StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + v := pcommon.NewValueInt(int64(0)) + return v, nil + }, + }, + want: false, + valid: true, + }, + { + name: "pcommon.value type string", + getter: StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + v := pcommon.NewValueStr("false") + return v, nil + }, + }, + want: false, + valid: true, + }, + { + name: "pcommon.value type bool", + getter: StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + v := pcommon.NewValueBool(true) + return v, nil + }, + }, + want: true, + valid: true, + }, + { + name: "pcommon.value type double", + getter: StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + v := pcommon.NewValueDouble(float64(0.0)) + return v, nil + }, + }, + want: false, + valid: true, + }, + { + name: "nil", + getter: StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return nil, nil + }, + }, + want: nil, + valid: true, + }, + { + name: "invalid type", + getter: StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return []byte{}, nil + }, + }, + valid: false, + expectedErrorMsg: "unsupported type: []uint8", + }, + { + name: "invalid pcommon.value type", + getter: StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + v := pcommon.NewValueMap() + return v, nil + }, + }, + valid: false, + expectedErrorMsg: "unsupported value type: Map", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + val, err := tt.getter.Get(context.Background(), nil) + if tt.valid { + assert.NoError(t, err) + if tt.want == nil { + assert.Nil(t, val) + } else { + assert.Equal(t, tt.want, *val) + } + } else { + assert.IsType(t, TypeError(""), err) + assert.EqualError(t, err, tt.expectedErrorMsg) + } + }) + } +} + +// nolint:errorlint +func Test_StandardBoolLikeGetter_WrappedError(t *testing.T) { + getter := StandardBoolLikeGetter[any]{ + Getter: func(ctx context.Context, tCtx any) (any, error) { + return nil, TypeError("") + }, + } + _, err := getter.Get(context.Background(), nil) + assert.Error(t, err) + _, ok := err.(TypeError) + assert.False(t, ok) +} + func Test_StandardPMapGetter(t *testing.T) { tests := []struct { name string diff --git a/pkg/ottl/ottlfuncs/README.md b/pkg/ottl/ottlfuncs/README.md index ac5d7dff851f..c975b6aad5b6 100644 --- a/pkg/ottl/ottlfuncs/README.md +++ b/pkg/ottl/ottlfuncs/README.md @@ -297,6 +297,7 @@ Available Converters: - [Double](#double) - [Duration](#duration) - [Int](#int) +- [IsBool](#isbool) - [IsMap](#ismap) - [IsMatch](#ismatch) - [IsString](#isstring) @@ -480,6 +481,32 @@ Examples: - `Int("2.0")` +### IsBool + +`IsBool(value)` + +The `IsBool` Converter evaluates whether the given `value` is a boolean or not. + +Specifically, it will return `true` if the provided `value` is one of the following: + +1. A Go's native `bool` type. +2. A `pcommon.ValueTypeBool`. + +Otherwise, it will return `false`. + +Examples: + +- `IsBool(false)` + + +- `IsBool(pcommon.NewValueBool(false))` + + +- `IsBool(42)` + + +- `IsBool(attributes["any key"])` + ### IsMap `IsMap(value)` diff --git a/pkg/ottl/ottlfuncs/func_is_bool.go b/pkg/ottl/ottlfuncs/func_is_bool.go new file mode 100644 index 000000000000..b2845e919c33 --- /dev/null +++ b/pkg/ottl/ottlfuncs/func_is_bool.go @@ -0,0 +1,45 @@ +// 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 IsBoolArguments[K any] struct { + Target ottl.BoolGetter[K] +} + +func NewIsBoolFactory[K any]() ottl.Factory[K] { + return ottl.NewFactory("IsBool", &IsBoolArguments[K]{}, createIsBoolFunction[K]) +} + +func createIsBoolFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) { + args, ok := oArgs.(*IsBoolArguments[K]) + + if !ok { + return nil, fmt.Errorf("IsBoolFactory args must be of type *IsBoolArguments[K]") + } + + return isBool(args.Target), nil +} + +// nolint:errorlint +func isBool[K any](target ottl.BoolGetter[K]) ottl.ExprFunc[K] { + return func(ctx context.Context, tCtx K) (any, error) { + _, err := target.Get(ctx, tCtx) + // Use type assertion, because we don't want to check wrapped errors + switch err.(type) { + case ottl.TypeError: + return false, nil + case nil: + return true, nil + default: + return false, err + } + } +} diff --git a/pkg/ottl/ottlfuncs/func_is_bool_test.go b/pkg/ottl/ottlfuncs/func_is_bool_test.go new file mode 100644 index 000000000000..4cb780385923 --- /dev/null +++ b/pkg/ottl/ottlfuncs/func_is_bool_test.go @@ -0,0 +1,74 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package ottlfuncs + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "go.opentelemetry.io/collector/pdata/pcommon" + + "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl" +) + +func Test_IsBool(t *testing.T) { + tests := []struct { + name string + value any + expected bool + }{ + { + name: "bool", + value: true, + expected: true, + }, + { + name: "ValueTypeBool", + value: pcommon.NewValueBool(false), + expected: true, + }, + { + name: "not bool", + value: 1, + expected: false, + }, + { + name: "ValueTypeSlice", + value: pcommon.NewValueSlice(), + expected: false, + }, + { + name: "nil", + value: nil, + expected: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + exprFunc := isBool[any](&ottl.StandardBoolGetter[any]{ + Getter: func(context.Context, any) (any, error) { + return tt.value, nil + }, + }) + result, err := exprFunc(context.Background(), nil) + assert.NoError(t, err) + assert.Equal(t, tt.expected, result) + }) + } +} + +// nolint:errorlint +func Test_IsBool_Error(t *testing.T) { + exprFunc := isBool[any](&ottl.StandardBoolGetter[any]{ + Getter: func(context.Context, any) (any, error) { + return nil, ottl.TypeError("") + }, + }) + result, err := exprFunc(context.Background(), nil) + assert.Equal(t, false, result) + assert.Error(t, err) + _, ok := err.(ottl.TypeError) + assert.False(t, ok) +} diff --git a/pkg/ottl/ottlfuncs/functions.go b/pkg/ottl/ottlfuncs/functions.go index e43507192392..e892135c45e8 100644 --- a/pkg/ottl/ottlfuncs/functions.go +++ b/pkg/ottl/ottlfuncs/functions.go @@ -42,6 +42,7 @@ func converters[K any]() []ottl.Factory[K] { NewFnvFactory[K](), NewHoursFactory[K](), NewIntFactory[K](), + NewIsBoolFactory[K](), NewIsMapFactory[K](), NewIsMatchFactory[K](), NewIsStringFactory[K](),