An efficient way to get the number of file handles opened by a process in Go?
I have a monitoring agent called scollector that uses more CPU on our load balancer. Perf says CPUs are mostly due to __d_lookup
. One of the things I monitor is the number of open file handles – I do this with the following code:
fds, e := ioutil. ReadDir("/proc/" + pid + "/fd")
if e != nil {
w.Remove(pid)
continue
}
...
Add(md, "linux.proc.num_fds", len(fds), tags, metadata. Gauge, metadata. Files, descLinuxProcFd)
When I trace a process, I see that it calls lstat
on every file in the /fd
directory (which would be a lot for our event load balancer (at least 500,000 fds) – so I’m assuming this is the source of the process’s high dentry cache cpu usage.
Does anyone have any suggestions for a better way to do this?
Solution
ioutil. The problem with Readdir
is that it executes file. Readdir
, which indicates that it performs lstat
on each file.
It seems that Readdirnames
does not do this, only returns the name. Since you only need to count, that’s enough.