Использование monit для мониторинга
Постановка задачи
monit - это демон, который периодически (по умолчанию раз в минуту) проверяет выполнение условия (например наличие запущенного процесса), и выполняет действия.
Установка и основные настройки
ставим
yum install monit chkconfig monit on
создаем конфиг /etc/monit.conf
mv /etc/monit.conf /etc/monit.conf_bkp touch /etc/monit.conf chmod 600 /etc/monit.conf
содержимое:
set daemon 60 # check services at 1-minute intervals
set logfile syslog facility log_daemon
set idfile /var/run/monit.id
set statefile /var/run/monit.state
set mailserver mx.minder.com
set alert monit@minder.com
set mail-format { from: monit@minder.com }
set httpd port 2812 and
use address localhost # only accept connection from localhost
allow localhost # allow localhost to connect to the server and
allow admin:monit # require user 'admin' with password 'monit'
allow @monit # allow users of group 'monit' to connect (rw)
allow @users readonly # allow users of group 'users' to connect readonly
include /etc/monit.d/*
Настройка для мониторинга apache
создаем файл /etc/monit.d/httpd
# проверка процесса осуществляется по pid-файлу. Путь к pid-файлу всегда абсолютный
check process httpd with pidfile /var/run/httpd/httpd.pid
start program = "/etc/init.d/httpd start"
# stop program = "/bin/bash -c '/bin/ps ax | /bin/grep httpd | /bin/grep -v grep | /bin/awk "{print \$1}" | /usr/bin/xargs /bin/kill -9'"
stop program = "/etc/init.d/httpd stop"
if cpu > 100% for 2 cycles then alert
# если веб сервер сожрал 90% процессорного времени и не отдает его пять циклов проверки подряд - рестартуем его
if cpu > 90% for 5 cycles then restart
# аналогично по суммарной памяти, которую он поглотил.
# if totalmem > 2048.0 MB for 1 cycles then restart
if totalmem > 90% for 1 cycles then restart
if children > 250 then restart
# если load average сервера за 5 минут больше 10 8 циклов подряд - вырубаем.
# if loadavg(5min) greater than 10 for 8 cycles then stop
# вот тут самое интересное - многоэтапная проверка:
# первый шаг - подключение на 80 порт, протокол http
if failed host 127.0.0.1 port 80 protocol http
# если получилось - запрашиваем файл /index.html
and request "/index.php"
with timeout 15 seconds
# а если что-то из цепочки не получилось - рестартуем демон
then restart
# если за последние пять циклов проверки было три рестарта или больше - пропускаем один цикл проверки.
if 3 restarts within 5 cycles then timeout
Настройка для мониторинга tomcat
check host tomcat with address localhost
start program = "/etc/init.d/tomcat start"
stop program = "/etc/init.d/tomcat stop"
if failed host localhost port 8080 protocol http
and request '/client?&systemPrefix=PMIM'
with timeout 15 seconds
for 5 cycles
then restart
if 3 restarts within 5 cycles then timeout
Настройка для мониторинга файловой системы
файл /etc/monit.d/fs
check filesystem rootfs with path /
if space usage > 90% for 5 times within 15 cycles then alert
if inodes usage > 90% for 5 times within 15 cycles then alert
Мониторинг процесса без PID и проверка кастомного протокола по TELNET
Check process nginx matching nginx
start program = "/bin/systemctl start nginx"
stop program = "/bin/systemctl stop nginx"
if failed host localhost port 4444 with timeout 60 seconds
send "GET /status HTTP/1.1\r\n\r\n"
expect ".*ready.*"
then restart
if 5 restarts within 5 cycles then timeout
Мониторинг при помощи внешнего скрипта
Скрипт /etc/monit/check_chromedriver_status.sh
#!/bin/bash exit `/usr/bin/curl -s http://localhost:4444/status | grep "ready" | wc -l`
конфиг:
Check process chrome-driver matching chromedriver
start program = "/bin/systemctl start chromedriver"
stop program = "/bin/systemctl stop chromedriver"
if failed host 192.168.1.137 port 4444 type tcp then restart
if 5 restarts within 5 cycles then timeout
check program check_chromedriver_status with path /etc/monit/check_chromedriver_status.sh
if status == 0 then restart
depends on chrome-driver
Запуск демонов и проверка состояния
Если сервис мониторится через monit, то само собой его нужно останавливать и запускать только через monit. В противном случае сервис запустится снова.
проверить статус
monit status
остановить/запустить демон
monit stop httpd monit start httpd
приостановить/возобновить мониторинг
monit unmonitor httpd monit monitor httpd
Enjoy!