shirou / gopsutil

psutil for golang
Other
10.47k stars 1.58k forks source link

Process createTime calculation for linux lxc guest is incorrect #1562

Open drubinMeta opened 9 months ago

drubinMeta commented 9 months ago

Describe the bug createTime for processes running in lxc utilize in calculation container boot time, based on uptime (gopsutil/internal/common /common_linux.go:78) and /proc/[pid]/stats field 22 that represent process start time that based on host boot time (gopsutil/process/process_linux.go:1074) As a result, when host boot time considerably differ from lxc boot time, createTime of lxc processes has future value.

To Reproduce

On long running host, start lxc container and query processes createTime

Expected behavior Possible fix, in case of VirtualizationSystem is lxc and VirtualizationRole is guest, use host boot time from /proc/stat in conjunction with
/proc/[pid]/stats field 22 (gopsutil/process/process_linux.go:1074)

Environment: Ubuntu 20.04.6 LTS Linux 5.15.30-051530-generic Lxc 4.0.9

shirou commented 8 months ago

Sorry, I don't have a time to dig it deep in this weekend, but is this problem related to this issue? If so, this only happened on LXC 2.0.7, but it still exists on 4.0.9?

drubinMeta commented 8 months ago

The issue is different, both /proc/stats btime and /proc/[pid]/stats represent host time But the calculation of process create time based on container boot time in process_linux.go. This is actually causes the mix up between virtualized boot time and non-virtualized start time

shirou commented 8 months ago

Let me confirm my understanding. Please point out if I'm wrong.

LXC guest changed to see /proc/uptime at #390. Current behavior works on host.BootTime(). However, it goes wrong when using boottime to calculate Process.CreateTime().

What we want as the Process.CreateTime() is the ctime in /process/stat minus the "BootTime".

Where "BootTime" is definitely the Host BootTime in the case of host. However, in the case of lxc container guest, what we want is not the Host BootTime(== /proc/uptime), but LXC Container BootTime (== the btime in /proc/stat)

If my understanding is correct, then I would expect the same thing to happen with Docker containers.

drubinMeta commented 8 months ago

Not quite: lxc guest uses /proc/uptime. But it shows container uptime However /proc/[pid]/stat field 22 based on host boot time So for calculation of create time in lxc, /proc/stats btime field should be used