This post’s name and script’s comments are pretty descriptive, right? 🙂
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 |
#!/bin/bash # # Just put it to your crontab: # # * * * * * root /root/bin/lalala.sh --la1 50 --la5 20 --laf 10 --service httpd --kill --process httpd # # It will kill all httpd processes and restart httpd service when LA1 becomes greater or equal to 50, LA5 - to 20 and LA15 - to 10 # PATH=/bin:/sbin:/usr/bin OPTS=$(getopt -n $(basename ${0}) -o 1:5:f:s:kp: -l la1:,la5:,laf:,service:,kill,process: -- "${@}") if [ "${?}" -ne 0 ]; then echo "Can't get options" >&2 exit 1 fi eval set -- "${OPTS}" while :; do case "${1}" in -1|--la1) THR1="${2}"; shift 2;; -5|--la5) THR5="${2}"; shift 2;; -f|--laf) THR15="${2}"; shift 2;; -s|--service) SERVICE="${2}"; shift 2;; -k|--kill) KILL="1"; shift 1;; -p|--process) PROCESS="${2}"; shift 2;; --) shift; break;; *) echo "Can't recognize the option: ${1}"; exit 1;; esac done if [ -z "${SERVICE}" ]; then echo "Can't understand what service shall I restart" >&2 exit 1 fi if [ "${KILL}" ] && [ -z "${PROCESS}" ]; then echo "Can't understand what process shall I kill" >&2 exit 1 fi LA=$( uptime | sed -r 's/^.*load average: ([0-9]+)(\.[0-9]+)?, ([0-9]+)(\.[0-9]+)?, ([0-9]+)(\.[0-9]+)?$/\1\t\3\t\5/g' ) LA1=$( echo "${LA}" | cut -f1) LA5=$( echo "${LA}" | cut -f2) LA15=$(echo "${LA}" | cut -f3) if [ -n "${THR1}" ] && [ -n "${LA1}" ] && [ "${LA1}" -ge "${THR1}" ] && [ -n "${THR5}" ] && [ -n "${LA5}" ] && [ "${LA5}" -ge "${THR5}" ] && [ -n "${THR15}" ] && [ -n "${LA15}" ] && [ "${LA15}" -ge "${THR15}" ]; then if [ "${KILL}" ]; then while PIDS=$(pidof ${PROCESS}); do echo "Slaying ${PIDS}..." kill -9 ${PIDS} sleep 1 done sleep 10 else service "${SERVICE}" restart fi fi |
Of course, you can get all further updates of this script from GitHub: https://gist.github.com/melnik13/04225e4e60a8d66f9ab6.
Now you can sleep tight in the night! 🙂