Skip to content

Commit

Permalink
Check host fields type before converting to common.MapStr (elastic#20791
Browse files Browse the repository at this point in the history
)
  • Loading branch information
kaiyan-sheng authored and melchiormoulin committed Oct 14, 2020
1 parent 48c1da6 commit 0ed3a07
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 6 deletions.
29 changes: 23 additions & 6 deletions libbeat/processors/add_host_metadata/add_host_metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,29 @@ func skipAddingHostMetadata(event *beat.Event) bool {
return false
}

hostFieldsMap := hostFields.(common.MapStr)
// or if "name" is the only field, don't skip
hasName, _ := hostFieldsMap.HasKey("name")
if hasName && len(hostFieldsMap) == 1 {
switch m := hostFields.(type) {
case common.MapStr:
// if "name" is the only field, don't skip
hasName, _ := m.HasKey("name")
if hasName && len(m) == 1 {
return false
}
return true
case map[string]interface{}:
hostMapStr := common.MapStr(m)
// if "name" is the only field, don't skip
hasName, _ := hostMapStr.HasKey("name")
if hasName && len(m) == 1 {
return false
}
return true
case map[string]string:
// if "name" is the only field, don't skip
if m["name"] != "" && len(m) == 1 {
return false
}
return true
default:
return false
}

return true
}
46 changes: 46 additions & 0 deletions libbeat/processors/add_host_metadata/add_host_metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,16 @@ func TestEventWithReplaceFieldsTrue(t *testing.T) {
}

func TestSkipAddingHostMetadata(t *testing.T) {
hostIDMap := map[string]string{}
hostIDMap["id"] = hostID

hostNameMap := map[string]string{}
hostNameMap["name"] = hostName

hostIDNameMap := map[string]string{}
hostIDNameMap["id"] = hostID
hostIDNameMap["name"] = hostName

cases := []struct {
title string
event beat.Event
Expand Down Expand Up @@ -403,6 +413,42 @@ func TestSkipAddingHostMetadata(t *testing.T) {
},
false,
},
{
"event with field type map[string]string hostID",
beat.Event{
Fields: common.MapStr{
"host": hostIDMap,
},
},
true,
},
{
"event with field type map[string]string host name",
beat.Event{
Fields: common.MapStr{
"host": hostNameMap,
},
},
false,
},
{
"event with field type map[string]string host ID and name",
beat.Event{
Fields: common.MapStr{
"host": hostIDNameMap,
},
},
true,
},
{
"event with field type string",
beat.Event{
Fields: common.MapStr{
"host": "string",
},
},
false,
},
}

for _, c := range cases {
Expand Down

0 comments on commit 0ed3a07

Please sign in to comment.