Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 48 additions & 2 deletions utils/hwstats/memory_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,25 @@
package hwstats

import (
"bufio"
"fmt"
"os"
"strconv"
"strings"

"github.com/livekit/protocol/logger"
)

const (
memUsagePathV1 = "/sys/fs/cgroup/memory/memory.usage_in_bytes"
memLimitPathV1 = "/sys/fs/cgroup/memory/memory.limit_in_bytes"
memUsagePathV1 = "/sys/fs/cgroup/memory/memory.usage_in_bytes"
memLimitPathV1 = "/sys/fs/cgroup/memory/memory.limit_in_bytes"
memStatPathV1 = "/sys/fs/cgroup/memory/memory.stat"
totalInactiveFileV1 = "total_inactive_file"

memCurrentPathV2 = "/sys/fs/cgroup/memory.current"
memMaxPathV2 = "/sys/fs/cgroup/memory.max"
memStatPathV2 = "/sys/fs/cgroup/memory.stat"
inactiveFileV2 = "inactive_file"
)

type memInfoGetter interface {
Expand Down Expand Up @@ -95,6 +102,10 @@ func (cg *memInfoGetterV1) getMemory() (uint64, uint64, error) {
if err != nil {
return 0, 0, err
}
totalInactiveFile, err := readValueOfKeyFromFile(memStatPathV1, totalInactiveFileV1)
if err == nil && usage > totalInactiveFile {
usage -= totalInactiveFile
}

total, err := readValueFromFile(memLimitPathV1)
if err != nil {
Expand Down Expand Up @@ -131,6 +142,10 @@ func (cg *memInfoGetterV2) getMemory() (uint64, uint64, error) {
if err != nil {
return 0, 0, err
}
inactiveFile, err := readValueOfKeyFromFile(memStatPathV2, inactiveFileV2)
if err == nil && usage > inactiveFile {
usage -= inactiveFile
}

total, err := readValueFromFile(memMaxPathV2)
if err != nil {
Expand All @@ -155,3 +170,34 @@ func readValueFromFile(file string) (uint64, error) {
// Skip the trailing EOL
return strconv.ParseUint(string(b[:len(b)-1]), 10, 64)
}

func readValueOfKeyFromFile(file string, key string) (uint64, error) {
fd, err := os.Open(file)
if err != nil {
return 0, err
}
defer fd.Close()

scanner := bufio.NewScanner(fd)
for scanner.Scan() {
line := scanner.Text()
parts := strings.Split(line, " ")
if len(parts) != 2 {
continue
}

if parts[0] != key {
continue
}

val := strings.TrimSpace(parts[1])
if v, err := strconv.ParseUint(val, 10, 64); err == nil {
return v, nil
}
}
if err := scanner.Err(); err != nil {
return 0, fmt.Errorf("scan error for %s, key: %s: %s", file, key, err)
}

return 0, nil
}
Loading