Настройка системы мониторинга Nagios

Введение

С увеличением размера подконтрольных сетей перед каждым администратором встает вопрос о создании единой системы мониторинга серверов и сервисов. Внедрение такой системы позволит повысить производительность работы компании, уменьшить время простоя оборудования и повысить удовлетворенность руководства результатами вашей работы.

Несмотря на свои неоспоримые достоинства, коммерческие системы вроде Solar Winds, 3COM Network Superviser и HP OpenView в данной статье рассматриватся не будут из-за своих довольно высоких цен и трудоемкости внедрения.

В соответствии со стандартом e-tom задача сбора аварийных сообщений с элементов сетей, серверов и сервисов и диагностика первопричин называется Fault managemet. Для выполнения этой функции мы будем использовать инструмент по имени Nagios.

В тоже время необходимо четко понимать что Nagios как и многие другие решения с открытым кодом не предназначен быть полноценной заменой коммерческим системам технологической поддержки OSS (Operations Support Systems) и значительно уступает им по функционалу во многих областях.

Стоит отметить что кроме Nagios существует множество других бесплатных систем способных в той или иной степени выполнять озвученые задачи. Наиболее известными являются Big Brother, Angel Network Monitor, HiWayS, MARS, Autostatus, NocMonitor, RITW, Zabbix, NetXMS, OpenNMS и множество других.

Давайте рассмотрим главные задачи системы мониторинга. Она должна оповещать администратора с помощью электронной почты, пейджера или sms сообщений, если с наблюдаемыми объектами случаются какие-либо неприятности. Также оповещения должны отсылаться, когда состояние объекта возвращается в норму. Вдобавок ко всем способам, перечисленным выше, Nagios позволяет использовать в качестве инструмента оповещения программы, разработанные пользователями. К примеру таким образом можно реализовать механизм оповещения через SMS. http://onix.opennet.ru/content/view/17/26/

Данные:

Сервер Centos 5.0

Сеть с маршрутизаторами HP Procurve

Задача: обеспечить мониторинг и уведомление о доступности хостов и сервисов в локальной сети.

Установка Nagios

Рекомендую ставить все пакеты с помошью YUM. Для этого подключаем репозиторий epel

rpm -Uvh http://download.fedora.redhat.com/pub/epel/5/i386/epel-release-5-3.noarch.rpm

И делаем хорошо знакомый нам

yum install nagios nagios-plugins

Если по каким-то причинам у Вас не получилось, можно пересобрать srpm пакеты.

Закачиваем и устанавливаем nagios из srpm пакетов

cd /usr/src/redhat/SRPMS
wget -c http://ftp.riken.jp/Linux/fedora/epel/5Server/SRPMS/nagios-2.12-1.el5.src.rpm
rpm -Uvh nagios-2.12-1.el5.src.rpm
cd /usr/src/redhat/SPECS 
rpmbuild --ba nagios.spec
cd /usr/src/redhat/RPMS/i386
rpm -Uvh nagios-2.12-1.i386.rpm nagios-devel-2.12-1.i386.rpm

Закачиваем и устанавливаем плагины

cd /usr/src/redhat/SRPMS
wget -c http://ftp.riken.jp/Linux/fedora/epel/5Server/SRPMS/nagios-plugins-1.4.11-2.el5.src.rpm
rpm -Uvh nagios-plugins-1.4.11-2.el5.src.rpm
cd /usr/src/redhat/SPECS
rpmbuild --ba nagios-plugins.spec

У меня возникли такие неудовлетворенные зависимости

net-snmp-devel нужен для nagios-plugins-1.4.11-2.i386
net-snmp-utils нужен для nagios-plugins-1.4.11-2.i386
postgresql-devel нужен для nagios-plugins-1.4.11-2.i386
/usr/sbin/fping нужен для nagios-plugins-1.4.11-2.i386
perl(Net::SNMP) нужен для nagios-plugins-1.4.11-2.i386
radiusclient-ng-devel нужен для nagios-plugins-1.4.11-2.i386
/usr/bin/qstat нужен для nagios-plugins-1.4.11-2.i386

Устанавливаем их с помошью YUM или собираем из srpm пакетов.

Далее устанавливаем все пакеты nagios-plugins*.rpm

На этом установка nagios и его плагинов завершена.

Настройка вэб сервера apache.

Редактируем файл /etc/httpd/conf.d/nagios.conf а именно строку allow from 10.0.1.10, где указываем адрес с которого разрешен вход.

Создаем файл где будут храниться имена пользователей и пароли touch /etc/nagios/passwd

Создаем пользователя admin

