Skip to content

Commit

Permalink
change vmstat struct filling algo, use json struct tags
Browse files Browse the repository at this point in the history
  • Loading branch information
fearful-symmetry committed Aug 16, 2019
1 parent 18f2cdf commit a48bf8f
Show file tree
Hide file tree
Showing 3 changed files with 186 additions and 189 deletions.
34 changes: 16 additions & 18 deletions providers/linux/vmstat.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ import (
func parseVMStat(content []byte) (*types.VMStatInfo, error) {
vmStat := &types.VMStatInfo{}
refVal := reflect.ValueOf(vmStat).Elem()
tagMap := make(map[string]*reflect.Value)

//iterate over the struct and make a map of tags->values
for index := 0; index < refVal.NumField(); index++ {
tag := refVal.Type().Field(index).Tag.Get("json")
val := refVal.Field(index)
tagMap[tag] = &val
}

err := parseKeyValue(content, " ", func(key, value []byte) error {
// turn our []byte value into an int
Expand All @@ -37,26 +45,16 @@ func parseVMStat(content []byte) (*types.VMStatInfo, error) {
return errors.Wrapf(err, "failed to parse %v value of %v", string(key), string(value))
}

// Search The struct object to see if we have a field with a tag that matches the raw key coming off the file input
// This is the best way I've found to "search" for a a struct field based on a struct tag value.
// In this case, the /proc/vmstat keys are struct tags.
fieldToSet := refVal.FieldByNameFunc(func(name string) bool {
testField, exists := reflect.TypeOf(vmStat).Elem().FieldByName(name)
if !exists {
return false
}
if testField.Tag.Get("vmstat") == string(key) {
return true
}
return false
})

// This protects us from fields in /proc/vmstat that we don't have added in our struct
// This is just a way to make sure we actually found a field in the above `FieldByNameFunc`
if fieldToSet.CanSet() {
fieldToSet.SetUint(val)
sval, ok := tagMap[string(key)]
if !ok {
return nil
}

if sval.CanSet() {
sval.SetUint(val)
}
return nil

})

return vmStat, err
Expand Down
1 change: 0 additions & 1 deletion providers/linux/vmstat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,6 @@ func TestVmStatParse(t *testing.T) {
if err != nil {
t.Fatal(err)
}

// Check a few values
assert.Equal(t, uint64(8348560), data.SlabsScanned)
assert.Equal(t, uint64(0), data.SwapRa)
Expand Down
Loading

0 comments on commit a48bf8f

Please sign in to comment.