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] Add Decode function #33942

Merged
merged 40 commits into from
Sep 5, 2024
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
40 commits
Select commit Hold shift + click to select a range
4e9baac
add decode function
bacherfl Jul 5, 2024
e6a21c1
additional tests and documentation
bacherfl Jul 5, 2024
7c3ac25
fix typo in docs
bacherfl Jul 8, 2024
8a682c2
add link to iana index
bacherfl Jul 8, 2024
a4d6e74
remove obsolete todo comment
bacherfl Jul 8, 2024
51ccfa5
add changelog entry
bacherfl Jul 8, 2024
9dea2c9
appease linter
bacherfl Jul 8, 2024
c8a744e
add license comments
bacherfl Jul 8, 2024
04d67bb
appease linter
bacherfl Jul 8, 2024
f8d3041
go mod tidy
bacherfl Jul 8, 2024
b6aac52
Merge branch 'main' into feat/32493/decode-function
bacherfl Jul 9, 2024
bfff733
go mod tidy
bacherfl Jul 9, 2024
f6682e2
Merge branch 'main' into feat/32493/decode-function
bacherfl Jul 9, 2024
a7f04aa
trigger CI checks
bacherfl Jul 10, 2024
7e18876
incorporate review comments
bacherfl Jul 11, 2024
275933f
incorporate review comments
bacherfl Jul 23, 2024
0f1d591
Merge branch 'main' into feat/32493/decode-function
bacherfl Jul 23, 2024
921b6fe
go mod tidy after merging main
bacherfl Jul 23, 2024
413190e
fix dependencies
bacherfl Jul 23, 2024
d31f342
fix dependencies
bacherfl Jul 23, 2024
90939bd
fix dependencies
bacherfl Jul 23, 2024
bc294fe
fix dependencies
bacherfl Jul 23, 2024
74be1cf
go mod tidy
bacherfl Jul 23, 2024
874e87c
remove dependency to stanza from ottl
bacherfl Jul 30, 2024
d9abbe8
appease linter
bacherfl Jul 30, 2024
1941c07
trigger CI checks
bacherfl Jul 30, 2024
3f2a84b
Merge branch 'main' into feat/32493/decode-function
bacherfl Aug 9, 2024
5647ab2
update dependencies after merging main
bacherfl Aug 9, 2024
5f8b384
Merge branch 'main' into feat/32493/decode-function
bacherfl Aug 26, 2024
822cecc
Merge branch 'main' into feat/32493/decode-function
bacherfl Aug 29, 2024
e12de34
Merge branch 'main' into feat/32493/decode-function
bacherfl Aug 30, 2024
9232575
use encodingOverrides from stanza
bacherfl Sep 2, 2024
e871462
Merge branch 'main' into feat/32493/decode-function
bacherfl Sep 2, 2024
c30068a
fix linting
bacherfl Sep 2, 2024
2f4b94d
fix deps
bacherfl Sep 2, 2024
6a82df1
Merge branch 'main' into feat/32493/decode-function
bacherfl Sep 2, 2024
522fc2d
Merge branch 'main' into feat/32493/decode-function
djaglowski Sep 3, 2024
52056fd
fix linting
bacherfl Sep 4, 2024
208a14d
Merge branch 'main' into feat/32493/decode-function
bacherfl Sep 4, 2024
46029c8
Merge branch 'main' into feat/32493/decode-function
bacherfl Sep 5, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .chloggen/add-decode-function.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 Decode() converter function

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