htpasswd /etc/nagios/passwd admin
New password: *****
Re-type new password: *****
Adding password for user admin

На этом настройка вэб сервера завершена.

Настройка nagios

Файлы конфигурации находятся в /etc/nagios/. Для удобства создаем следующие файлы.

touch /etc/nagios/contactgroups.cfg
touch /etc/nagios/contacts.cfg
touch /etc/nagios/hostgroups.cfg
touch /etc/nagios/hosts.cfg
touch /etc/nagios/services.cfg
touch /etc/nagios/timeperiods.cfg

Теперь займемся файлом cgi.cfg. Нам нужно изменить некоторые параметры:

authorized_for_system_information=admin
# Список пользователей, которым разрешен просмотр
# информации о работе процесса Nagios

authorized_for_configuration_information= admin
# Список пользователей, которым разрешен просмотр
# информации о конфигурации всех хостов и сервисов.
# По умолчанию пользователь может смотреть
# конфигурацию только хостов и сервисов,
# принадлежащих к его контактной группе.

authorized_for_system_commands=admin
# Список пользователей, авторизованных для выполнения
# через cmd.cgi команд управления процессом Nagios.

authorized_for_all_services=admin
authorized_for_all_hosts=admin
# Эти два параметра определяют список пользователей, которым разрешен просмотр
# информации обо всех наблюдаемых хоста и сервисах.
# По умолчанию пользователь может видеть
# только те хосты и сервисы, которые принадлежат к его контактной группе.

refresh_rate=10
# Частота обновления (в секундах) информации, просматриваемой через web-интерфейс.
# По умолчанию установлено 90 секунд, но нам такой большой интервал не подходит.
# Поэтому поставим 10 секунд.

В файл nagios.cfg вносим следующие изменения

date_format=euro
# Устанавливаем формат даты более привычный для России

check_external_commands=1
# Разрешаем обрабатывать команды, передаваемые процессу Nagios через web-интерфейс.

command_file=/usr/local/nagios/var/nagios.cmd
# Местоположение файла внешних команд.

Конфигурируем localhost

Описываем контактную группу

 cat contactgroups.cfg 
define contactgroup{
        contactgroup_name       admins
        alias                   AES Administrators
        members                 admin
        }

Вносим свои контактные данные

cat contacts.cfg 
define contact{
        contact_name                    admin
        alias                           Admin
        service_notification_period     24x7
        host_notification_period        24x7
        service_notification_options    w,u,c,r
        host_notification_options       d,r
        service_notification_commands   notify-by-email
        host_notification_commands      host-notify-by-email
        email                           admin@mydomain.com
        }

Разбиваем объекты мониторинга на группы.

cat hostgroups.cfg 
define hostgroup{
        hostgroup_name  servers
        alias           AES Servers
        members         gw
        }

Создаем шаблоны и описываем хосты

cat hosts.cfg 
define host{
        name                            generic-host    ; The name of this host template
        notifications_enabled           1               ; Host notifications are enabled
        event_handler_enabled           1               ; Host event handler is enabled
        flap_detection_enabled          1               ; Flap detection is enabled
        failure_prediction_enabled      1               ; Failure prediction is enabled
        process_perf_data               1               ; Process performance data
        retain_status_information       1               ; Retain status information across program restarts
        retain_nonstatus_information    1               ; Retain non-status information across program restarts
        notification_period             24x7            ; Send host notifications at any time
        register                        0               ; DONT REGISTER THIS DEFINITION        }

define host{
        name                            aes-server      ; The name of this host template
        use                             generic-host    ; This template inherits other values from the generic-host template
        check_period                    24x7            ; By default, Linux hosts are checked round the clock
        max_check_attempts              10              ; Check each Linux host 10 times (max)
        check_command                   check-host-alive ; Default command to check Linux hosts
        notification_period             workhours       ; Linux admins hate to be woken up, so we only notify during the day
                                                        ; Note that the notification_period variable is being overridden from
                                                        ; the value that is inherited from the generic-host template!
        notification_interval           120             ; Resend notification every 2 hours
        notification_options            d,u,r           ; Only send notifications for specific host states
        contact_groups                  admins          ; Notifications get sent to the admins by default
        register                        0               ; DONT REGISTER THIS DEFINITION 
        }

define host{
        use                     aes-server              ; Name of host template to use
                                                        ; This host definition will inherit all variables that are defined
                                                        ; in (or inherited by) the linux-server host template definition.
        host_name               gw
        alias                   gw
        address                 127.0.0.1
        }

Описываем список объектов которые будем мониторить

