The purpose of this script:
Mainly used to monitor the Linux VPS server load and memory footprint, such as MySQl, PHP-FPM, when the load or memory consumption reached the set value, it will automatically restart the process to avoid downtime.
The code is as follows:
# Set maximum memory occupancy percentage
pid_mem_max= "85"
# Set Maximum system load
sys_load_max= "3"
# Set the name of the service that needs to be monitored
name_list= "PHP-FPM MySQL"
For NAME in $NAME _list
Todo
# Initialize Memory statistics
Pid_mem_sum=0
# get the total process number of the program
pid_num_sum= ' ps aux | grep $NAME | Wc-l '
# list percent per process memory footprint
pid_mem_list= ' ps aux | grep $NAME | awk ' {print $} '
# Calculate total memory footprint for all processes
For Pid_mem in $PID _mem_list
Todo
Pid_mem_sum= ' echo $PID _mem_sum + $PID _mem | BC '
Done
# get the last minute system load
Sys_load= ' Uptime | awk ' {print $ (NF-2)} ' | Sed ' s/,//'
# Compare memory footprint and system load over thresholds
Mem_vule= ' awk ' begin{print (' $PID _mem_sum "' >= '" $PID _mem_max ""? " 1 ": 0")} '
Load_vule= ' awk ' begin{print (' $SYS _load "' >= '" $SYS _load_max ""? " 1 ": 0")} '
# If the system memory footprint and system load exceed the threshold, do the following.
if [$MEM _vule = 1] | | [$LOAD _vule = 1]; then
# Write Log
echo $ (date + "%y-%m-%d%h:%m:%s") "Killall $NAME" (MEM: $PID _mem_sum,load: $SYS _load) ">>/var/log/autoreboot.log
# Normal Stop Service
/etc/init.d/$NAME Stop
Sleep 3
# Force Close
Pkill $NAME
# reboot
/etc/init.d/$NAME Start
#写入日志
echo $ (date + "%y-%m-%d%h:%m:%s") "Start $NAME" (MEM: $PID _mem_sum,load: $SYS _load) ">>/var/log/autoreboot.log
Else
echo "$NAME very health! (MEM: $PID _mem_sum,load: $SYS _load) ">/dev/null
Fi
Done
End of code
The above code is saved as a file, for example: auto_reboot.sh
To add a scheduled task, set the check once per minute
Crontab-e
* * * * */bin/bash/root/auto_reboot.sh * * *
Note that the location of the file should be correct.