#!/bin/bash
#
# Author: Songtang Liu <liusongtang@bytedance.com>
#
# This script moves tasks around different cgroups to create pressure on cgroup_threadgroup_rwsem.
# Run this script as root with two params representing two cgroup names, with each cgroup having
# a 16cpu quota so the VM has to have more than 32 vCPUs. Run it like this:
# #./cg.sh s1 s2

./test.sh $1 &
t1=$!

./test.sh $2 &
t2=$!

cleanup() {
	echo "Cleaning up..."
	kill -s SIGINT $t1 $t2 $sleep_test $cat_test
	killall test.sh
	pids=$(pgrep stress-ng)
	kill $pids
	killall cg.sh
	exit
}
trap cleanup SIGINT

CG=/sys/fs/cgroup
CG1=${CG}/$1
CG2=${CG}/$2

# move tasks around cgroups
while true; do
	list1=$(cat ${CG1}/cgroup.procs)
	list2=$(cat ${CG2}/cgroup.procs)
	for pid in $list1; do
		# echo $pid  ${CGROUP_PATH}/cgroup.procs ${CGROUP_ROOT}/cgroup.procs
		echo "move $pid to CG2"
		echo $pid > ${CG2}/cgroup.procs 2>&1
	done

	for pid in $list2; do
		# echo $pid  ${CGROUP_PATH}/cgroup.procs ${CGROUP_ROOT}/cgroup.procs
		echo "move $pid to CG1"
		echo $pid > ${CG1}/cgroup.procs 2>&1
	done
done
