Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/common-go/cgroups/v2/cpu.go
2500 views
1
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package cgroups_v2
6
7
import (
8
"math"
9
"os"
10
"path/filepath"
11
"strconv"
12
"strings"
13
14
"github.com/gitpod-io/gitpod/common-go/cgroups"
15
"golang.org/x/xerrors"
16
)
17
18
const (
19
StatUsageTotal = "usage_usec"
20
StatUsageUser = "user_usec"
21
StatUsageSystem = "system_usec"
22
)
23
24
type Cpu struct {
25
path string
26
}
27
28
func NewCpuControllerWithMount(mountPoint, path string) *Cpu {
29
fullPath := filepath.Join(mountPoint, path)
30
return &Cpu{
31
path: fullPath,
32
}
33
}
34
35
func NewCpuController(path string) *Cpu {
36
return &Cpu{
37
path: path,
38
}
39
}
40
41
// Max return the quota and period in microseconds
42
func (c *Cpu) Max() (quota uint64, period uint64, err error) {
43
path := filepath.Join(c.path, "cpu.max")
44
content, err := os.ReadFile(path)
45
if err != nil {
46
return 0, 0, err
47
}
48
49
values := strings.Split(strings.TrimSpace(string(content)), " ")
50
if len(values) < 2 {
51
return 0, 0, xerrors.Errorf("%s has less than 2 values", path)
52
}
53
54
if values[0] == "max" {
55
quota = math.MaxUint64
56
} else {
57
quota, err = strconv.ParseUint(values[0], 10, 64)
58
if err != nil {
59
return 0, 0, err
60
}
61
}
62
63
period, err = strconv.ParseUint(values[1], 10, 64)
64
if err != nil {
65
return 0, 0, err
66
}
67
68
return quota, period, nil
69
}
70
71
// Stat returns cpu statistics (all values are in microseconds)
72
func (c *Cpu) Stat() (*cgroups.CpuStats, error) {
73
path := filepath.Join(c.path, "cpu.stat")
74
statMap, err := cgroups.ReadFlatKeyedFile(path)
75
if err != nil {
76
return nil, err
77
}
78
79
stats := cgroups.CpuStats{
80
UsageTotal: statMap[StatUsageTotal],
81
UsageUser: statMap[StatUsageUser],
82
UsageSystem: statMap[StatUsageSystem],
83
}
84
85
return &stats, nil
86
}
87
88
func (c *Cpu) PSI() (cgroups.PSI, error) {
89
path := filepath.Join(c.path, "cpu.pressure")
90
return cgroups.ReadPSIValue(path)
91
}
92
93