Skip to content
Closed
Show file tree
Hide file tree
Changes from 5 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-profilelocation.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 OTTL support for location submessage of OTel Profiling signal.

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

# (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]
16 changes: 16 additions & 0 deletions pkg/ottl/contexts/internal/ctxprofilelocation/context.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ctxprofilelocation // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/contexts/internal/ctxprofilelocation"

import "go.opentelemetry.io/collector/pdata/pprofile"

const (
Name = "profilelocation"
DocRef = "https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/pkg/ottl/contexts/ottlprofilelocation"
)

type Context interface {
GetProfileLocation() pprofile.Location
GetProfilesDictionary() pprofile.ProfilesDictionary
}
168 changes: 168 additions & 0 deletions pkg/ottl/contexts/internal/ctxprofilelocation/profilelocation.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ctxprofilelocation // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/contexts/internal/ctxprofilelocation"

import (
"context"
"errors"
"math"

"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/pprofile"

"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/contexts/internal/ctxerror"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/contexts/internal/ctxutil"
)

var (
errMaxValueExceed = errors.New("exceeded max value")
errInvalidValueType = errors.New("invalid value type")
)

func PathGetSetter[K Context](path ottl.Path[K]) (ottl.GetSetter[K], error) {
if path == nil {
return nil, ctxerror.New("nil", "nil", Name, DocRef)
}
switch path.Name() {
case "mapping_index":
return accessMappingIndex[K](), nil
case "address":
return accessAddress[K](), nil
case "line":
return accessLine[K](), nil
case "attribute_indices":
return accessAttributeIndices[K](), nil
case "attributes":
if path.Keys() == nil {
return accessAttributes[K](), nil
}
return accessAttributesKey(path.Keys()), nil
default:
return nil, ctxerror.New(path.Name(), path.String(), Name, DocRef)
}
}

func accessMappingIndex[K Context]() ottl.StandardGetSetter[K] {
return ottl.StandardGetSetter[K]{
Getter: func(_ context.Context, tCtx K) (any, error) {
return int64(tCtx.GetProfileLocation().MappingIndex()), nil
},
Setter: func(_ context.Context, tCtx K, val any) error {
if v, ok := val.(int64); ok {
if v >= math.MaxInt32 {
return errMaxValueExceed
}
tCtx.GetProfileLocation().SetMappingIndex(int32(v))
return nil
}
return errInvalidValueType
},
}
}

func accessAddress[K Context]() ottl.StandardGetSetter[K] {
return ottl.StandardGetSetter[K]{
Getter: func(_ context.Context, tCtx K) (any, error) {
return tCtx.GetProfileLocation().Address(), nil
},
Setter: func(_ context.Context, tCtx K, val any) error {
if v, ok := val.(uint64); ok {
Copy link
Contributor

Choose a reason for hiding this comment

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

Please use int64 for getting and setting integer values. OTTL cannot produce uint64 values unless it's coming from non-standardized paths, which should be avoided.

tCtx.GetProfileLocation().SetAddress(v)
return nil
}
return errInvalidValueType
},
}
}

func accessLine[K Context]() ottl.StandardGetSetter[K] {
return ottl.StandardGetSetter[K]{
Getter: func(_ context.Context, tCtx K) (any, error) {
return tCtx.GetProfileLocation().Line(), nil
},
Setter: func(_ context.Context, tCtx K, val any) error {
lines, ok := val.(pprofile.LineSlice)
if !ok {
return errInvalidValueType
}
tCtx.GetProfileLocation().Line().RemoveIf(func(_ pprofile.Line) bool { return true })
_ = lines
for _, line := range lines.All() {
newLine := tCtx.GetProfileLocation().Line().AppendEmpty()
line.CopyTo(newLine)
}
return nil
},
}
}

func accessAttributeIndices[K Context]() ottl.StandardGetSetter[K] {
return ottl.StandardGetSetter[K]{
Getter: func(_ context.Context, tCtx K) (any, error) {
return ctxutil.GetCommonIntSliceValues[int32](tCtx.GetProfileLocation().AttributeIndices()), nil
},
Setter: func(_ context.Context, tCtx K, val any) error {
return ctxutil.SetCommonIntSliceValues[int32](tCtx.GetProfileLocation().AttributeIndices(), val)
},
}
}

