examples: Add example to traverse cgroup v2 hierarchy

Add simple example to traverse cgroup v2 hierarchy.

It can be run w/o arguments and in this case root cgroup will be used:

  # python36 -m drgn examples/linux/cgroup.py | wc -l
  1081
  # python36 -m drgn examples/linux/cgroup.py | shuf -n 3
  /system.slice/nfs-idmapd.service
  /user.slice/user-0.slice/user@0.service/dev-hugepages.mount
  /system.slice/crond.service

Or a path in cgroup v2 filesystem can be specified to limit the
traversal by this path:

  # python36 -m drgn examples/linux/cgroup.py /sys/fs/cgroup/www.slice
  /www.slice
  /www.slice/hack.service
  /www.slice/flow.service

Signed-off-by: Andrey Ignatov <rdna@fb.com>
This commit is contained in:
Andrey Ignatov 2020-01-03 17:53:51 -08:00 committed by Omar Sandoval
parent 820d25ae29
commit 36cedcdc6f

40
examples/linux/cgroup.py Executable file
View File

@ -0,0 +1,40 @@
"""List the paths of all descendants of a cgroup v2"""
import os
import sys
from contextlib import contextmanager
from drgn import cast
from drgn.helpers.linux import (
cgroup_path,
css_for_each_descendant_pre,
fget,
find_task,
)
@contextmanager
def open_dir(*args, **kwds):
# Built-in open() context manager can't deal with directories.
fd = os.open(*args, **kwds)
try:
yield fd
finally:
os.close(fd)
def get_cgroup():
if len(sys.argv) == 1:
return prog["cgrp_dfl_root"].cgrp
task = find_task(prog, os.getpid())
with open_dir(sys.argv[1], os.O_RDONLY) as fd:
file_ = fget(task, fd)
kn = cast("struct kernfs_node *", file_.f_path.dentry.d_inode.i_private)
return cast("struct cgroup *", kn.priv)
css = get_cgroup().self.address_of_()
for pos in css_for_each_descendant_pre(css):
print(cgroup_path(pos.cgroup).decode())