-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoroutine_cpu_load.go
64 lines (51 loc) · 1.42 KB
/
goroutine_cpu_load.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
// Go routine to capture CPU utilization for docker/kubernetes container
// cat imitates Unix cat
func cat(stream io.Reader) ([]byte, error) {
data, err := ioutil.ReadAll(stream)
if err != nil {
panic(err)
return nil, err
}
return data, nil
}
// int64frombytes converts bytes[] to int64
func int64frombytes(bytes []byte) int64 {
s:= string(bytes[:len(bytes)-1]) // len-1 is needed to remove /n
num, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return int64(num)
}
//readcpudata reads container cpu stats from container files
func readCPUStats() int64 {
// filepath
filepath := "/sys/fs/cgroup/cpu/cpuacct.usage"
// open and read stats from file
data, err := os.Open(filepath)
if err != nil {
panic(err)
}
output, _ := cat(data) // calls cat func to immitate Unix cat
CPUVal := int64frombytes(output)
defer func() {
err := data.Close()
if err != nil {
panic(err)
}
}()
return CPUVal
}
// Goroutine CPULoadCalc computes CPU utilization over 5 seconds
func CPULoadCalc() {
// infinte loop for goroutine
for {
previous := readCPUStats()
start := time.Now().UnixNano()
time.Sleep(5 * time.Second)
after := readCPUStats()
stop := time.Now().UnixNano()
cpuLoad := float64(after-prev) / float64(stop-start)
fmt.Println("CPU load percentage", cpuLoad * 100)
}
}