You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/stat/internal/cpu_linux.go

144 lines
2.3 KiB
Go

4 years ago
package internal
import (
"errors"
"fmt"
"strings"
"sync"
4 years ago
"time"
"github.com/zeromicro/go-zero/core/iox"
"github.com/zeromicro/go-zero/core/logx"
4 years ago
)
const (
cpuTicks = 100
cpuFields = 8
cpuMax = 1000
statFile = "/proc/stat"
4 years ago
)
var (
preSystem uint64
preTotal uint64
limit float64
4 years ago
cores uint64
initOnce sync.Once
4 years ago
)
// if /proc not present, ignore the cpu calculation, like wsl linux
func initialize() {
cpus, err := effectiveCpus()
if err != nil {
logx.Error(err)
return
}
4 years ago
cores = uint64(cpus)
limit = float64(cpus)
quota, err := cpuQuota()
if err == nil && quota > 0 {
if quota < limit {
limit = quota
4 years ago
}
}
preSystem, err = systemCpuUsage()
if err != nil {
logx.Error(err)
return
}
4 years ago
preTotal, err = cpuUsage()
if err != nil {
logx.Error(err)
return
}
4 years ago
}
// RefreshCpu refreshes cpu usage and returns.
4 years ago
func RefreshCpu() uint64 {
initOnce.Do(initialize)
total, err := cpuUsage()
4 years ago
if err != nil {
return 0
}
4 years ago
system, err := systemCpuUsage()
if err != nil {
return 0
}
var usage uint64
cpuDelta := total - preTotal
systemDelta := system - preSystem
if cpuDelta > 0 && systemDelta > 0 {
usage = uint64(float64(cpuDelta*cores*cpuMax) / (float64(systemDelta) * limit))
if usage > cpuMax {
usage = cpuMax
}
4 years ago
}
preSystem = system
preTotal = total
return usage
}
func cpuQuota() (float64, error) {
4 years ago
cg, err := currentCgroup()
if err != nil {
return 0, err
}
return cg.cpuQuota()
4 years ago
}
func cpuUsage() (uint64, error) {
4 years ago
cg, err := currentCgroup()
if err != nil {
return 0, err
}
return cg.cpuUsage()
4 years ago
}
func effectiveCpus() (int, error) {
4 years ago
cg, err := currentCgroup()
if err != nil {
return 0, err
4 years ago
}
return cg.effectiveCpus()
4 years ago
}
func systemCpuUsage() (uint64, error) {
lines, err := iox.ReadTextLines(statFile, iox.WithoutBlank())
4 years ago
if err != nil {
return 0, err
}
for _, line := range lines {
fields := strings.Fields(line)
if fields[0] == "cpu" {
if len(fields) < cpuFields {
return 0, fmt.Errorf("bad format of cpu stats")
}
var totalClockTicks uint64
for _, i := range fields[1:cpuFields] {
v, err := parseUint(i)
if err != nil {
return 0, err
}
totalClockTicks += v
}
return (totalClockTicks * uint64(time.Second)) / cpuTicks, nil
}
}
return 0, errors.New("bad stats format")
}