summaryrefslogtreecommitdiff
path: root/libpod/stats.go
diff options
context:
space:
mode:
authorPaul Holzinger <pholzing@redhat.com>2022-03-22 17:10:43 +0100
committerPaul Holzinger <pholzing@redhat.com>2022-03-22 17:43:49 +0100
commit0edb3ddd39ec5ed80cf580148b119d0528875fa9 (patch)
treede2279d53b74ed77fe292e1c8afe07fa658f3f00 /libpod/stats.go
parent02aae4a65856305f657bc3684ad1ac2a47fbc30e (diff)
downloadpodman-0edb3ddd39ec5ed80cf580148b119d0528875fa9.tar.gz
podman-0edb3ddd39ec5ed80cf580148b119d0528875fa9.tar.bz2
podman-0edb3ddd39ec5ed80cf580148b119d0528875fa9.zip
podman stats: calc CPU percentage correctly
When you run podman stats, the first interval always shows the wrong cpu usage. To calculate cpu percentage we get the cpu time from the cgroup and compare this against the system time between two stats. Since the first time we do not have a previous stats an empty struct is used instead. Thus we do not use the actual running time of the container but the current unix timestamp (time since Jan 1 1970). To fix this we make sure that the previous stats time is set to the container start time, when it is empty. [NO NEW TESTS NEEDED] No idea how I could create a test which would have a predictable cpu usage. See the linked bugzilla for a reproducer. Fixes https://bugzilla.redhat.com/show_bug.cgi?id=2066145 Signed-off-by: Paul Holzinger <pholzing@redhat.com>
Diffstat (limited to 'libpod/stats.go')
-rw-r--r--libpod/stats.go12
1 files changed, 11 insertions, 1 deletions
diff --git a/libpod/stats.go b/libpod/stats.go
index b5d39240d..988aa4b5c 100644
--- a/libpod/stats.go
+++ b/libpod/stats.go
@@ -14,7 +14,9 @@ import (
"github.com/pkg/errors"
)
-// GetContainerStats gets the running stats for a given container
+// GetContainerStats gets the running stats for a given container.
+// The previousStats is used to correctly calculate cpu percentages. You
+// should pass nil if there is no previous stat for this container.
func (c *Container) GetContainerStats(previousStats *define.ContainerStats) (*define.ContainerStats, error) {
stats := new(define.ContainerStats)
stats.ContainerID = c.ID()
@@ -36,6 +38,14 @@ func (c *Container) GetContainerStats(previousStats *define.ContainerStats) (*de
return stats, define.ErrCtrStateInvalid
}
+ if previousStats == nil {
+ previousStats = &define.ContainerStats{
+ // if we have no prev stats use the container start time as prev time
+ // otherwise we cannot correctly calculate the CPU percentage
+ SystemNano: uint64(c.state.StartedTime.UnixNano()),
+ }
+ }
+
cgroupPath, err := c.cGroupPath()
if err != nil {
return nil, err