func accessAttributes[K Context]() ottl.StandardGetSetter[K] {
return ottl.StandardGetSetter[K]{
Getter: func(_ context.Context, tCtx K) (any, error) {
return pprofile.FromAttributeIndices(tCtx.GetProfilesDictionary().AttributeTable(), tCtx.GetProfileLocation()), nil
},
Setter: func(_ context.Context, tCtx K, val any) error {
m, err := ctxutil.GetMap(val)
if err != nil {
return err
}
tCtx.GetProfileLocation().AttributeIndices().FromRaw([]int32{})
for k, v := range m.All() {
if err := pprofile.PutAttribute(tCtx.GetProfilesDictionary().AttributeTable(), tCtx.GetProfileLocation(), k, v); err != nil {
return err
}
}
return nil
},
}
}

func accessAttributesKey[K Context](key []ottl.Key[K]) ottl.StandardGetSetter[K] {
return ottl.StandardGetSetter[K]{
Getter: func(ctx context.Context, tCtx K) (any, error) {
return ctxutil.GetMapValue[K](ctx, tCtx, pprofile.FromAttributeIndices(tCtx.GetProfilesDictionary().AttributeTable(), tCtx.GetProfileLocation()), key)
},
Setter: func(ctx context.Context, tCtx K, val any) error {
newKey, err := ctxutil.GetMapKeyName(ctx, tCtx, key[0])
if err != nil {
return err
}
v := getAttributeValue(tCtx, *newKey)
if err := ctxutil.SetIndexableValue[K](ctx, tCtx, v, val, key[1:]); err != nil {
return err
}
return pprofile.PutAttribute(tCtx.GetProfilesDictionary().AttributeTable(), tCtx.GetProfileLocation(), *newKey, v)
},
}
}

