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

[9.0](backport #42849) [otelconsumer]: Add support for conversion of type any #42994

Merged
merged 1 commit into from
Mar 4, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
46 changes: 46 additions & 0 deletions libbeat/otelbeat/otelmap/otelmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,9 +168,55 @@ func FromMapstr(m mapstr.M) pcommon.Map {
newVal := dest.AppendEmpty()
newVal.SetStr(i.UTC().Format("2006-01-02T15:04:05.000Z"))
}
case []any:
dest := out.PutEmptySlice(k)
convertValue(v.([]interface{}), dest)
default:
out.PutStr(k, fmt.Sprintf("unknown type: %T", x))
}
}
return out
}

// convertValue converts a slice of any[] to pcommon.Value
func convertValue(v []any, dest pcommon.Slice) {
// Handling the most common types without reflect is a small perf win.
for _, i := range v {
newValue := dest.AppendEmpty()
switch val := i.(type) {
case bool:
newValue.SetBool(val)
case string:
newValue.SetStr(val)
case int:
newValue.SetInt(int64(val))
case int8:
newValue.SetInt(int64(val))
case int16:
newValue.SetInt(int64(val))
case int32:
newValue.SetInt(int64(val))
case int64:
newValue.SetInt(val)
case uint:
newValue.SetInt(int64(val))
case uint8:
newValue.SetInt(int64(val))
case uint16:
newValue.SetInt(int64(val))
case uint32:
newValue.SetInt(int64(val))
case uint64:
newValue.SetInt(int64(val))
case float32:
newValue.SetDouble(float64(val))
case float64:
newValue.SetDouble(val)
case time.Time:
newValue.SetStr(val.UTC().Format("2006-01-02T15:04:05.000Z"))
default:
newValue.SetStr(fmt.Sprintf("unknown type: %T", val))
}

}
}
19 changes: 19 additions & 0 deletions libbeat/otelbeat/otelmap/otelmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,25 @@ func TestFromMapstrSliceInt(t *testing.T) {
assert.Equal(t, want, got)
}

func TestFromMapstrSliceAny(t *testing.T) {
inputSlice := []any{42, "forty-three", true}
inputMap := mapstr.M{
"slice": inputSlice,
}
want := pcommon.NewMap()
sliceOfInt := want.PutEmptySlice("slice")

val := sliceOfInt.AppendEmpty()
val.SetInt(int64(inputSlice[0].(int)))
val = sliceOfInt.AppendEmpty()
val.SetStr(inputSlice[1].(string))
val = sliceOfInt.AppendEmpty()
val.SetBool(inputSlice[2].(bool))

got := FromMapstr(inputMap)
assert.Equal(t, want, got)
}

func TestFromMapstrDouble(t *testing.T) {
tests := map[string]struct {
mapstr_val interface{}
Expand Down
Loading