MyTetra Share
Делитесь знаниями!
Установка monit в Debian
Время создания: 14.03.2017 09:51
Текстовые метки: linux monit config
Раздел: Linux
Запись: Velonski/mytetra-database/master/base/1489467077rd2217co3e/text.html на raw.githubusercontent.com

Monit — программа для поддержания сервисов на плаву, которая умеет слать уведомления в случае каких либо отклонений, софтина работает под linux, bsd и других unix-системах. Используется как средство мониторинга и перезапуска каких либо сервисов.  Гибкие настройки и функционал делают программу очень даже привлекательной!  Рекомендую к употреблению и добро пожаловать под кат.

Monit умеет проверять:

Существование процесса по PID.
Работу определенного порта (TCP/UDP).
Ответ определенного протокола по порту (SMTP, SSH, HTTP,MYSQL…).
Ресурсы, занимаемые процессом (CPU/RAM).
Объем и свободное пространство в файловой системе.
Права доступа к файлу или каталогу.

В случае отклонений monit может:

Остановить, стартовать или перезапустить сервис.
Подождать определенное время.
Послать уведомление.
Примонтировать, отмонтировать файловую систему
Запустить отдельный скрипт и передать ему определенные параметры.

Как видите функционал довольно таки серьезный, софтина есть практически во всех распространенных дистрибутивах Debian, CentOS, FreeBSD. Устанавливать в Debian будем из портов:


Shell

aptitude install monit


1

aptitude install monit

Готово? идем конфигугрировать, но перед этим я немного схитрю, поставилась у нас не самая свежая версия а мы хотим свежую с полным функционалом, идем на официальный сайт и качаем под свою ОС.

http://mmonit.com/monit/download/

берем из архива исполняемый файл monit и кладем его к себе в /usr/bin/monit с заменой =)

Теперь можно настроить конфиг, документация http://mmonit.com/monit/documentation/

Например можно настроить как то так:

/etc/monit/monitrc


Shell

############################################################################### ## Monit конфигурационный файл ############################################################################### ## Запустить monit как депон и проверять процесс с интервалом 1 минута set daemon 60 # Использовать syslog регистрирующий со средством 'демона'. set logfile syslog facility log_daemon ## Список mailservers для доставки оповещения.По умолчанию это 25 порт. set mailserver localhost # primary mailserver set eventqueue basedir /var/log/monit # путь к каталогу, где будут храниться оповещения slots 100 # лимит ## Вы можете самостоятельно задать формат письма set mail-format { from: system-alert@host.com } #set alert sis@host.com # все оповещения set mmonit http://monit:password@IP:PORT/collector set httpd port 2800 and use address IP-SERVER allow admin:admin #Состояние сервера в целом check system serv.host.com group server if loadavg (15min) > 10 then alert if loadavg (5min) > 30 then alert if memory usage > 90% then alert #Проверка apache2 check process apache2 with pidfile /var/run/apache2.pid group www start program = "/etc/init.d/apache2 start" stop program = "/etc/init.d/apache2 stop" if cpu > 50% for 3 cycles then alert # если загрузка cpu > 50% в течение 5 (проверок) послать предупреждение. if cpu > 90% for 3 cycles then restart # если загрузка cpu > 90% в течение 3 циклов то послать перезапустить процесс. if totalmem > 4000.0 MB for 3 cycles then restart # если юзается больше 600 MB мозгов то перезапустить процесс. if children > 200 then restart # если число дочерних процессов > 50 то перезапустить процесс. if failed host IP_ADDR port 80 protocol HTTP then restart # передернуть если не отвечает. if 5 restarts within 5 cycles then timeout # если 5 раз уже перезапускали процесс то сделать timeout. #Проверка nginx check process nginx with pidfile /var/run/nginx.pid group www start program = "/etc/init.d/nginx start" stop program = "/etc/init.d/nginx stop" if cpu > 50% for 3 cycles then alert # если загрузка cpu > 50% в течение 3 (проверок) послать предупреждение. if cpu > 90% for 5 cycles then restart # если загрузка cpu > 80% 6 циклов то послать перезапустить процесс. if totalmem > 1200.0 MB for 3 cycles then restart # если юзается больше 200 MB мозгов то перезапустить процесс. if children > 10 then restart # если число дочерних процессов > 5 то перезапустить процесс. #Проверка dovecot check process dovecot with pidfile /var/run/dovecot/master.pid start program = "/etc/init.d/dovecot start" stop program = "/etc/init.d/dovecot stop" if cpu > 50% for 3 cycles then alert if cpu > 90% for 5 cycles then restart if totalmem > 400.0 MB for 5 cycles then restart if children > 40 then restart if failed port 110 type TCP protocol POP then restart if 5 restarts within 5 cycles then timeout #Проверка exim check process exim with pidfile /var/run/exim4/exim.pid start program = "/etc/init.d/exim4 start" stop program = "/etc/init.d/exim4 stop" if cpu > 50% for 3 cycles then alert if cpu > 90% for 5 cycles then restart if children > 30 then restart #if failed port 25 protocol smtp then restart if 5 restarts within 5 cycles then timeout #Проверка mysql check process mysql with pidfile /var/run/mysqld/mysqld.pid group www start program = "/etc/init.d/mysql start" stop program = "/etc/init.d/mysql stop" if failed unixsocket /var/run/mysqld/mysqld.sock then restart #if failed host 127.0.0.1 port 3306 protocol mysql then restart if 5 restarts within 5 cycles then timeout #Проверка SSH check process sshd with pidfile /var/run/sshd.pid start program "/etc/init.d/ssh start" stop program "/etc/init.d/ssh stop" if failed host IP_ADDR port 22 protocol ssh then restart if 5 restarts within 5 cycles then timeout #Проверка fail2ban # check process fail2ban with pidfile /var/run/fail2ban/fail2ban.pid # start program = "/etc/init.d/fail2ban start" # stop program = "/etc/init.d/fail2ban stop" # if 5 restarts within 5 cycles then timeout # проверяем устройство по точке монтирования. check device rootfs with path / if failed permission 755 then alert if space usage > 90% for 5 times within 10 cycles then alert if inode usage > 90% for 5 times within 10 cycles then alert group server # проверяем устройство по точке монтирования. check device varfs with path /var if failed permission 0755 then alert if space usage > 90% for 5 times within 10 cycles then alert if inode usage > 90% for 5 times within 10 cycles then alert group server # проверяем устройство по точке монтирования. check device tmpfs with path /tmp if failed permission 1777 then alert if space usage > 90% for 5 times within 10 cycles then alert if inode usage > 90% for 5 times within 10 cycles then alert group server


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

