Skip to content

Commit

Permalink
[receiver/hostmetricsreceiver] Add support for cpu frequency metric (#…
Browse files Browse the repository at this point in the history
…27445)

**Description:** : Added support for host's cpu frequency as part
                   of the hostmetricsreceiver.

**Link to tracking Issue:** #26532

**Testing:**

1. Using the following configuration:
```yml
receivers:
  hostmetrics:
    collection_interval: 5s
    scrapers:
      cpu:
        metrics:
          system.cpu.frequency:
            enabled: true

processors:
  resourcedetection/system:
    detectors: ["system"]
    system:
      hostname_sources: ["lookup", "cname", "dns", "os"]
      resource_attributes:
        host.name:
          enabled: true
        host.id:
          enabled: true
        host.cpu.cache.l2.size:
          enabled: true
        host.cpu.family:
          enabled: true
        host.cpu.model.id:
          enabled: true
        host.cpu.model.name:
          enabled: true
        host.cpu.stepping:
          enabled: true
        host.cpu.vendor.id:
          enabled: true

service:
  pipelines:
    metrics:
      receivers: [hostmetrics]
      exporters: [file]
      processors: [resourcedetection/system]

exporters:
  file:
    path: ./output.json
```

2. Start the collector with ./bin/otelcontribcol_linux_amd64 --config
examples/host_config.yaml
3. The output reports the added metric successfully:

```json
{
   "resourceMetrics":[
      {
         "scopeMetrics":[
            {
               "scope":{
                  "name":"otelcol/hostmetricsreceiver/cpu",
                  "version":"0.85.0-dev"
               },
               "metrics":[
                  {
                     "name":"system.cpu.frequency",
                     "description":"Current frequency of the CPU core in MHz.",
                     "unit":"MHz",
                     "gauge":{
                        "dataPoints":[
                           {
                              "attributes":[
                                 {
                                    "key":"cpu",
                                    "value":{
                                       "stringValue":"cpu0"
                                    }
                                 }
                              ],
                              "startTimeUnixNano":"1696487580000000000",
                              "timeUnixNano":"1696512423758783158",
                              "asDouble":3000
                           },
                           {
                              "attributes":[
                                 {
                                    "key":"cpu",
                                    "value":{
                                       "stringValue":"cpu1"
                                    }
                                 }
                              ],
                              "startTimeUnixNano":"1696487580000000000",
                              "timeUnixNano":"1696512423758783158",
                              "asDouble":3000
                           },
...
```

Signed-off-by: ChrsMark <chrismarkou92@gmail.com>
  • Loading branch information
ChrsMark authored Oct 31, 2023
1 parent faada96 commit 1c63ac9
Show file tree
Hide file tree
Showing 12 changed files with 181 additions and 1 deletion.
27 changes: 27 additions & 0 deletions .chloggen/cpuinfo_frequency_metric.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: receiver/hostmetricsreceiver

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Added support for host's cpuinfo frequnecies.

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [27445]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext: In Linux the current frequency is populated using the values from /proc/cpuinfo. An os specific implementation will be needed for Windows and others.

# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: []
2 changes: 1 addition & 1 deletion receiver/hostmetricsreceiver/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ require (
github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal v0.88.0
github.com/open-telemetry/opentelemetry-collector-contrib/internal/filter v0.88.0
github.com/open-telemetry/opentelemetry-collector-contrib/pkg/pdatatest v0.88.0
github.com/prometheus/procfs v0.11.1
github.com/shirou/gopsutil/v3 v3.23.9
github.com/stretchr/testify v1.8.4
github.com/yusufpapurcu/wmi v1.2.3
Expand Down Expand Up @@ -79,7 +80,6 @@ require (
github.com/prometheus/client_golang v1.17.0 // indirect
github.com/prometheus/client_model v0.5.0 // indirect
github.com/prometheus/common v0.45.0 // indirect
github.com/prometheus/procfs v0.11.1 // indirect
github.com/prometheus/statsd_exporter v0.22.7 // indirect
github.com/shoenig/go-m1cpu v0.1.6 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package cpuscraper // import "github.com/open-telemetry/opentelemetry-collector-

import (
"context"
"fmt"
"time"

"github.com/shirou/gopsutil/v3/common"
Expand All @@ -21,6 +22,7 @@ import (
)

const metricsLen = 2
const hzInAMHz = 1_000_000

// scraper for CPU Metrics
type scraper struct {
Expand All @@ -35,6 +37,11 @@ type scraper struct {
now func() time.Time
}

type cpuInfo struct {
frequency float64
processor uint
}

// newCPUScraper creates a set of CPU related metrics
func newCPUScraper(_ context.Context, settings receiver.CreateSettings, cfg *Config) *scraper {
return &scraper{settings: settings, config: cfg, bootTime: host.BootTimeWithContext, times: cpu.TimesWithContext, ucal: &ucal.CPUUtilizationCalculator{}, now: time.Now}
Expand Down Expand Up @@ -79,5 +86,15 @@ func (s *scraper) scrape(ctx context.Context) (pmetric.Metrics, error) {
}
s.mb.RecordSystemCPULogicalCountDataPoint(now, int64(numCPU))

if s.config.MetricsBuilderConfig.Metrics.SystemCPUFrequency.Enabled {
cpuInfos, err := s.getCPUInfo()
if err != nil {
return pmetric.NewMetrics(), scrapererror.NewPartialScrapeError(err, metricsLen)
}
for _, cInfo := range cpuInfos {
s.mb.RecordSystemCPUFrequencyDataPoint(now, cInfo.frequency*hzInAMHz, fmt.Sprintf("cpu%d", cInfo.processor))
}
}

return s.mb.Emit(), nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
package cpuscraper // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/cpuscraper"

import (
"github.com/prometheus/procfs"
"github.com/shirou/gopsutil/v3/cpu"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/receiver/scrapererror"

"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/internal/metadata"
"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal/scraper/cpuscraper/ucal"
Expand All @@ -35,3 +37,23 @@ func (s *scraper) recordCPUUtilization(now pcommon.Timestamp, cpuUtilization uca
s.mb.RecordSystemCPUUtilizationDataPoint(now, cpuUtilization.Steal, cpuUtilization.CPU, metadata.AttributeStateSteal)
s.mb.RecordSystemCPUUtilizationDataPoint(now, cpuUtilization.Iowait, cpuUtilization.CPU, metadata.AttributeStateWait)
}

func (s *scraper) getCPUInfo() ([]cpuInfo, error) {
var cpuInfos []cpuInfo
fs, err := procfs.NewDefaultFS()
if err != nil {
return nil, scrapererror.NewPartialScrapeError(err, metricsLen)
}
cInf, err := fs.CPUInfo()
if err != nil {
return nil, scrapererror.NewPartialScrapeError(err, metricsLen)
}
for _, cInfo := range cInf {
c := cpuInfo{
frequency: cInfo.CPUMHz,
processor: cInfo.Processor,
}
cpuInfos = append(cpuInfos, c)
}
return cpuInfos, nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,8 @@ func (s *scraper) recordCPUUtilization(now pcommon.Timestamp, cpuUtilization uca
s.mb.RecordSystemCPUUtilizationDataPoint(now, cpuUtilization.Idle, cpuUtilization.CPU, metadata.AttributeStateIdle)
s.mb.RecordSystemCPUUtilizationDataPoint(now, cpuUtilization.Irq, cpuUtilization.CPU, metadata.AttributeStateInterrupt)
}

func (s *scraper) getCPUInfo() ([]cpuInfo, error) {
var cpuInfos []cpuInfo
return cpuInfos, nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,20 @@ metrics:
enabled: true
```
### system.cpu.frequency
Current frequency of the CPU core in Hz.
| Unit | Metric Type | Value Type |
| ---- | ----------- | ---------- |
| Hz | Gauge | Double |
#### Attributes
| Name | Description | Values |
| ---- | ----------- | ------ |
| cpu | Logical CPU number starting at 0. | Any Str |
### system.cpu.logical.count
Number of available logical CPUs.
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
default:
all_set:
metrics:
system.cpu.frequency:
enabled: true
system.cpu.logical.count:
enabled: true
system.cpu.physical.count:
Expand All @@ -11,6 +13,8 @@ all_set:
enabled: true
none_set:
metrics:
system.cpu.frequency:
enabled: false
system.cpu.logical.count:
enabled: false
system.cpu.physical.count:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,11 @@ metrics:
value_type: int
monotonic: false
aggregation_temporality: cumulative

system.cpu.frequency:
enabled: false
description: Current frequency of the CPU core in Hz.
unit: "Hz"
gauge:
value_type: double
attributes: [cpu]

0 comments on commit 1c63ac9

Please sign in to comment.