-
Notifications
You must be signed in to change notification settings - Fork 2.9k
[pkg/ottl] Add ParseKeyValue function #31035
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
Merged
evan-bradley
merged 9 commits into
open-telemetry:main
from
observIQ:ottl/key-value-parser
Feb 15, 2024
Merged
Changes from 4 commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
479838a
write ottl key value func
dpaasman00 e36dbd7
add e2e tests, documentation, and changelog entry
dpaasman00 885a566
internal feedback
dpaasman00 967289c
name changes & remove inQuotes
dpaasman00 2ecf32d
update parsing to reflect changes made to stanza keyvalue parser
dpaasman00 6b0a26d
add license
dpaasman00 0dbc0d9
put pair parsing into internal pkg, add some more unit tests, update …
dpaasman00 ca573d9
update how empty string is handled
dpaasman00 e1bbb38
move key-value split into parseutils
dpaasman00 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 hidden or 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 `ParseKeyValue` function for parsing key value pairs from a target string | ||
|
||
# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists. | ||
issues: [30998] | ||
|
||
# (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: [] |
This file contains hidden or 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 hidden or 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 hidden or 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,120 @@ | ||
package ottlfuncs | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"strings" | ||
|
||
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl" | ||
"go.opentelemetry.io/collector/pdata/pcommon" | ||
) | ||
|
||
type ParseKeyValueArguments[K any] struct { | ||
Target ottl.StringGetter[K] | ||
Delimiter ottl.Optional[string] | ||
PairDelimiter ottl.Optional[string] | ||
evan-bradley marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
func NewParseKeyValueFactory[K any]() ottl.Factory[K] { | ||
return ottl.NewFactory("ParseKeyValue", &ParseKeyValueArguments[K]{}, createParseKeyValueFunction[K]) | ||
} | ||
|
||
func createParseKeyValueFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) { | ||
args, ok := oArgs.(*ParseKeyValueArguments[K]) | ||
|
||
if !ok { | ||
return nil, fmt.Errorf("ParseKeyValueFactory args must be of type *ParseKeyValueArguments[K]") | ||
} | ||
|
||
return parseKeyValue[K](args.Target, args.Delimiter, args.PairDelimiter) | ||
} | ||
|
||
func parseKeyValue[K any](target ottl.StringGetter[K], d ottl.Optional[string], p ottl.Optional[string]) (ottl.ExprFunc[K], error) { | ||
delimiter := "=" | ||
if !d.IsEmpty() { | ||
delimiter = d.Get() | ||
} | ||
|
||
pairDelimiter := " " | ||
if !p.IsEmpty() { | ||
pairDelimiter = p.Get() | ||
} | ||
|
||
if pairDelimiter == delimiter { | ||
return nil, fmt.Errorf("pair delimiter \"%s\" cannot be equal to delimiter \"%s\"", pairDelimiter, delimiter) | ||
evan-bradley marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
TylerHelmuth marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
return func(ctx context.Context, tCtx K) (any, error) { | ||
source, err := target.Get(ctx, tCtx) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
if source == "" { | ||
return nil, fmt.Errorf("cannot parse from empty target") | ||
evan-bradley marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
pairs, err := splitPairs(source, pairDelimiter) | ||
if err != nil { | ||
return nil, fmt.Errorf("splitting pairs failed: %w", err) | ||
} | ||
|
||
parsed := make(map[string]any) | ||
for _, p := range pairs { | ||
pair := strings.SplitN(p, delimiter, 2) | ||
if len(pair) != 2 { | ||
return nil, fmt.Errorf("cannot split '%s' into 2 items, got %d", p, len(pair)) | ||
evan-bradley marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
key := strings.TrimSpace(strings.Trim(pair[0], "\"'")) | ||
value := strings.TrimSpace(strings.Trim(pair[1], "\"'")) | ||
parsed[key] = value | ||
} | ||
|
||
result := pcommon.NewMap() | ||
err = result.FromRaw(parsed) | ||
return result, err | ||
}, nil | ||
} | ||
|
||
// splitPairs will split the input on the pairDelimiter and return the resulting slice. | ||
// `strings.Split` is not used because it does not respect quotes and will split if the delimiter appears in a quoted value | ||
func splitPairs(input, pairDelimiter string) ([]string, error) { | ||
evan-bradley marked this conversation as resolved.
Show resolved
Hide resolved
|
||
var result []string | ||
currentPair := "" | ||
delimiterLength := len(pairDelimiter) | ||
quoteChar := "" // "" means we are not in quotes | ||
|
||
i := 0 | ||
for i < len(input) { | ||
if quoteChar == "" && i+delimiterLength <= len(input) && input[i:i+delimiterLength] == pairDelimiter { | ||
if currentPair == "" { | ||
i++ | ||
continue | ||
} | ||
result = append(result, currentPair) | ||
currentPair = "" | ||
i += delimiterLength | ||
continue | ||
} else if input[i] == '"' || input[i] == '\'' { | ||
if quoteChar != "" { | ||
if quoteChar == string(input[i]) { | ||
quoteChar = "" | ||
} | ||
} else { | ||
quoteChar = string(input[i]) | ||
} | ||
} | ||
currentPair += string(input[i]) | ||
i++ | ||
} | ||
|
||
if quoteChar != "" { | ||
return nil, fmt.Errorf("never reached end of a quoted value") | ||
} | ||
|
||
if currentPair != "" { | ||
result = append(result, currentPair) | ||
} | ||
|
||
return result, nil | ||
} |
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.
Uh oh!
There was an error while loading. Please reload this page.