###############################################################################

## Monit конфигурационный файл

###############################################################################

## Запустить monit как депон и проверять процесс с интервалом 1 минута

set daemon 60

# Использовать syslog регистрирующий со средством 'демона'.

set logfile syslog facility log_daemon

## Список mailservers для доставки оповещения.По умолчанию это 25 порт.

set mailserver localhost          # primary mailserver

set eventqueue

    basedir /var/log/monit     # путь к каталогу, где будут храниться оповещения

    slots 100                  # лимит

## Вы можете самостоятельно задать формат письма

set mail-format { from: system-alert@host.com }

#set alert sis@host.com        # все оповещения

set mmonit http://monit:password@IP:PORT/collector

    set httpd port 2800 and

    use address IP-SERVER

    allow admin:admin

#Состояние сервера в целом

check system serv.host.com

    group server

    if loadavg (15min) > 10 then alert

    if loadavg (5min) > 30 then alert

    if memory usage > 90% then alert

#Проверка apache2

    check process apache2 with pidfile /var/run/apache2.pid

group www

    start program = "/etc/init.d/apache2 start"

    stop program  = "/etc/init.d/apache2 stop"

    if cpu > 50% for 3 cycles then alert       # если загрузка cpu > 50% в течение 5 (проверок) послать предупреждение.

    if cpu > 90% for 3 cycles then restart            # если загрузка cpu > 90% в течение 3 циклов то послать перезапустить процесс.

    if totalmem > 4000.0 MB for 3 cycles then restart # если юзается больше 600 MB мозгов то перезапустить процесс.

    if children > 200 then restart               # если число дочерних процессов > 50 то перезапустить процесс.

    if failed host IP_ADDR port 80 protocol HTTP then restart # передернуть если не отвечает.

    if 5 restarts within 5 cycles then timeout                # если 5 раз уже перезапускали процесс то сделать timeout.

#Проверка nginx

    check process nginx with pidfile /var/run/nginx.pid

