mirror of
https://github.com/opencontainers/runc.git
synced 2026-07-11 06:03:57 +08:00
aac4d1f5c3
2. Fix wrapping the error to not have the value as it's already part of the error returned from ParseUint. 3. Fix/improve doc. Signed-off-by: Kir Kolyshkin <kolyshkin@gmail.com>
85 lines
2.2 KiB
Go
85 lines
2.2 KiB
Go
// +build linux
|
|
|
|
package fscommon
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"math"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
var (
|
|
ErrNotValidFormat = errors.New("line is not a valid key value format")
|
|
)
|
|
|
|
// Saturates negative values at zero and returns a uint64.
|
|
// Due to kernel bugs, some of the memory cgroup stats can be negative.
|
|
func ParseUint(s string, base, bitSize int) (uint64, error) {
|
|
value, err := strconv.ParseUint(s, base, bitSize)
|
|
if err != nil {
|
|
intValue, intErr := strconv.ParseInt(s, base, bitSize)
|
|
// 1. Handle negative values greater than MinInt64 (and)
|
|
// 2. Handle negative values lesser than MinInt64
|
|
if intErr == nil && intValue < 0 {
|
|
return 0, nil
|
|
} else if intErr != nil && intErr.(*strconv.NumError).Err == strconv.ErrRange && intValue < 0 {
|
|
return 0, nil
|
|
}
|
|
|
|
return value, err
|
|
}
|
|
|
|
return value, nil
|
|
}
|
|
|
|
// GetCgroupParamKeyValue parses a space-separated "name value" kind of cgroup
|
|
// parameter and returns its components. For example, "io_service_bytes 1234"
|
|
// will return as "io_service_bytes", 1234.
|
|
func GetCgroupParamKeyValue(t string) (string, uint64, error) {
|
|
parts := strings.Fields(t)
|
|
switch len(parts) {
|
|
case 2:
|
|
value, err := ParseUint(parts[1], 10, 64)
|
|
if err != nil {
|
|
return "", 0, fmt.Errorf("unable to convert to uint64: %v", err)
|
|
}
|
|
|
|
return parts[0], value, nil
|
|
default:
|
|
return "", 0, ErrNotValidFormat
|
|
}
|
|
}
|
|
|
|
// Gets a single uint64 value from the specified cgroup file.
|
|
func GetCgroupParamUint(cgroupPath, cgroupFile string) (uint64, error) {
|
|
fileName := filepath.Join(cgroupPath, cgroupFile)
|
|
contents, err := ioutil.ReadFile(fileName)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
trimmed := strings.TrimSpace(string(contents))
|
|
if trimmed == "max" {
|
|
return math.MaxUint64, nil
|
|
}
|
|
|
|
res, err := ParseUint(trimmed, 10, 64)
|
|
if err != nil {
|
|
return res, fmt.Errorf("unable to parse %q as a uint from Cgroup file %q", string(contents), fileName)
|
|
}
|
|
return res, nil
|
|
}
|
|
|
|
// Gets a string value from the specified cgroup file
|
|
func GetCgroupParamString(cgroupPath, cgroupFile string) (string, error) {
|
|
contents, err := ioutil.ReadFile(filepath.Join(cgroupPath, cgroupFile))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
return strings.TrimSpace(string(contents)), nil
|
|
}
|