cat services.cfg 
define service{
        name                            generic-service ; The 'name' of this service template
        active_checks_enabled           1               ; Active service checks are enabled
        passive_checks_enabled          1               ; Passive service checks are enabled/accepted
        parallelize_check               1               ; Active service checks should be parallelized
        obsess_over_service             1               ; We should obsess over this service (if necessary)
        check_freshness                 0               ; Default is to NOT check service 'freshness'
        notifications_enabled           1               ; Service notifications are enabled
        event_handler_enabled           1               ; Service event handler is enabled
        flap_detection_enabled          1               ; Flap detection is enabled
        failure_prediction_enabled      1               ; Failure prediction is enabled
        process_perf_data               1               ; Process performance data
        retain_status_information       1               ; Retain status information across program restarts
        retain_nonstatus_information    1               ; Retain non-status information across program restarts
        is_volatile                     0               ; The service is not volatile
        register                        0               ; DONT REGISTER THIS DEFINITION
        }

define service{
        name                            local-service   ; The name of this service template
        use                             generic-service ; Inherit default values from the generic-service definition
        check_period                    24x7            ; The service can be checked at any time of the day
        max_check_attempts              4               ; Re-check the service up to 4 times in order to determine its final (hard) state
        normal_check_interval           5               ; Check the service every 5 minutes under normal conditions
        retry_check_interval            1               ; Re-check the service every minute until a hard state can be determined
        contact_groups                  admins          ; Notifications get sent out to everyone in the 'admins' group
        notification_options            w,u,c,r         ; Send notifications about warning, unknown, critical, and recovery events
        notification_interval           60              ; Re-notify about service problems every hour
        notification_period             24x7            ; Notifications can be sent out at any time
        register                        0               ; DONT REGISTER THIS DEFINITION
        }

# Define a service to "ping" the local machine
define service{
        use                             local-service   ; Name of service template to use
        host_name                       gw
        service_description             PING
        check_command                   check_ping!100.0,20%!500.0,60%
        }

define service{
        use                             local-service
        host_name                       gw
        service_description             Root Partition
        check_command                   check_local_disk!20%!10%!/
        }

define service{
        use                             local-service        
        host_name                       gw
        service_description             Current Users
        check_command                   check_local_users!20!50
        }

define service{
        use                             local-service         
        host_name                       gw
        service_description             Total Processes
        check_command                   check_local_procs!250!400!RSZDT
        }

define service{
        use                             local-service         
        host_name                       gw
        service_description             Current Load
        check_command                   check_local_load!5.0,4.0,3.0!10.0,6.0,4.0
        }

define service{
        use                             local-service         
        host_name                       gw
        service_description             Httpd
        check_command                   check_http
        }

define service{
        use                             local-service         
        host_name                       gw
        service_description             SMTP
        check_command                   check_smtp
        }

define service{
        use                             local-service         
        host_name                       gw
        service_description             IMAP
        check_command                   check_imap
        }

define service{
        use                             local-service         
        host_name                       gw
        service_description             DNS
        check_command                   check_dns
        }

Конфигурируем Switchs

Добавляем в hostgroups.cfg

define hostgroup{
        hostgroup_name  switchs
        alias           AES Switchs
        members         main
        }

host.cfg

define host{
        name                            aes-switchs     ; The name of this host template
        use                             generic-host    ; This template inherits other values from the generic-host template
        check_period                    24x7            ; By default, Linux hosts are checked round the clock
        max_check_attempts              10              ; Check each Linux host 10 times (max)
        check_command                   check-host-alive ; Default command to check Linux hosts
        notification_period             workhours
        notification_interval           120             ; Resend notification every 2 hours
        notification_options            d,u,r           ; Only send notifications for specific host states
        contact_groups                  admins          ; Notifications get sent to the admins by default
        register                        0               ; DONT REGISTER THIS DEFINITION
        }
#switchs
define host{
        use                     aes-switchs
        host_name               main
        alias                   mail
        address                 10.180.0.11
        }
define host{
        use                     aes-switchs
        host_name               1a
        alias                   1st floor A
        address                 10.180.0.12
        parents                 main
        }

services.cfg

#switchs
define service{
        use                             local-service
        host_name                       main
        service_description             PING
        check_command                   check_ping!100.0,20%!500.0,60%
        }

После каждого изменения в конфигурационных файлах делаем

/etc/init.d/nagios restart

После всех манипуляций в броузере набираем  http://ip/nagios/  и наслаждаемся результатом.

Articles/RomanLobko/nagios (last edited 2008-07-10 06:23:18 by RomanLobko)