Skip to content

Commit

Permalink
[exporter/loki] Allow nested attribute to be promoted to label
Browse files Browse the repository at this point in the history
Fixes #16475

Signed-off-by: Juraci Paixão Kröhling <juraci@kroehling.de>
  • Loading branch information
jpkrohling committed Dec 5, 2022
1 parent 434a961 commit 56a146f
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
23 changes: 22 additions & 1 deletion pkg/translator/loki/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,14 @@ func convertAttributesToLabels(attributes pcommon.Map, attrsToSelect pcommon.Val
attrs := parseAttributeNames(attrsToSelect)
for _, attr := range attrs {
attr = strings.TrimSpace(attr)
av, ok := attributes.Get(attr) // do we need to trim this?

av, ok := attributes.Get(attr)
if !ok {
// couldn't find the attribute under the given name directly
// perhaps it's a nested attribute?
av, ok = getNestedAttribute(attr, attributes) // shadows the OK from above on purpose
}

if ok {
out[model.LabelName(attr)] = model.LabelValue(av.AsString())
}
Expand All @@ -90,6 +97,20 @@ func convertAttributesToLabels(attributes pcommon.Map, attrsToSelect pcommon.Val
return out
}

func getNestedAttribute(attr string, attributes pcommon.Map) (pcommon.Value, bool) {
left, right, _ := strings.Cut(attr, ".")
av, ok := attributes.Get(left)
if !ok {
return pcommon.Value{}, false
}

if len(right) == 0 {
return av, ok
}

return getNestedAttribute(right, av.Map())
}

func parseAttributeNames(attrsToSelect pcommon.Value) []string {
var out []string

Expand Down
31 changes: 31 additions & 0 deletions pkg/translator/loki/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,20 @@ func TestConvertAttributesToLabels(t *testing.T) {
"pod.name": "pod-123",
},
},
{
desc: "nested attributes",
attrsAvailable: map[string]interface{}{
"host": map[string]interface{}{
"name": "guarana",
},
"pod.name": "pod-123",
},
attrsToSelect: attrsToSelectSlice,
expected: model.LabelSet{
"host.name": "guarana",
"pod.name": "pod-123",
},
},
}
for _, tC := range testCases {
t.Run(tC.desc, func(t *testing.T) {
Expand Down Expand Up @@ -213,3 +227,20 @@ func TestRemoveAttributes(t *testing.T) {
})
}
}

func TestGetNestedAttribute(t *testing.T) {
// prepare
attrs := pcommon.NewMap()
attrs.FromRaw(map[string]interface{}{
"host": map[string]interface{}{
"name": "guarana",
},
})

// test
attr, ok := getNestedAttribute("host.name", attrs)

// verify
assert.Equal(t, "guarana", attr.AsString())
assert.True(t, ok)
}

0 comments on commit 56a146f

Please sign in to comment.