1
0
mirror of https://github.com/go-kratos/kratos.git synced 2025-01-24 03:46:37 +02:00
kratos/pkg/stat/sys/cpu/cpu.go

68 lines
1010 B
Go
Raw Normal View History

2019-02-01 15:57:43 +08:00
package cpu
import (
"fmt"
"sync/atomic"
"time"
)
2019-06-17 15:43:35 +08:00
const (
interval time.Duration = time.Millisecond * 500
)
2019-02-01 15:57:43 +08:00
2019-06-17 15:43:35 +08:00
var (
stats CPU
usage uint64
2019-02-01 15:57:43 +08:00
)
2019-06-17 15:43:35 +08:00
type CPU interface {
Usage() (u uint64, e error)
Info() Info
}
2019-02-01 15:57:43 +08:00
2019-06-17 15:43:35 +08:00
func init() {
var (
err error
)
stats, err = newCgroupCPU()
2019-02-01 15:57:43 +08:00
if err != nil {
2019-06-17 15:43:35 +08:00
fmt.Printf("cgroup cpu init failed(%v),switch to psutil cpu\n", err)
stats, err = newPsutilCPU(interval)
if err != nil {
panic(fmt.Sprintf("cgroup cpu init failed!err:=%v", err))
2019-02-01 15:57:43 +08:00
}
}
go func() {
2019-06-17 15:43:35 +08:00
ticker := time.NewTicker(interval)
2019-02-01 15:57:43 +08:00
defer ticker.Stop()
for {
<-ticker.C
2019-06-17 15:43:35 +08:00
u, err := stats.Usage()
if err == nil && u != 0 {
atomic.StoreUint64(&usage, u)
2019-02-01 15:57:43 +08:00
}
}
}()
}
// Stat cpu stat.
type Stat struct {
Usage uint64 // cpu use ratio.
}
// Info cpu info.
type Info struct {
Frequency uint64
Quota float64
}
// ReadStat read cpu stat.
func ReadStat(stat *Stat) {
stat.Usage = atomic.LoadUint64(&usage)
}
// GetInfo get cpu info.
func GetInfo() Info {
2019-06-17 15:43:35 +08:00
return stats.Info()
2019-02-01 15:57:43 +08:00
}