modbot/lib/readers/cpu_usage.go

86 lines
2.2 KiB
Go
Raw Permalink Normal View History

// modbot is a system information agregator
2024-07-30 04:02:05 -04:00
// Copyright (C) 2024 frosty <inthishouseofcards@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
2024-08-25 02:27:55 -04:00
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
2024-07-30 04:02:05 -04:00
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2024-08-25 02:27:55 -04:00
// GNU General Public License for more details.
2024-07-30 04:02:05 -04:00
//
2024-08-25 02:27:55 -04:00
// You should have received a copy of the GNU General Public License
2024-07-30 04:02:05 -04:00
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package readers
import (
"bufio"
"errors"
"fmt"
"os"
"strings"
)
type CpuUsageInfo struct {
InUse uint64
Total uint64
UsagePercent float64
}
func (cu CpuUsageInfo) String() string {
return fmt.Sprintf("%d%%", uint(cu.UsagePercent))
}
func ReadCpuUsage() func() (interface{}, error) {
return func() (interface{}, error) {
file, err := os.Open("/proc/stat")
if err != nil {
return CpuUsageInfo{}, err
}
defer file.Close()
2024-07-30 04:02:05 -04:00
var cpuInUse, cpuTotal uint64
scanner := bufio.NewScanner(file)
2024-07-30 04:02:05 -04:00
scanner.Scan()
for scanner.Scan() {
line := scanner.Text()
2024-07-30 04:02:05 -04:00
if !strings.HasPrefix(line, "cpu") {
break
}
2024-07-30 04:02:05 -04:00
var cpuN string
var cpuUser, cpuNice, cpuSystem, cpuIdle, cpuIoWait, cpuIrq, cpuSoftIrq uint64
2024-07-30 04:02:05 -04:00
_, err := fmt.Sscanf(line, "cpu%s %d %d %d %d %d %d %d",
&cpuN, &cpuUser, &cpuNice, &cpuSystem, &cpuIdle, &cpuIoWait, &cpuIrq, &cpuSoftIrq)
if err != nil {
return CpuUsageInfo{}, fmt.Errorf("failed to parse CPU stats: %w", err)
}
2024-07-30 04:02:05 -04:00
inUse := cpuUser + cpuNice + cpuSystem
total := inUse + cpuIdle + cpuIoWait + cpuIrq + cpuSoftIrq
2024-07-30 04:02:05 -04:00
cpuInUse += inUse
cpuTotal += total
}
2024-07-30 04:02:05 -04:00
if err := scanner.Err(); err != nil {
return CpuUsageInfo{}, err
}
if cpuTotal == 0 {
return CpuUsageInfo{}, errors.New("no CPU stats found")
}
return CpuUsageInfo{
InUse: cpuInUse,
Total: cpuTotal,
UsagePercent: float64(cpuInUse) * 100 / float64(cpuTotal),
}, nil
}
}