group www

    start program = "/etc/init.d/nginx start"

    stop program  = "/etc/init.d/nginx stop"

    if cpu > 50% for 3 cycles then alert     # если загрузка cpu > 50% в течение 3 (проверок) послать предупреждение.

    if cpu > 90% for 5 cycles then restart          # если загрузка cpu > 80% 6 циклов то послать перезапустить процесс.

    if totalmem > 1200.0 MB for 3 cycles then restart # если юзается больше 200 MB мозгов то перезапустить процесс.

    if children > 10 then restart             # если число дочерних процессов > 5 то перезапустить процесс.

#Проверка dovecot

    check process dovecot with pidfile /var/run/dovecot/master.pid

    start program = "/etc/init.d/dovecot start"

    stop program  = "/etc/init.d/dovecot stop"

    if cpu > 50% for 3 cycles then alert

    if cpu > 90% for 5 cycles then restart

    if totalmem > 400.0 MB for 5 cycles then restart

    if children > 40 then restart

    if failed port 110 type TCP protocol POP then restart

    if 5 restarts within 5 cycles then timeout

#Проверка exim

    check process exim with pidfile /var/run/exim4/exim.pid

    start program = "/etc/init.d/exim4 start"

    stop program  = "/etc/init.d/exim4 stop"

if cpu > 50% for 3 cycles then alert

    if cpu > 90% for 5 cycles then restart

if children > 30 then restart

    #if failed port 25 protocol smtp then restart

    if 5 restarts within 5 cycles then timeout

#Проверка mysql

    check process mysql with pidfile /var/run/mysqld/mysqld.pid

    group www

    start program = "/etc/init.d/mysql start"

    stop program = "/etc/init.d/mysql stop"

    if failed unixsocket /var/run/mysqld/mysqld.sock then restart

    #if failed host 127.0.0.1 port 3306 protocol mysql then restart

    if 5 restarts within 5 cycles then timeout

#Проверка SSH

    check process sshd with pidfile /var/run/sshd.pid

    start program "/etc/init.d/ssh start"

    stop program "/etc/init.d/ssh stop"

    if failed host IP_ADDR port 22 protocol ssh then restart

    if 5 restarts within 5 cycles then timeout

#Проверка fail2ban

#   check process fail2ban with pidfile /var/run/fail2ban/fail2ban.pid

#  start program = "/etc/init.d/fail2ban start"

#   stop program = "/etc/init.d/fail2ban stop"

#   if 5 restarts within 5 cycles then timeout

# проверяем устройство по точке монтирования.

        check device rootfs with path /

        if failed permission 755 then alert

        if space usage > 90% for 5 times within 10 cycles then alert

        if inode usage > 90% for 5 times within 10 cycles then alert

        group server

# проверяем устройство по точке монтирования.

        check device varfs with path /var

        if failed permission 0755 then alert

        if space usage > 90% for 5 times within 10 cycles then alert

        if inode usage > 90% for 5 times within 10 cycles then alert

        group server

# проверяем устройство по точке монтирования.

        check device tmpfs with path /tmp

        if failed permission 1777 then alert

        if space usage > 90% for 5 times within 10 cycles then alert

        if inode usage > 90% for 5 times within 10 cycles then alert

        group server

А вот так можно проверять свои сервера по вебу:


Shell

#host1 check host s3.dgrad-host.com with address host1.com group host if failed port 80 protocol http and request "/status.php" for 2 cycles then alert #host2 check host hit-host.net with address host2.com group host if failed port 80 protocol http and request "/status.php" for 2 cycles then alert


1

2

3

4

5

6

7

8

#host1

check host s3.dgrad-host.com with address host1.com

   group host

   if failed port 80 protocol http and request "/status.php" for 2 cycles then alert

#host2

check host hit-host.net with address host2.com

   group host

   if failed port 80 protocol http and request "/status.php" for 2 cycles then alert

Аналогично но + поиск строки в ответе


Shell

check host host with address host3.com group host CONTENT != "The page you are looking for is temporarily unavailable" timeout 60 seconds 3 cycles then alert


1

2

3

4

5

check host host with address host3.com

group host

CONTENT !=  "The page you are looking for is temporarily unavailable"

timeout 60 seconds 3 cycles

then alert

Внимание! Это только примеры, детальнее смотрите на оф сайте программы а конфигурируйте под свой сервер самостоятельно. Удачных установок monit в Debian!

Так же в этом разделе:
 
MyTetra Share v.0.59
Яндекс индекс цитирования