# (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: []
6 changes: 6 additions & 0 deletions pkg/ottl/e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,12 @@ func Test_e2e_converters(t *testing.T) {
tCtx.GetLogRecord().Attributes().PutStr("test", "pass")
},
},
{
statement: `set(attributes["test"], Decode("cGFzcw==", "base64"))`,
want: func(tCtx ottllog.TransformContext) {
tCtx.GetLogRecord().Attributes().PutStr("test", "pass")
},
},
{
statement: `set(attributes["test"], Concat(["A","B"], ":"))`,
want: func(tCtx ottllog.TransformContext) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/ottl/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ require (
go.uber.org/zap v1.27.0
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842
golang.org/x/net v0.27.0
golang.org/x/text v0.16.0
)

require (
Expand All @@ -45,7 +46,6 @@ require (
go.opentelemetry.io/otel/sdk/metric v1.28.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/sys v0.22.0 // indirect
golang.org/x/text v0.16.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240701130421-f6361c86f094 // indirect
google.golang.org/grpc v1.65.0 // indirect
google.golang.org/protobuf v1.34.2 // indirect
Expand Down
16 changes: 16 additions & 0 deletions pkg/ottl/ottlfuncs/README.md
Copy link
Member

Choose a reason for hiding this comment

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

We should mark base64decode as deprecated and link to decode in this doc.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

good point - i added a deprecation notice to the base64decode function

Original file line number Diff line number Diff line change
Expand Up @@ -474,6 +474,22 @@ Examples:

- `Base64Decode(attributes["encoded field"])`

### Decode

`Decode(value, encoding)`

The `Decode` Converter takes a string or byte array encoded with the specified encoding and returns the decoded string.

`value` is a valid encoded string or byte array.
`encoding` is a valid encoding name included in the [IANA encoding index](https://www.iana.org/assignments/character-sets/character-sets.xhtml).

Examples:

- `Decode("aGVsbG8gd29ybGQ=", "base64")`


- `Decode(attributes["encoded field"], "us-ascii")`

### Concat

`Concat(values[], delimiter)`
Expand Down
78 changes: 78 additions & 0 deletions pkg/ottl/ottlfuncs/func_decode.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// 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"
"encoding/base64"
"fmt"

"golang.org/x/text/encoding/ianaindex"

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

type DecodeArguments[K any] struct {
Target ottl.Getter[K]
Encoding string
}

func NewDecodeFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("Decode", &DecodeArguments[K]{}, createDecodeFunction[K])
}

func createDecodeFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) {
args, ok := oArgs.(*DecodeArguments[K])
if !ok {
return nil, fmt.Errorf("DecodeFactory args must be of type *DecodeArguments[K]")
}

return Decode(args.Target, args.Encoding)
}

func Decode[K any](target ottl.Getter[K], encoding string) (ottl.ExprFunc[K], error) {
return func(ctx context.Context, tCtx K) (any, error) {
val, err := target.Get(ctx, tCtx)
if err != nil {
return nil, err
}
var stringValue string

switch v := val.(type) {
case []byte:
stringValue = string(v)
case *string:
stringValue = *v
case string:
stringValue = v
default:
return nil, fmt.Errorf("unsupported type provided to Decode function: %T", v)
}

switch encoding {
case "base64":
// base64 is not in IANA index, so we have to deal with this encoding separately
decodedBytes, err := base64.StdEncoding.DecodeString(stringValue)
if err != nil {
return nil, fmt.Errorf("could not decode: %w", err)
}
return string(decodedBytes), nil
default:
e, err := ianaindex.IANA.Encoding(encoding)
if err != nil {
return nil, fmt.Errorf("could not get encoding for %s: %w", encoding, err)
}
if e == nil {
// for some encodings a nil error and a nil encoding is returned, so we need to double check
// if the encoding is actually set here
return nil, fmt.Errorf("no decoder available for encoding: %s", encoding)
}
decodedString, err := e.NewDecoder().String(stringValue)
if err != nil {
return nil, fmt.Errorf("could not decode: %w", err)
}
return decodedString, nil
}
}, nil
}
121 changes: 121 additions & 0 deletions pkg/ottl/ottlfuncs/func_decode_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ottlfuncs

import (
"context"
"testing"

"github.com/stretchr/testify/require"

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

func TestDecode(t *testing.T) {
type testCase struct {
name string
value any
encoding string
want any
expectedError string
}
tests := []testCase{
{
name: "convert base64 byte array",
value: []byte("dGVzdAo="),
encoding: "base64",
want: "test\n",
},
{
name: "convert base64 string",
value: "aGVsbG8gd29ybGQ=",
encoding: "base64",
want: "hello world",
},
{
name: "decode us-ascii encoded string",
value: "test string",
encoding: "us-ascii",
want: "test string",
},
{
name: "decode ISO-8859-1 encoded string",
value: "test string",
encoding: "ISO-8859-1",
want: "test string",
},
{
name: "decode WINDOWS-1251 encoded string",
value: "test string",
encoding: "WINDOWS-1251",
want: "test string",
},
{
name: "decode WINDOWS-1252 encoded string",
value: "test string",
encoding: "WINDOWS-1252",
want: "test string",
},
{
name: "decode UTF-8 encoded string",
value: "test string",
encoding: "UTF-8",
want: "test string",
},
{
name: "decode GB2312 encoded string; no decoder available",
value: "test string",
encoding: "GB2312",
want: nil,
expectedError: "no decoder available for encoding: GB2312",
},
{
name: "non-string",
value: 10,
encoding: "base64",
expectedError: "unsupported type provided to Decode function: int",
},
{
name: "nil",
value: nil,
encoding: "base64",
expectedError: "unsupported type provided to Decode function: <nil>",
},
{
name: "not-base64-string",
value: "!@#$%^&*()_+",
encoding: "base64",
expectedError: "illegal base64 data at input byte",
},
{
name: "missing-base64-padding",
value: "cmVtb3ZlZCBwYWRkaW5nCg",
encoding: "base64",
expectedError: "illegal base64 data at input byte",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
expressionFunc, err := createDecodeFunction[any](ottl.FunctionContext{}, &DecodeArguments[any]{
Target: &ottl.StandardGetSetter[any]{
Getter: func(context.Context, any) (any, error) {
return tt.value, nil
},
},
Encoding: tt.encoding,
})

require.Nil(t, err)

result, err := expressionFunc(nil, nil)
if tt.expectedError != "" {
require.ErrorContains(t, err, tt.expectedError)
return
}

require.NoError(t, err)
require.Equal(t, tt.want, result)
})
}
}
1 change: 1 addition & 0 deletions pkg/ottl/ottlfuncs/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func converters[K any]() []ottl.Factory[K] {
return []ottl.Factory[K]{
// Converters
NewBase64DecodeFactory[K](),
NewDecodeFactory[K](),
NewConcatFactory[K](),
NewConvertCaseFactory[K](),
NewDayFactory[K](),
Expand Down
Loading