Skip to content

Commit

Permalink
feat(inputs.cpu): Add tags with core id or physical id to cpus (#11141)
Browse files Browse the repository at this point in the history
  • Loading branch information
mmolnar authored May 23, 2022
1 parent 622815c commit b5e5f4c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
3 changes: 3 additions & 0 deletions plugins/inputs/cpu/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ The `cpu` plugin gather metrics on the system CPUs.
collect_cpu_time = false
## If true, compute and report the sum of all non-idle CPU states
report_active = false
## If true and the info is available then add core_id and physical_id tags
core_tags = false
```

## Metrics
Expand Down Expand Up @@ -52,6 +54,7 @@ On Linux, consult `man proc` for details on the meanings of these values.

On Linux systems the `/proc/stat` file is used to gather CPU times.
Percentages are based on the last 2 samples.
Tags core_id and physical_id are read from `/proc/cpuinfo` on Linux systems

## Example Output

Expand Down
35 changes: 33 additions & 2 deletions plugins/inputs/cpu/cpu.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,19 @@ import (
)

type CPUStats struct {
ps system.PS
lastStats map[string]cpuUtil.TimesStat
ps system.PS
lastStats map[string]cpuUtil.TimesStat
cpuInfo map[string]cpuUtil.InfoStat
coreID bool
physicalID bool

PerCPU bool `toml:"percpu"`
TotalCPU bool `toml:"totalcpu"`
CollectCPUTime bool `toml:"collect_cpu_time"`
ReportActive bool `toml:"report_active"`
CoreTags bool `toml:"core_tags"`

Log telegraf.Logger `toml:"-"`
}

func NewCPUStats(ps system.PS) *CPUStats {
Expand All @@ -40,6 +46,12 @@ func (c *CPUStats) Gather(acc telegraf.Accumulator) error {
tags := map[string]string{
"cpu": cts.CPU,
}
if c.coreID {
tags["core_id"] = c.cpuInfo[cts.CPU].CoreID
}
if c.physicalID {
tags["physical_id"] = c.cpuInfo[cts.CPU].PhysicalID
}

total := totalCPUTime(cts)
active := activeCPUTime(cts)
Expand Down Expand Up @@ -113,6 +125,25 @@ func (c *CPUStats) Gather(acc telegraf.Accumulator) error {
return err
}

func (c *CPUStats) Init() error {
if c.CoreTags {
cpuInfo, err := cpuUtil.Info()
if err == nil {
c.coreID = cpuInfo[0].CoreID != ""
c.physicalID = cpuInfo[0].PhysicalID != ""

c.cpuInfo = make(map[string]cpuUtil.InfoStat)
for _, ci := range cpuInfo {
c.cpuInfo[fmt.Sprintf("cpu%d", ci.CPU)] = ci
}
} else {
c.Log.Warnf("Failed to gather info about CPUs: %s", err)
}
}

return nil
}

func totalCPUTime(t cpuUtil.TimesStat) float64 {
total := t.User + t.System + t.Nice + t.Iowait + t.Irq + t.Softirq + t.Steal + t.Idle
return total
Expand Down

0 comments on commit b5e5f4c

Please sign in to comment.