#!/bin/bash
#########################################################################################
#
# Load monitor for RSS feed media downloader.
#
#
# © Copyright 2012 Arto Jääskeläinen <temp001(at)pp.inet.fi>
# Part of Auto DL software package. All rights reserved.
# The program is distributed under the terms of the GNU General Public License
#
#    Auto DL is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Auto DL is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Auto DL.  If not, see <http://www.gnu.org/licenses/>.
#
# V1.0  2013-08-09 Initial version
#
#########################################################################################

get_cpu_load()
# Estimates cpu load using one second window
# Entry:  $1 = pid
# Return: $result = approximate load in %
{
local pid=$1
result=0
[[ -d "/proc/$pid" ]] || return 1
t14_1=$(cut -d ' ' -f14 /proc/$pid/stat) 
t15_1=$(cut -d ' ' -f15 /proc/$pid/stat)
sleep 1
[[ -d "/proc/$pid" ]] || return 1
t14_2=$(cut -d ' ' -f14 /proc/$pid/stat)
t15_2=$(cut -d ' ' -f15 /proc/$pid/stat)
d_t14=$[ $t14_2-$t14_1 ]
d_t15=$[ $t15_2-$t15_1 ]
result=$[d_t14+d_t15]
if [ $result -gt 100 ]; then result=100; fi
}

react_to_load()
{
local load_limit=$1  # [ % ]
local time_limit=$2  # [ seconds ]
local pid="$3"
hi_load_count=0
times_to_check=$time_limit # since 1 s per check
i=$times_to_check
while [ $i -gt 0 ] 
	do
	[[ -d "/proc/$pid" ]] || exit 1
	get_cpu_load $pid
	if [ $? = 1 ]; then
	echo "Monitor closing."
	exit      #Process ended either normal way or killed
	fi
	if [ $result -ge $load_limit ]
	then 
	((hi_load_count++ ))
	((i--))
	else
	hi_load_count=0
	i=$times_to_check
	fi
	done
if [ $hi_load_count -eq $times_to_check ]; then
kill -9 $pid
echo "$(date "+%F %T %z") rtmpdump was killed due to high load $result %, limit $load_limit % $time_limit s." | tee -a $logs_dir/$log_file
fi 
}

inst_dir=/opt/auto_dl
data_root=$inst_dir/.auto_dl
logs_dir=$inst_dir/logs
run_dir=$data_root/running
log_file="loadmon.log"

mkdir -p $data_root/loadmon/started

name="rtmpdump"	
echo "$(date "+%F %T %z") Load control activated." | tee -a $logs_dir/$log_file
while :
do
	pid_list=$(pgrep $name)
	if [ -z "$pid_list" ]; then
		echo "Load control: No rtmpdump active."
		else
		echo "Load control: Starting load watchdog."
		for pid in $pid_list
		do
		if [ ! -f "$data_root/loadmon/started/$pid" ]; then
			touch $data_root/loadmon/started/$pid
			react_to_load 90 15 $pid &
		fi
		done
	fi
	sleep 30
done
rm $data_root/loadmon/started/*

