-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathEasyDeamonizer.sh
107 lines (93 loc) · 2.58 KB
/
EasyDeamonizer.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/bin/bash
# Name EasyDeamonizer
# Source :
# Atuhor : Sina Salek
# Website : http://sina.salek.ws
# --(Begin)-- Configuration
# Make this script executable by chmod a=r+w+x
# The EasyDeamonizer to run by cron every minute in case it halted
# Optional
APP_NAME="My App"
# Name or part of the name of process when it runs. should be unique
PROCESS_NAME="mailSender:send"
# The command used for running the app via shell
COMMAND="php -q myapp.php"
# Automatically terminates the app when the average load reaches the defined threshhold
MAX_VALID_CPU_LOAD=100
# Add a delay before restarting the app after crash
RESTART_DELAY=10
# Log deamonizer activities including restarting or termination
LOGFILE=EasyDeamonizerLog.txt
RETAIN_NUM_LINES=1000
# --(End)-- Configuration
# Begin - Log
function logsetup {
TMP=$(tail -n $RETAIN_NUM_LINES $LOGFILE 2>/dev/null) && echo "${TMP}" > $LOGFILE
#exec > >(tee -a $LOGFILE)
#exec 2>&1
}
function log {
DATE='date +%Y/%m/%d:%H:%M:%S'
echo `$DATE`": $1" >> $LOGFILE
}
logsetup
#log "Daemon started2"
# End - Log
# Begin - Make sure that it's not already running
PIDS=`pgrep -f $PROCESS_NAME`
CURRENT_PID=`echo $$`
ALREADY_RUNNING=0
for PID in $PIDS
do
if [[ "$PID" != "$CURRENT_PID" ]]
then
ALREADY_RUNNING=1
fi
done
if [ $ALREADY_RUNNING -eq 1 ]
then
#echo "Already running, abort ($PIDS)"
exit;
fi
# End - Make sure that it's not already running
log "Daemon started"
PID=""
PIDS=`pgrep -f $PROCESS_NAME`
for PID in $PIDS
do
kill $PID
log "It is already running by other means $PID, killing it";
done
PID=""
while sleep 2; do
VAR="---"
if [ -z "$PID" ]
then
VAR="---"
else
if ps -p $PID > /dev/null
then
VAR=""
fi
fi
if [ -z "$VAR" ]
then
CPU_LOAD=`ps aux|awk '{print $2,$3,$4}'|grep $PID|awk '{print $2}'`
CPU_LOAD=$( printf "%.0f" $CPU_LOAD )
echo "Current process is $PID And CPU load is $CPU_LOAD"
if [ $CPU_LOAD -gt $MAX_VALID_CPU_LOAD ]
then
kill $PID
log "KILL $PID due to high cpu load"
fi
else
$COMMAND &
PID=$!
log "Daemon started : $PID"
sleep $RESTART_DELAY
fi
done
# Calculate average cpu usage
# ps aux|awk '{print $2,$3,$4}'|grep 23275|awk '{print $3}'
# Calculate current cpu load of a single process
# top -b -d 1 -p 23275 n 1 | awk 'FNR == 8 {print $9}'