|
| 1 | +// Copyright 2024 The Prometheus Authors |
| 2 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +// you may not use this file except in compliance with the License. |
| 4 | +// You may obtain a copy of the License at |
| 5 | +// |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | +// |
| 8 | +// Unless required by applicable law or agreed to in writing, software |
| 9 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 | +// See the License for the specific language governing permissions and |
| 12 | +// limitations under the License. |
| 13 | + |
| 14 | +//go:build !nocpu |
| 15 | +// +build !nocpu |
| 16 | + |
| 17 | +package collector |
| 18 | + |
| 19 | +/* |
| 20 | +#include <unistd.h> // Include the standard Unix header |
| 21 | +#include <errno.h> // For errno |
| 22 | +*/ |
| 23 | +import "C" |
| 24 | +import ( |
| 25 | + "fmt" |
| 26 | + "log/slog" |
| 27 | + "strconv" |
| 28 | + |
| 29 | + "github.com/power-devops/perfstat" |
| 30 | + "github.com/prometheus/client_golang/prometheus" |
| 31 | +) |
| 32 | + |
| 33 | +type cpuCollector struct { |
| 34 | + cpu typedDesc |
| 35 | + logger *slog.Logger |
| 36 | + tickPerSecond int64 |
| 37 | +} |
| 38 | + |
| 39 | +func init() { |
| 40 | + registerCollector("cpu", defaultEnabled, NewCpuCollector) |
| 41 | +} |
| 42 | + |
| 43 | +func tickPerSecond() (int64, error) { |
| 44 | + ticks, err := C.sysconf(C._SC_CLK_TCK) |
| 45 | + if ticks == -1 || err != nil { |
| 46 | + return 0, fmt.Errorf("failed to get clock ticks per second: %v", err) |
| 47 | + } |
| 48 | + return int64(ticks), nil |
| 49 | +} |
| 50 | + |
| 51 | +func NewCpuCollector(logger *slog.Logger) (Collector, error) { |
| 52 | + ticks, err := tickPerSecond() |
| 53 | + if err != nil { |
| 54 | + return nil, err |
| 55 | + } |
| 56 | + return &cpuCollector{ |
| 57 | + cpu: typedDesc{nodeCPUSecondsDesc, prometheus.CounterValue}, |
| 58 | + logger: logger, |
| 59 | + tickPerSecond: ticks, |
| 60 | + }, nil |
| 61 | +} |
| 62 | + |
| 63 | +func (c *cpuCollector) Update(ch chan<- prometheus.Metric) error { |
| 64 | + stats, err := perfstat.CpuStat() |
| 65 | + if err != nil { |
| 66 | + return err |
| 67 | + } |
| 68 | + |
| 69 | + for n, stat := range stats { |
| 70 | + ch <- c.cpu.mustNewConstMetric(float64(stat.User/c.tickPerSecond), strconv.Itoa(n), "user") |
| 71 | + ch <- c.cpu.mustNewConstMetric(float64(stat.Sys/c.tickPerSecond), strconv.Itoa(n), "system") |
| 72 | + ch <- c.cpu.mustNewConstMetric(float64(stat.Idle/c.tickPerSecond), strconv.Itoa(n), "idle") |
| 73 | + ch <- c.cpu.mustNewConstMetric(float64(stat.Wait/c.tickPerSecond), strconv.Itoa(n), "wait") |
| 74 | + } |
| 75 | + return nil |
| 76 | +} |
0 commit comments