forked from elastic/gosigar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpuacct.go
112 lines (93 loc) · 2.35 KB
/
cpuacct.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package cgroup
import (
"bufio"
"bytes"
"io/ioutil"
"os"
"path/filepath"
"time"
"github.com/elastic/gosigar/sys/linux"
)
var clockTicks = uint64(linux.GetClockTicks())
// CPUAccountingSubsystem contains metrics from the "cpuacct" subsystem.
type CPUAccountingSubsystem struct {
Metadata
TotalNanos uint64 `json:"total_nanos"`
UsagePerCPU []uint64 `json:"usage_percpu_nanos"`
// CPU time statistics for tasks in this cgroup.
Stats CPUAccountingStats `json:"stats,omitempty"`
}
// CPUAccountingStats contains the stats reported from the cpuacct subsystem.
type CPUAccountingStats struct {
UserNanos uint64 `json:"user_nanos"`
SystemNanos uint64 `json:"system_nanos"`
}
// get reads metrics from the "cpuacct" subsystem. path is the filepath to the
// cgroup hierarchy to read.
func (cpuacct *CPUAccountingSubsystem) get(path string) error {
if err := cpuacctStat(path, cpuacct); err != nil {
return err
}
if err := cpuacctUsage(path, cpuacct); err != nil {
return err
}
if err := cpuacctUsagePerCPU(path, cpuacct); err != nil {
return err
}
return nil
}
func cpuacctStat(path string, cpuacct *CPUAccountingSubsystem) error {
f, err := os.Open(filepath.Join(path, "cpuacct.stat"))
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
t, v, err := parseCgroupParamKeyValue(sc.Text())
if err != nil {
return err
}
switch t {
case "user":
cpuacct.Stats.UserNanos = convertJiffiesToNanos(v)
case "system":
cpuacct.Stats.SystemNanos = convertJiffiesToNanos(v)
}
}
return sc.Err()
}
func cpuacctUsage(path string, cpuacct *CPUAccountingSubsystem) error {
var err error
cpuacct.TotalNanos, err = parseUintFromFile(path, "cpuacct.usage")
if err != nil {
return err
}
return nil
}
func cpuacctUsagePerCPU(path string, cpuacct *CPUAccountingSubsystem) error {
contents, err := ioutil.ReadFile(filepath.Join(path, "cpuacct.usage_percpu"))
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
var values []uint64
usages := bytes.Fields(contents)
for _, usage := range usages {
value, err := parseUint(usage)
if err != nil {
return err
}
values = append(values, value)
}
cpuacct.UsagePerCPU = values
return nil
}
func convertJiffiesToNanos(j uint64) uint64 {
return (j * uint64(time.Second)) / clockTicks
}