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 ability to parse conditions #29315

Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
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/ottl-condition-parser-add-interfaces.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 ability to independently parse OTTL conditions.

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

# (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: [api]
84 changes: 77 additions & 7 deletions pkg/ottl/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package ottl // import "github.com/open-telemetry/opentelemetry-collector-contri

import (
"context"
"errors"
"fmt"
"strings"

Expand Down Expand Up @@ -32,13 +33,6 @@ func (e *ErrorMode) UnmarshalText(text []byte) error {
}
}

type Parser[K any] struct {
functions map[string]Factory[K]
pathParser PathExpressionParser[K]
enumParser EnumParser
telemetrySettings component.TelemetrySettings
}

// Statement holds a top level Statement for processing telemetry data. A Statement is a combination of a function
// invocation and the boolean expression to match telemetry for invoking the function.
type Statement[K any] struct {
Expand Down Expand Up @@ -66,6 +60,26 @@ func (s *Statement[K]) Execute(ctx context.Context, tCtx K) (any, bool, error) {
return result, condition, nil
}

// Condition holds a top level Condition. A Condition is a boolean expression to match telemetry.
type Condition[K any] struct {
condition BoolExpr[K]
origText string
}

// Eval returns true if the condition was met for the given TransformContext and false otherwise.
func (c *Condition[K]) Eval(ctx context.Context, tCtx K) (bool, error) {
return c.condition.Eval(ctx, tCtx)
}

// Parser provides the means to parse OTTL Statements and Conditions given a specific set of functions,
// a PathExpressionParser, and an EnumParser.
type Parser[K any] struct {
functions map[string]Factory[K]
pathParser PathExpressionParser[K]
enumParser EnumParser
telemetrySettings component.TelemetrySettings
}

func NewParser[K any](
functions map[string]Factory[K],
pathParser PathExpressionParser[K],
Expand Down Expand Up @@ -141,7 +155,49 @@ func (p *Parser[K]) ParseStatement(statement string) (*Statement[K], error) {
}, nil
}

// ParseConditions parses string conditions into a Condition slice ready for execution.
// Returns a slice of Condition and a nil error on successful parsing.
// If parsing fails, returns nil and an error containing each error per failed condition.
func (p *Parser[K]) ParseConditions(conditions []string) ([]*Condition[K], error) {
parsedConditions := make([]*Condition[K], 0, len(conditions))
var parseErrs []error

for _, condition := range conditions {
ps, err := p.ParseCondition(condition)
if err != nil {
parseErrs = append(parseErrs, fmt.Errorf("unable to parse OTTL condition %q: %w", condition, err))
continue
}
parsedConditions = append(parsedConditions, ps)
}

if len(parseErrs) > 0 {
return nil, errors.Join(parseErrs...)
}

return parsedConditions, nil
}

// ParseCondition parses a single string condition into a Condition objects ready for execution.
// Returns an Condition and a nil error on successful parsing.
// If parsing fails, returns nil and an error.
func (p *Parser[K]) ParseCondition(condition string) (*Condition[K], error) {
parsed, err := parseCondition(condition)
if err != nil {
return nil, err
}
expression, err := p.newBoolExpr(parsed)
if err != nil {
return nil, err
}
return &Condition[K]{
condition: expression,
origText: condition,
}, nil
}

var parser = newParser[parsedStatement]()
var conditionParser = newParser[booleanExpression]()

func parseStatement(raw string) (*parsedStatement, error) {
parsed, err := parser.ParseString("", raw)
Expand All @@ -157,6 +213,20 @@ func parseStatement(raw string) (*parsedStatement, error) {
return parsed, nil
}

func parseCondition(raw string) (*booleanExpression, error) {
parsed, err := conditionParser.ParseString("", raw)

if err != nil {
return nil, fmt.Errorf("condition has invalid syntax: %w", err)
}
err = parsed.checkForCustomError()
if err != nil {
return nil, err
}

return parsed, nil
}

// newParser returns a parser that can be used to read a string into a parsedStatement. An error will be returned if the string
// is not formatted for the DSL.
func newParser[G any]() *participle.Parser[G] {
Expand Down
Loading
Loading