Skip to content

Commit

Permalink
[pkg/ottl] Add ParseSimplifiedXML Converter
Browse files Browse the repository at this point in the history
  • Loading branch information
djaglowski committed Sep 26, 2024
1 parent 2ef6000 commit 4b55252
Show file tree
Hide file tree
Showing 6 changed files with 467 additions and 2 deletions.
27 changes: 27 additions & 0 deletions .chloggen/ottl-parse-simple-xml.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: Add ParseSimplifiedXML Converter

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

# (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: []
9 changes: 9 additions & 0 deletions pkg/ottl/e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,15 @@ func Test_e2e_converters(t *testing.T) {
m.PutStr("k2", "v2__!__v2")
},
},
{
statement: `set(attributes["test"], ParseSimplifiedXML("<Log><id>1</id><Message>This is a log message!</Message></Log>"))`,
want: func(tCtx ottllog.TransformContext) {
attr := tCtx.GetLogRecord().Attributes().PutEmptyMap("test")
log := attr.PutEmptyMap("Log")
log.PutStr("id", "1")
log.PutStr("Message", "This is a log message!")
},
},
{
statement: `set(attributes["test"], ParseXML("<Log id=\"1\"><Message>This is a log message!</Message></Log>"))`,
want: func(tCtx ottllog.TransformContext) {
Expand Down
20 changes: 18 additions & 2 deletions pkg/ottl/ottlfuncs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1250,8 +1250,7 @@ An element has "extraneous text content" when it contains both text and element

#### Parsing logic

1. The Converter will NOT error due to the presence of attributes or extraneous text content.
However, it will omit those values from the result.
1. Declaration elements, attributes, comments, and extraneous text content are ignored.
2. Elements which contain a value are converted into key/value pairs.
e.g. `<foo>bar</foo>` becomes `"foo": "bar"`
3. Elements which contain child elements are converted into a key/value pair where the value is a map.
Expand Down Expand Up @@ -1326,6 +1325,23 @@ Parse a Simplified XML document with multiple elements of the same tag:
}
```

Parse a Simplified XML document with CDATA element:

```xml
<a>
<b>1</b>
<b><![CDATA[2]]></b>
</a>
```

```json
{
"a": {
"b": ["1", "2"]
}
}
```

### ParseXML

`ParseXML(target)`
Expand Down
134 changes: 134 additions & 0 deletions pkg/ottl/ottlfuncs/func_parse_simplified_xml.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// 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"
"go.opentelemetry.io/collector/pdata/pcommon"

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

type ParseSimplifiedXMLArguments[K any] struct {
Target ottl.StringGetter[K]
}

func NewParseSimplifiedXMLFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("ParseSimplifiedXML", &ParseSimplifiedXMLArguments[K]{}, createParseSimplifiedXMLFunction[K])
}

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

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

return parseSimplifiedXML(args.Target), nil
}

// The `ParseSimplifiedXML` Converter returns a `pcommon.Map` struct that is the result of parsing the target
// string without preservation of attributes or extraneous text content.
func parseSimplifiedXML[K any](target ottl.StringGetter[K]) 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
}

docMap := pcommon.NewMap()
parseElement(doc, &docMap)
return docMap, nil
}
}

func parseElement(parent *xmlquery.Node, parentMap *pcommon.Map) {
// Count the number of each element tag so we know whether it will be a member of a slice or not
childTags := make(map[string]int)
for child := parent.FirstChild; child != nil; child = child.NextSibling {
if child.Type != xmlquery.ElementNode {
continue
}
childTags[child.Data]++
}
if len(childTags) == 0 {
return
}

// Convert the children, now knowing whether they will be a member of a slice or not
for child := parent.FirstChild; child != nil; child = child.NextSibling {
if child.Type != xmlquery.ElementNode || child.FirstChild == nil {
continue
}

leafValue := leafValueFromElement(child)

// Slice of the same element
if childTags[child.Data] > 1 {
// Get or create the slice of children
var childrenSlice pcommon.Slice
childrenValue, ok := parentMap.Get(child.Data)
if ok {
childrenSlice = childrenValue.Slice()
} else {
childrenSlice = parentMap.PutEmptySlice(child.Data)
}

// Add the child's text content to the slice
if leafValue != "" {
childrenSlice.AppendEmpty().SetStr(leafValue)
continue
}

// Parse the child to make sure there's something to add
childMap := pcommon.NewMap()
parseElement(child, &childMap)
if childMap.Len() == 0 {
continue
}

sliceValue := childrenSlice.AppendEmpty()
sliceMap := sliceValue.SetEmptyMap()
childMap.CopyTo(sliceMap)
continue
}

if leafValue != "" {
parentMap.PutStr(child.Data, leafValue)
continue
}

// Child will be a map
childMap := pcommon.NewMap()
parseElement(child, &childMap)
if childMap.Len() == 0 {
continue
}

childMap.CopyTo(parentMap.PutEmptyMap(child.Data))
}
}

func leafValueFromElement(node *xmlquery.Node) string {
// First check if there are any child elements. If there are, ignore any extraneous text.
for child := node.FirstChild; child != nil; child = child.NextSibling {
if child.Type == xmlquery.ElementNode {
return ""
}
}

// No child elements, so return the first text or CDATA content
for child := node.FirstChild; child != nil; child = child.NextSibling {
switch child.Type {
case xmlquery.TextNode, xmlquery.CharDataNode:
return child.Data
}
}
return ""
}
Loading

0 comments on commit 4b55252

Please sign in to comment.