From c49b9aebd8c27b06cb3a7742a9daf2adfc20138c Mon Sep 17 00:00:00 2001 From: Kamalesh Babulal Date: Fri, 10 Feb 2023 06:39:11 +0000 Subject: [PATCH] tests/systemd - Add more helpers for cgroup delegation Add more helpers to work with systemd cgroup delegation, this patch adds: - remove_scope_slice_conf() to remove the cgconfig file created and remove the scope cgroup and slice cgroups. - write_config_with_pid() to write a cgconfig file with the systemd configurations. Signed-off-by: Kamalesh Babulal Signed-off-by: Tom Hromatka --- tests/ftests/systemd.py | 47 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/tests/ftests/systemd.py b/tests/ftests/systemd.py index e2388c9d..826f3c40 100644 --- a/tests/ftests/systemd.py +++ b/tests/ftests/systemd.py @@ -7,6 +7,8 @@ # from run import Run, RunError +from cgroup import Cgroup +import os class Systemd(object): @@ -27,3 +29,48 @@ class Systemd(object): # until we figure out something better :( return True raise re + + # This function creates a task and writes its pid into systemd + # configuration file, that gets passed to the cgconfigparser tool to + # create systemd slice/scope. + @staticmethod + def write_config_with_pid(config, config_fname, _slice, scope, setdefault="yes"): + pid = config.process.create_process(config) + config_file = '''systemd {{ + slice = {}; + scope = {}; + setdefault = {}; + pid = {}; + }}'''.format(_slice, scope, setdefault, pid) + + f = open(config_fname, 'w') + f.write(config_file) + f.close() + + return pid + + # Stopping the systemd scope, will kill the default task in the scope + # and remove scope cgroup but will not remove the slice, that needs to + # removed manually. + @staticmethod + def remove_scope_slice_conf(config, _slice, scope, controller, config_fname=None): + if config_fname: + os.remove(config_fname) + + try: + if config.args.container: + config.container.run(['systemctl', 'stop', '{}'.format(scope)], + shell_bool=True) + else: + Run.run(['sudo', 'systemctl', 'stop', '{}'.format(scope)], shell_bool=True) + except RunError as re: + if 'scope not loaded' in re.stderr: + raise re + + # In case the error occurs before the creation of slice/scope and + # we may very well be on the teardown path, ignore the exception + try: + Cgroup.delete(config, controller, cgname=_slice, ignore_systemd=True) + except RunError as re: + if 'No such file or directory' not in re.stderr: + raise re -- 2.47.2