#!/bin/bash

CGROUP_ROOT="/cgroup/blkio/libvirt/qemu"
DEFAULT_DEVICE="8:16"
DEFAULT_W_IOPS=200
DEFAULT_R_IOPS=200

set_iops_cond() {
	local uuid=$1; shift
	local type=$1; shift
	local iops=$1; shift

	c_iops=$(cat $CGROUP_ROOT/$uuid/blkio.throttle.${type}_iops_device | awk '{print $2}')

	if [[ "x$c_iops" = x ]]; then
		echo "$uuid $type iops empty, set"
		echo "$DEFAULT_DEVICE $iops" > $CGROUP_ROOT/$uuid/blkio.throttle.${type}_iops_device
	else
		echo "$uuid $type iops not empty, skip"
	fi
}

show_current_iops() {
	local uuid=$1; shift

	r_iops=$(cat $CGROUP_ROOT/$uuid/blkio.throttle.read_iops_device | awk '{print $2}')
	w_iops=$(cat $CGROUP_ROOT/$uuid/blkio.throttle.write_iops_device | awk '{print $2}')

	echo "$uuid W_IOPS: [$w_iops] R_IOPS: [$r_iops]"
}

if [[ ! -d $CGROUP_ROOT ]]; then
	echo "cgroup $CGROUP_ROOT does not exists" >&2
	exit 1
fi

for uuid in `virsh list | grep -v vnat | grep -v -E '^[-]' | grep -v Id | awk '{print $2}'`
do
	show_current_iops $uuid

	set_iops_cond $uuid "write" $DEFAULT_W_IOPS
	set_iops_cond $uuid "read" $DEFAULT_R_IOPS

	show_current_iops $uuid
	echo
	echo
done
