2020-08-11 21:54:13 +02:00
|
|
|
package cgroup
|
|
|
|
|
|
|
|
import (
|
2021-02-08 14:46:22 +01:00
|
|
|
"fmt"
|
2022-08-21 22:51:13 +02:00
|
|
|
"os"
|
2021-02-08 14:49:02 +01:00
|
|
|
"path"
|
2020-08-11 21:54:13 +02:00
|
|
|
"strconv"
|
2021-02-08 14:46:22 +01:00
|
|
|
"strings"
|
2020-08-11 21:54:13 +02:00
|
|
|
)
|
|
|
|
|
2021-02-08 14:49:02 +01:00
|
|
|
func getStatGeneric(statName, sysfsPrefix, cgroupPath, cgroupGrepLine string) (int64, error) {
|
|
|
|
data, err := getFileContents(statName, sysfsPrefix, cgroupPath, cgroupGrepLine)
|
2021-02-08 14:46:22 +01:00
|
|
|
if err != nil {
|
2021-02-08 14:49:02 +01:00
|
|
|
return 0, err
|
2021-02-08 14:46:22 +01:00
|
|
|
}
|
2021-05-13 08:26:20 +02:00
|
|
|
data = strings.TrimSpace(data)
|
2021-02-08 14:49:02 +01:00
|
|
|
n, err := strconv.ParseInt(data, 10, 64)
|
|
|
|
if err != nil {
|
2021-05-13 08:26:20 +02:00
|
|
|
return 0, fmt.Errorf("cannot parse %q: %w", cgroupPath, err)
|
2021-02-08 14:46:22 +01:00
|
|
|
}
|
2021-02-08 14:49:02 +01:00
|
|
|
return n, nil
|
2021-02-08 14:46:22 +01:00
|
|
|
}
|
|
|
|
|
2021-02-08 14:49:02 +01:00
|
|
|
func getFileContents(statName, sysfsPrefix, cgroupPath, cgroupGrepLine string) (string, error) {
|
|
|
|
filepath := path.Join(sysfsPrefix, statName)
|
2022-08-21 22:51:13 +02:00
|
|
|
data, err := os.ReadFile(filepath)
|
2020-09-03 23:04:08 +02:00
|
|
|
if err == nil {
|
2021-02-08 14:49:02 +01:00
|
|
|
return string(data), nil
|
|
|
|
}
|
2022-08-21 22:51:13 +02:00
|
|
|
cgroupData, err := os.ReadFile(cgroupPath)
|
2021-02-08 14:49:02 +01:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
subPath, err := grepFirstMatch(string(cgroupData), cgroupGrepLine, 2, ":")
|
|
|
|
if err != nil {
|
2021-05-13 08:26:20 +02:00
|
|
|
return "", fmt.Errorf("cannot find cgroup path for %q in %q: %w", cgroupGrepLine, cgroupPath, err)
|
2021-02-08 14:49:02 +01:00
|
|
|
}
|
|
|
|
filepath = path.Join(sysfsPrefix, subPath, statName)
|
2022-08-21 22:51:13 +02:00
|
|
|
data, err = os.ReadFile(filepath)
|
2021-02-08 14:49:02 +01:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return string(data), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// grepFirstMatch searches match line at data and returns item from it by index with given delimiter.
|
|
|
|
func grepFirstMatch(data string, match string, index int, delimiter string) (string, error) {
|
|
|
|
lines := strings.Split(string(data), "\n")
|
|
|
|
for _, s := range lines {
|
|
|
|
if !strings.Contains(s, match) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
parts := strings.Split(s, delimiter)
|
|
|
|
if index < len(parts) {
|
|
|
|
return strings.TrimSpace(parts[index]), nil
|
|
|
|
}
|
2020-09-03 23:04:08 +02:00
|
|
|
}
|
2021-02-08 14:49:02 +01:00
|
|
|
return "", fmt.Errorf("cannot find %q in %q", match, data)
|
2020-08-11 21:54:13 +02:00
|
|
|
}
|