forked from livekit/protocol
/
cpu.go
77 lines (61 loc) · 1.45 KB
/
cpu.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package utils
import (
"runtime"
"time"
"github.com/abdulhaseeb08/protocol/logger"
"github.com/frostbyte73/go-throttle"
"go.uber.org/atomic"
)
// This object returns cgroup quota aware cpu stats. On other systems than Linux,
// it falls back to full system stats
type CPUStats struct {
idleCPUs atomic.Float64
platform *platformCPUMonitor
updateCallback func(idle float64)
warningThrottle func(func())
closeChan chan struct{}
}
func NewCPUStats(updateCallback func(idle float64)) (*CPUStats, error) {
p, err := newPlatformCPUMonitor()
if err != nil {
return nil, err
}
c := &CPUStats{
platform: p,
warningThrottle: throttle.New(time.Minute),
updateCallback: updateCallback,
closeChan: make(chan struct{}),
}
go c.monitorCPULoad()
return c, nil
}
func (c *CPUStats) GetCPUIdle() float64 {
return c.idleCPUs.Load()
}
func (c *CPUStats) Stop() {
close(c.closeChan)
}
func (c *CPUStats) monitorCPULoad() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-c.closeChan:
return
case <-ticker.C:
idle, err := c.platform.getCPUIdle()
if err != nil {
logger.Errorw("failed retrieving CPU idle", err)
continue
}
c.idleCPUs.Store(idle)
idleRatio := idle / float64(runtime.NumCPU())
if idleRatio < 0.1 {
c.warningThrottle(func() { logger.Infow("high cpu load", "load", 1-idleRatio) })
}
if c.updateCallback != nil {
c.updateCallback(idle)
}
}
}
}