#!/bin/bash

CONFIG_DIR="/etc/vstorage"
VSTORAGE_CGRP_CPU_ROOT=/sys/fs/cgroup/cpu,cpuacct/vstorage.slice
LOG_FILE=/dev/null

load_config() 
{
	# load cluster config, it can use environment variables
	[ -f "${CONFIG_DIR}/service.config" ] && source "${CONFIG_DIR}/service.config"
	return 0
}

setup_rt_scheduling()
{
	local NCPU=$(nproc)
	[ "$NO_SCHED_CPUS" = "" ] && NO_SCHED_CPUS="2"

	if [ "$NCPU" -gt "$NO_SCHED_CPUS" ] ; then
		# configure real time scheduling quota if necessary
		if [ "$RT_RUNTIME" != "" ] ; then
			RT_ROOT_QUOTA=$(cat "$VSTORAGE_CGRP_CPU_ROOT/cpu.rt_runtime_us" 2>>$LOG_FILE)
			if [ "$RT_ROOT_QUOTA" = "0" ] ; then
				# Set vstorage root slice quota if its not yet set
				# Note that in typical production installation it should be managed elsewhere
				echo "$RT_RUNTIME" > "$VSTORAGE_CGRP_CPU_ROOT/cpu.rt_runtime_us" 2>>$LOG_FILE
			elif [ "$RT_ROOT_QUOTA" -lt "$RT_RUNTIME" ] ; then
				echo "current root rt_runtime_us quota $RT_ROOT_QUOTA is less than requested $RT_RUNTIME, increasing"
				echo "$RT_RUNTIME" > "$VSTORAGE_CGRP_CPU_ROOT/cpu.rt_runtime_us" 2>>$LOG_FILE
			fi
			echo "$RT_RUNTIME" > "$VSTORAGE_CGRP_CPU_ROOT/vstorage-services.slice/cpu.rt_runtime_us" 2>>$LOG_FILE
		fi
	fi
}

handle_service()
{
	load_config
	setup_rt_scheduling
}

handle_service "$@"
