-
Notifications
You must be signed in to change notification settings - Fork 2.9k
[pkg/ottl] Add ConvertTextToElementsXML Converter #35364
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
djaglowski
merged 6 commits into
open-telemetry:main
from
djaglowski:wrap-hanging-values-xml
Oct 10, 2024
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
06ef4e5
[pkg/ottl] Add ElementizeAttributesXML Converter
djaglowski d6f7da9
Rename function to ConvertAttributesToElementsXML
djaglowski 5b5be7a
[pkg/ottl] Add ElementizeValuesXML Converter
djaglowski 1522cbf
Rename function to ConvertTextToElementsXML
djaglowski 4184a36
Fix docs
djaglowski dc3174b
Add e2e test using all parameters
djaglowski 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 ConvertTextToElements Converter | ||
|
||
# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists. | ||
issues: [35364] | ||
|
||
# (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
107 changes: 107 additions & 0 deletions
107
pkg/ottl/ottlfuncs/func_convert_text_to_elements_xml.go
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,107 @@ | ||
// 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/antchfx/xmlquery" | ||
|
||
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl" | ||
) | ||
|
||
type ConvertTextToElementsXMLArguments[K any] struct { | ||
Target ottl.StringGetter[K] | ||
XPath ottl.Optional[string] | ||
ElementName ottl.Optional[string] | ||
} | ||
|
||
func NewConvertTextToElementsXMLFactory[K any]() ottl.Factory[K] { | ||
return ottl.NewFactory("ConvertTextToElementsXML", &ConvertTextToElementsXMLArguments[K]{}, createConvertTextToElementsXMLFunction[K]) | ||
} | ||
|
||
func createConvertTextToElementsXMLFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) { | ||
args, ok := oArgs.(*ConvertTextToElementsXMLArguments[K]) | ||
|
||
if !ok { | ||
return nil, fmt.Errorf("ConvertTextToElementsXML args must be of type *ConvertTextToElementsXMLAguments[K]") | ||
} | ||
|
||
xPath := args.XPath.Get() | ||
if xPath == "" { | ||
xPath = "/" | ||
} else if err := validateXPath(xPath); err != nil { | ||
return nil, err | ||
} | ||
|
||
elementName := args.ElementName.Get() | ||
if elementName == "" { | ||
elementName = "value" | ||
} | ||
|
||
return convertTextToElementsXML(args.Target, xPath, elementName), nil | ||
} | ||
|
||
// convertTextToElementsXML returns a string that is a result of wrapping any extraneous text nodes with a dedicated element. | ||
func convertTextToElementsXML[K any](target ottl.StringGetter[K], xPath string, elementName string) ottl.ExprFunc[K] { | ||
return func(ctx context.Context, tCtx K) (any, error) { | ||
var doc *xmlquery.Node | ||
if targetVal, err := target.Get(ctx, tCtx); err != nil { | ||
return nil, err | ||
} else if doc, err = parseNodesXML(targetVal); err != nil { | ||
return nil, err | ||
} | ||
for _, n := range xmlquery.Find(doc, xPath) { | ||
convertTextToElementsForNode(n, elementName) | ||
} | ||
return doc.OutputXML(false), nil | ||
} | ||
} | ||
|
||
func convertTextToElementsForNode(parent *xmlquery.Node, elementName string) { | ||
switch parent.Type { | ||
case xmlquery.ElementNode: // ok | ||
case xmlquery.DocumentNode: // ok | ||
default: | ||
return | ||
} | ||
|
||
if parent.FirstChild == nil { | ||
return | ||
} | ||
|
||
// Convert any child nodes and count text and element nodes. | ||
var valueCount, elementCount int | ||
for child := parent.FirstChild; child != nil; child = child.NextSibling { | ||
if child.Type == xmlquery.ElementNode { | ||
convertTextToElementsForNode(child, elementName) | ||
elementCount++ | ||
} else if child.Type == xmlquery.TextNode { | ||
valueCount++ | ||
} | ||
} | ||
|
||
// If there are no values to wrap, or if there is exactly one value OR one element, this node is all set. | ||
if valueCount == 0 || elementCount+valueCount <= 1 { | ||
return | ||
} | ||
|
||
// At this point, we either have multiple values, or a mix of values and elements. | ||
// Either way, we need to wrap the values. | ||
for child := parent.FirstChild; child != nil; child = child.NextSibling { | ||
if child.Type != xmlquery.TextNode { | ||
continue | ||
} | ||
newTextNode := &xmlquery.Node{ | ||
Type: xmlquery.TextNode, | ||
Data: child.Data, | ||
} | ||
// Change this node into an element | ||
child.Type = xmlquery.ElementNode | ||
child.Data = elementName | ||
child.FirstChild = newTextNode | ||
child.LastChild = newTextNode | ||
} | ||
} |
127 changes: 127 additions & 0 deletions
127
pkg/ottl/ottlfuncs/func_convert_text_to_elements_xml_test.go
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,127 @@ | ||
// 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" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
|
||
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl" | ||
) | ||
|
||
func Test_ConvertTextToElementsXML(t *testing.T) { | ||
tests := []struct { | ||
name string | ||
document string | ||
xPath string | ||
elementName string | ||
want string | ||
}{ | ||
{ | ||
name: "nop", | ||
document: `<a><b/></a>`, | ||
want: `<a><b></b></a>`, | ||
}, | ||
{ | ||
name: "nop declaration", | ||
document: `<?xml version="1.0" encoding="UTF-8"?><a><b/></a>`, | ||
want: `<?xml version="1.0" encoding="UTF-8"?><a><b></b></a>`, | ||
}, | ||
{ | ||
name: "nop attributes", | ||
document: `<a foo="bar" hello="world"/>`, | ||
want: `<a foo="bar" hello="world"></a>`, | ||
}, | ||
{ | ||
name: "nop wrapped text", | ||
document: `<a>hello world</a>`, | ||
want: `<a>hello world</a>`, | ||
}, | ||
{ | ||
name: "simple hanging", | ||
document: `<a><b/>foo</a>`, | ||
want: `<a><b></b><value>foo</value></a>`, | ||
}, | ||
{ | ||
name: "simple hanging with tag name", | ||
elementName: "bar", | ||
document: `<a><b/>foo</a>`, | ||
want: `<a><b></b><bar>foo</bar></a>`, | ||
}, | ||
{ | ||
name: "multiple hanging same level", | ||
document: `<a>foo<b/>bar</a>`, | ||
want: `<a><value>foo</value><b></b><value>bar</value></a>`, | ||
}, | ||
{ | ||
name: "multiple hanging multiple levels", | ||
document: `<a>foo<b/>bar<c/>1<d>not</d>2<e><f/><f/></e></a>`, | ||
elementName: "v", | ||
want: `<a><v>foo</v><b></b><v>bar</v><c></c><v>1</v><d>not</d><v>2</v><e><f></f><f></f></e></a>`, | ||
}, | ||
{ | ||
name: "xpath select some", | ||
document: `<a><b><c/>foo</b><d><c/>bar</d><b><c/>baz</b></a>`, | ||
xPath: "/a/b", | ||
want: `<a><b><c></c><value>foo</value></b><d><c></c>bar</d><b><c></c><value>baz</value></b></a>`, | ||
}, | ||
{ | ||
name: "xpath with element name", | ||
document: `<a><b><c/>foo</b><d><c/>bar</d><b><c/>baz</b></a>`, | ||
xPath: "/a/b", | ||
elementName: "V", | ||
want: `<a><b><c></c><V>foo</V></b><d><c></c>bar</d><b><c></c><V>baz</V></b></a>`, | ||
}, | ||
} | ||
factory := NewConvertTextToElementsXMLFactory[any]() | ||
for _, tt := range tests { | ||
t.Run(tt.name, func(t *testing.T) { | ||
args := &ConvertTextToElementsXMLArguments[any]{ | ||
Target: ottl.StandardStringGetter[any]{ | ||
Getter: func(_ context.Context, _ any) (any, error) { | ||
return tt.document, nil | ||
}, | ||
}, | ||
XPath: ottl.NewTestingOptional(tt.xPath), | ||
ElementName: ottl.NewTestingOptional(tt.elementName), | ||
} | ||
exprFunc, err := factory.CreateFunction(ottl.FunctionContext{}, args) | ||
assert.NoError(t, err) | ||
|
||
result, err := exprFunc(context.Background(), nil) | ||
assert.NoError(t, err) | ||
assert.Equal(t, tt.want, result) | ||
}) | ||
} | ||
} | ||
|
||
func TestCreateConvertTextToElementsXMLFunc(t *testing.T) { | ||
factory := NewConvertTextToElementsXMLFactory[any]() | ||
fCtx := ottl.FunctionContext{} | ||
|
||
// Invalid arg type | ||
exprFunc, err := factory.CreateFunction(fCtx, nil) | ||
assert.Error(t, err) | ||
assert.Nil(t, exprFunc) | ||
|
||
// Invalid XPath should error on function creation | ||
exprFunc, err = factory.CreateFunction( | ||
fCtx, &ConvertTextToElementsXMLArguments[any]{ | ||
XPath: ottl.NewTestingOptional("!"), | ||
}) | ||
assert.Error(t, err) | ||
assert.Nil(t, exprFunc) | ||
|
||
// Invalid XML should error on function execution | ||
exprFunc, err = factory.CreateFunction( | ||
fCtx, &ConvertTextToElementsXMLArguments[any]{ | ||
Target: invalidXMLGetter(), | ||
}) | ||
assert.NoError(t, err) | ||
assert.NotNil(t, exprFunc) | ||
_, err = exprFunc(context.Background(), nil) | ||
assert.Error(t, err) | ||
} |
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
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.