func getAttributeValue[K Context](tCtx K, key string) pcommon.Value {
// Find the index of the attribute in the profile's attribute indices
// and return the corresponding value from the attribute table.
table := tCtx.GetProfilesDictionary().AttributeTable()
indices := tCtx.GetProfileLocation().AttributeIndices().AsRaw()

for _, tableIndex := range indices {
attr := table.At(int(tableIndex))
if attr.Key() == key {
v := pcommon.NewValueEmpty()
attr.Value().CopyTo(v)
return v
}
}

return pcommon.NewValueEmpty()
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ctxprofilelocation // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/contexts/internal/ctxprofilelocation"

import (
"strings"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/pdata/pprofile"

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

func TestPathGetSetter(t *testing.T) {
lineSlice := pprofile.NewLineSlice()
for _, lineValue := range []int64{73, 74, 75} {
line := lineSlice.AppendEmpty()
line.SetLine(lineValue)
}
tests := []struct {
path string
val any
keys []ottl.Key[*profileLocationContext]
}{
{
path: "mapping_index",
val: int64(42),
},
{
path: "address",
val: uint64(43),
},
{
path: "line",
val: lineSlice,
},
{
path: "attribute_indices",
val: []int64{97, 98, 99},
},
}

for _, tt := range tests {
t.Run(tt.path, func(t *testing.T) {
pathParts := strings.Split(tt.path, " ")
path := &pathtest.Path[*profileLocationContext]{N: pathParts[0]}
if tt.keys != nil {
path.KeySlice = tt.keys
}
if len(pathParts) > 1 {
path.NextPath = &pathtest.Path[*profileLocationContext]{N: pathParts[1]}
}

location := pprofile.NewLocation()
dictionary := pprofile.NewProfilesDictionary()

accessor, err := PathGetSetter(path)
require.NoError(t, err)

err = accessor.Set(t.Context(), newProfileLocationContext(location, dictionary), tt.val)
require.NoError(t, err)

got, err := accessor.Get(t.Context(), newProfileLocationContext(location, dictionary))
require.NoError(t, err)

assert.Equal(t, tt.val, got)
})
}
}

type profileLocationContext struct {
location pprofile.Location
dictionary pprofile.ProfilesDictionary
}

func (p *profileLocationContext) GetProfilesDictionary() pprofile.ProfilesDictionary {
return p.dictionary
}

func (p *profileLocationContext) GetProfileLocation() pprofile.Location {
return p.location
}

func newProfileLocationContext(location pprofile.Location, dictionary pprofile.ProfilesDictionary) *profileLocationContext {
return &profileLocationContext{location: location, dictionary: dictionary}
}
27 changes: 27 additions & 0 deletions pkg/ottl/contexts/internal/logprofile/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,33 @@ func (s ProfileSample) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
return joinedErr
}

type ProfileLocation struct {
pprofile.Location
Dictionary pprofile.ProfilesDictionary
}

func (loc ProfileLocation) MarshalLogObject(encoder zapcore.ObjectEncoder) error {
var joinedErr error

encoder.AddInt32("mapping_index", loc.MappingIndex())
encoder.AddUint64("address", loc.Address())

ls := make(lines, 0, loc.Line().Len())
lines := loc.Line().All()
for _, line := range lines {
l, err := newLine(loc.Dictionary, line)
joinedErr = errors.Join(joinedErr, err)
ls = append(ls, l)
}
joinedErr = errors.Join(joinedErr, encoder.AddArray("line", ls))

ats, err := newAttributes(loc.Dictionary, loc.AttributeIndices())
joinedErr = errors.Join(joinedErr, err)
joinedErr = errors.Join(joinedErr, encoder.AddArray("attributes", ats))

return joinedErr
}

type valueTypes []valueType

func (s valueTypes) MarshalLogArray(encoder zapcore.ArrayEncoder) error {
Expand Down
30 changes: 30 additions & 0 deletions pkg/ottl/contexts/ottlprofilelocation/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Profile Location Context

> [!NOTE]
> This documentation applies only to version `0.133.0` and later. Information on earlier versions is not available.

The Profile Location Context is a Context implementation for [pdata Profiles](https://github.com/open-telemetry/opentelemetry-collector/tree/main/pdata/pprofile), the collector's internal representation for OTLP profile data. This Context should be used when interacted with OTLP profiles.

## Paths
In general, the Profile Location Context supports accessing pdata using the field names from the [profiles proto](https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/profiles/v1development/profiles.proto). All integers are returned and set via `int64`. All doubles are returned and set via `float64`.

The following paths are supported.

| path | field accessed | type |
|------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------|
| cache | the value of the current transform context's temporary cache. cache can be used as a temporary placeholder for data during complex transformations | pcommon.Map |
| cache\[""\] | the value of an item in cache. Supports multiple indexes to access nested fields | string, bool, int64, float64, pcommon.Map, pcommon.Slice, []byte or nil |
| resource | resource of the profile being processed | pcommon.Resource |
| resource.attributes | resource attributes of the profile being processed | pcommon.Map |
| resource.attributes\[""\] | the value of the resource attribute of the profile being processed. Supports multiple indexes to access nested fields | string, bool, int64, float64, pcommon.Map, pcommon.Slice, []byte or nil |
| instrumentation_scope | instrumentation scope of the profile being processed | pcommon.InstrumentationScope |
| instrumentation_scope.name | name of the instrumentation scope of the profile being processed | string |
| instrumentation_scope.version | version of the instrumentation scope of the profile being processed | string |
| instrumentation_scope.attributes | instrumentation scope attributes of the data point being processed | pcommon.Map |
| instrumentation_scope.attributes\[""\] | the value of the instrumentation scope attribute of the data point being processed. Supports multiple indexes to access nested fields | string, bool, int64, float64, pcommon.Map, pcommon.Slice, []byte or nil |
| profilelocation.attributes | attributes of the profile being processed | pcommon.Map |
| profilelocation.attributes\[""\] | the value of the attribute of the profile being processed. Supports multiple indexes to access nested fields | string, bool, int64, float64, pcommon.Map, pcommon.Slice, []byte or nil |
| profilelocation.attribute_indices | the attribute indices of the location being processed | []int64 |
| profilelocation.mapping_index | reference to mapping in ProfilesDictionary.mapping_table | int64 |
| profilelocation.address | the instruction address for this location, if available | int64 |
| profilelocation.line | reference to one or more lines in source code | profile.LineSlice |
14 changes: 14 additions & 0 deletions pkg/ottl/contexts/ottlprofilelocation/package_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package ottlprofilelocation

import (
"testing"

"go.uber.org/goleak"
)

func TestMain(m *testing.M) {
goleak.VerifyTestMain(m)
}
Loading
Loading