Path: blob/main/components/common-go/cgroups/v2/cpu.go
2500 views
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package cgroups_v256import (7"math"8"os"9"path/filepath"10"strconv"11"strings"1213"github.com/gitpod-io/gitpod/common-go/cgroups"14"golang.org/x/xerrors"15)1617const (18StatUsageTotal = "usage_usec"19StatUsageUser = "user_usec"20StatUsageSystem = "system_usec"21)2223type Cpu struct {24path string25}2627func NewCpuControllerWithMount(mountPoint, path string) *Cpu {28fullPath := filepath.Join(mountPoint, path)29return &Cpu{30path: fullPath,31}32}3334func NewCpuController(path string) *Cpu {35return &Cpu{36path: path,37}38}3940// Max return the quota and period in microseconds41func (c *Cpu) Max() (quota uint64, period uint64, err error) {42path := filepath.Join(c.path, "cpu.max")43content, err := os.ReadFile(path)44if err != nil {45return 0, 0, err46}4748values := strings.Split(strings.TrimSpace(string(content)), " ")49if len(values) < 2 {50return 0, 0, xerrors.Errorf("%s has less than 2 values", path)51}5253if values[0] == "max" {54quota = math.MaxUint6455} else {56quota, err = strconv.ParseUint(values[0], 10, 64)57if err != nil {58return 0, 0, err59}60}6162period, err = strconv.ParseUint(values[1], 10, 64)63if err != nil {64return 0, 0, err65}6667return quota, period, nil68}6970// Stat returns cpu statistics (all values are in microseconds)71func (c *Cpu) Stat() (*cgroups.CpuStats, error) {72path := filepath.Join(c.path, "cpu.stat")73statMap, err := cgroups.ReadFlatKeyedFile(path)74if err != nil {75return nil, err76}7778stats := cgroups.CpuStats{79UsageTotal: statMap[StatUsageTotal],80UsageUser: statMap[StatUsageUser],81UsageSystem: statMap[StatUsageSystem],82}8384return &stats, nil85}8687func (c *Cpu) PSI() (cgroups.PSI, error) {88path := filepath.Join(c.path, "cpu.pressure")89return cgroups.ReadPSIValue(path)90}919293