1 # Simple wrapper arround cgroups so we don't have to worry the type of
2 # virtualization the sliver runs on (lxc, qemu/kvm, etc.) managed by libvirt
4 # Xavi Leon <xleon@ac.upc.edu>
9 from functools import reduce
11 # Base dir for libvirt
12 BASE_DIR = '/sys/fs/cgroup'
14 def get_cgroup_paths(subsystem="cpuset"):
17 os.path.join(BASE_DIR, subsystem, 'libvirt', 'lxc'),
19 os.path.join(BASE_DIR, subsystem ),
21 os.path.join(BASE_DIR, subsystem, 'machine.slice'),
22 # as observed on f16 libvirt 1.2.1
23 os.path.join(BASE_DIR, subsystem, 'machine'),
25 # try several locations and return all the results
26 # get_cgroup_path will sort it out
28 # just return all the subdirs in the listed bases
31 for subsystem_base in subsystem_bases if os.path.isdir(subsystem_base)
32 # in each base search the immediate sons that are also dirs
33 for subdir in [ os.path.join(subsystem_base, f) for f in os.listdir(subsystem_base) ]
34 if os.path.isdir(subdir) ]
36 def get_cgroup_path(name, subsystem="cpuset"):
38 Returns the base path for the cgroup with a specific name or None.
40 result = reduce(lambda a, b: b if name in os.path.basename(b) else a,
41 get_cgroup_paths(subsystem), None)
44 name = name + ".libvirt-lxc"
45 result = reduce(lambda a, b: b if name in os.path.basename(b) else a,
46 get_cgroup_paths(subsystem), None)
54 """ Returns the list of cgroups active at this moment on the node """
55 return list(map(os.path.basename, get_cgroup_paths()))
57 def write(name, key, value, subsystem="cpuset"):
58 """ Writes a value to the file key with the cgroup with name """
59 base_path = get_cgroup_path(name, subsystem)
60 with open(os.path.join(base_path, key), 'w') as f:
62 logger.verbose("cgroups.write: overwrote {}".format(base_path))
64 def append(name, key, value, subsystem="cpuset"):
65 """ Appends a value to the file key with the cgroup with name """
66 base_path = get_cgroup_path(name, subsystem)
67 with open(os.path.join(base_path, key), 'a') as f:
69 logger.verbose("cgroups.append: appended {}".format(base_path))
71 if __name__ == '__main__':
73 # goes with the system tests
76 subsystems = 'blkio cpu cpu,cpuacct cpuacct cpuset devices freezer memory net_cls perf_event systemd'.split()
78 for subsystem in subsystems:
79 print('get_cgroup_path({}, {}) = {}'.\
80 format(name, subsystem, get_cgroup_path(name, subsystem)))
82 # print 'get_cgroup_paths = {}'.format(get_cgroup_paths(subsystem))