From 2c0baecffa3eba30b90072a6e5a0e8a67ddd31af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Graber?= Date: Sat, 26 Apr 2025 16:34:50 -0400 Subject: [PATCH] incus-agent: Reduce code duplication MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Stéphane Graber --- cmd/incus-agent/metrics.go | 5 +---- cmd/incus-agent/os_linux.go | 43 ++----------------------------------- 2 files changed, 3 insertions(+), 45 deletions(-) diff --git a/cmd/incus-agent/metrics.go b/cmd/incus-agent/metrics.go index 20f0ec5e3..0e1b222cf 100644 --- a/cmd/incus-agent/metrics.go +++ b/cmd/incus-agent/metrics.go @@ -49,10 +49,7 @@ func metricsGet(d *Daemon, r *http.Request) response.Response { out.Network = netStats } - out.ProcessesTotal, err = osGetTotalProcesses(d) - if err != nil { - logger.Warn("Failed to get total processes", logger.Ctx{"err": err}) - } + out.ProcessesTotal = uint64(osGetProcessesState()) cpuStats, err := osGetCPUMetrics(d) if err != nil { diff --git a/cmd/incus-agent/os_linux.go b/cmd/incus-agent/os_linux.go index a3ce773b0..7888f2895 100644 --- a/cmd/incus-agent/os_linux.go +++ b/cmd/incus-agent/os_linux.go @@ -245,45 +245,6 @@ func osGetCPUMetrics(d *Daemon) ([]metrics.CPUMetrics, error) { return out, nil } -func osGetTotalProcesses(d *Daemon) (uint64, error) { - entries, err := os.ReadDir("/proc") - if err != nil { - return 0, fmt.Errorf("Failed to read dir %q: %w", "/proc", err) - } - - pidCount := uint64(0) - - for _, entry := range entries { - // Skip everything which isn't a directory - if !entry.IsDir() { - continue - } - - name := entry.Name() - - // Skip all non-PID directories - _, err := strconv.ParseUint(name, 10, 64) - if err != nil { - continue - } - - cmdlinePath := filepath.Join("/proc", name, "cmdline") - - cmdline, err := os.ReadFile(cmdlinePath) - if err != nil { - continue - } - - if string(cmdline) == "" { - continue - } - - pidCount++ - } - - return pidCount, nil -} - func osGetDiskMetrics(d *Daemon) ([]metrics.DiskMetrics, error) { diskStats, err := os.ReadFile("/proc/diskstats") if err != nil { @@ -637,12 +598,12 @@ func osGetNetworkState() map[string]api.InstanceStateNetwork { func osGetProcessesState() int64 { pids := []int64{1} - // Go through the pid list, adding new pids at the end so we go through them all + // Go through the pid list, adding new pids at the end so we go through them all. for i := 0; i < len(pids); i++ { fname := fmt.Sprintf("/proc/%d/task/%d/children", pids[i], pids[i]) fcont, err := os.ReadFile(fname) if err != nil { - // the process terminated during execution of this loop + // The process terminated during execution of this loop. continue }