#! /bin/bash . /usr/src/k_framework/main.sh k_config_details # ---- SCRIPT VARS ----- VERSION="1.0.0" SCRIPT_NAME="Process Control" # ---- SETTINGS ---- TEST_MODE=0 THRESHOLD_CPU=90 # process CPU percent threshold (kill process if using more than X cpu percent) THRESHOLD_MIN=30 # process elapsed time threshold (kill process if running more than X minutes) PROCESSES_TO_MONITOR=(fetchmail) # which processes to monitor # ---- GLOBAL VARS ---- STATS=/tmp/process_control_stats.txt # ---- FUNCTIONS ---- text_blue() { echo -e "\033[0;34m$1\033[0m" } text_green() { echo -e "\033[0;32m$1\033[0m" } check_process() { local process=$1 local id=$(pidof $process 2> /dev/null | awk '{print $1}') if (( id > 0 )); then local elapsed=$(ps -p $id -o etimes | tail -n 1 | grep -Po "\d+") local elapsed_minutes=$(expr $elapsed / 60) local cpu_usage=$(cat $STATS | grep -P "${id}.*${process}.*" | tail -n 1 | awk '{print $9}') local cpu_usage_rounded=$(echo "$cpu_usage" | grep -Po "\d+" | head -n 1) report "Process $(text_green $process) is running for $(text_blue $elapsed_minutes) minutes, cpu usage $(text_blue "$cpu_usage%")" 0 if (( cpu_usage_rounded > THRESHOLD_CPU )) && (( elapsed_minutes > THRESHOLD_MIN )); then if [ "$TEST_MODE" == "0" ]; then report "Terminating process $(text_green $process)!" 2 /usr/bin/kill -9 $id fi fi else report "Process $(text_green $process) is not running" 0 fi } # ---- MAIN ---- k_start $@ if [ "$TEST_MODE" == "1" ]; then report "TEST MODE enabled, processes will not be terminated" 8 fi PATH=$PATH:/usr/sbin:/sbin # Maybe another instance is already running? pidof -o %PPID -x $0 > /dev/null && echo "Script $0 is already running" && exit 1 echo -e "\\t\\tTerminate process if running longer than $(text_blue $THRESHOLD_MIN) minutes and using more than $(text_blue "$THRESHOLD_CPU%") CPU" echo -e "\\t\\tCurrent time: $(date)" # Print stats to file LC_ALL=C top -b -n 2 > $STATS # Iterate through every process in array for process in ${PROCESSES_TO_MONITOR[@]}; do report "-- Checking process $(text_green $process)" 3 check_process $process done rm -fr $STATS &> /dev/null report "Script finished" 0