Skip to content

Commit

Permalink
fix: nerdctl stats on a container without a memory limit returns host…
Browse files Browse the repository at this point in the history
… memory limit

Signed-off-by: Cezar Rata <[email protected]>

Signed-off-by: Cezar Rata <[email protected]>

Signed-off-by: Cezar Rata <[email protected]>

Signed-off-by: Cezar Rata <[email protected]>
  • Loading branch information
cezar-r committed Sep 19, 2024
1 parent da6b454 commit 87686d0
Showing 1 changed file with 36 additions and 4 deletions.
40 changes: 36 additions & 4 deletions pkg/statsutil/stats_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@
package statsutil

import (
"bufio"
"os"
"strconv"
"strings"
"time"

"github.com/vishvananda/netlink"
Expand All @@ -26,11 +30,10 @@ import (
)

func SetCgroupStatsFields(previousStats *ContainerStats, data *v1.Metrics, links []netlink.Link) (StatsEntry, error) {

cpuPercent := calculateCgroupCPUPercent(previousStats, data)
blkRead, blkWrite := calculateCgroupBlockIO(data)
mem := calculateCgroupMemUsage(data)
memLimit := float64(data.Memory.Usage.Limit)
memLimit := getCgroupMemLimit(float64(data.Memory.Usage.Limit))
memPercent := calculateMemPercent(memLimit, mem)
pidsStatsCurrent := data.Pids.Current
netRx, netTx := calculateCgroupNetwork(links)
Expand All @@ -50,11 +53,10 @@ func SetCgroupStatsFields(previousStats *ContainerStats, data *v1.Metrics, links
}

func SetCgroup2StatsFields(previousStats *ContainerStats, metrics *v2.Metrics, links []netlink.Link) (StatsEntry, error) {

cpuPercent := calculateCgroup2CPUPercent(previousStats, metrics)
blkRead, blkWrite := calculateCgroup2IO(metrics)
mem := calculateCgroup2MemUsage(metrics)
memLimit := float64(metrics.Memory.UsageLimit)
memLimit := getCgroupMemLimit(float64(metrics.Memory.UsageLimit))
memPercent := calculateMemPercent(memLimit, mem)
pidsStatsCurrent := metrics.Pids.Current
netRx, netTx := calculateCgroupNetwork(links)
Expand All @@ -73,6 +75,36 @@ func SetCgroup2StatsFields(previousStats *ContainerStats, metrics *v2.Metrics, l

}

func getCgroupMemLimit(memLimit float64) float64 {
if memLimit == float64(^uint64(0)) {
return getHostMemLimit()
}
return memLimit
}

func getHostMemLimit() float64 {
file, err := os.Open("/proc/meminfo")
if err != nil {
return float64(^uint64(0))
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
if strings.HasPrefix(scanner.Text(), "MemTotal:") {
fields := strings.Fields(scanner.Text())
if len(fields) >= 2 {
memKb, err := strconv.ParseUint(fields[1], 10, 64)
if err == nil {
return float64(memKb * 1024) // kB to bytes
}
}
break
}
}
return float64(^uint64(0))
}

func calculateCgroupCPUPercent(previousStats *ContainerStats, metrics *v1.Metrics) float64 {
var (
cpuPercent = 0.0
Expand Down

0 comments on commit 87686d0

Please sign in to comment.