Nagios

Instalació

Nagios és una aplicació de monitorització remota de recursos (hosts, serveis i xarxes). Nagios ja està incorporat a SkoleLinux.

En les màquines ubuntu en les que he instalat nagios he utilitzat els repositoris main i les comandes apt-get o sinaptic per instalar els següents paquets:

$ sudo aptitude install nagios3 nagios-plugins nagios3-cgi nagios3-doc

El manual de nagios es troba a [HOW-TO http://nagios.linuxbaja.org/?q=node/15] (en castellà).

Configuració de nagios

La configuració del nagios és fa amb els fitxers de la carpeta /etc/nagios3/conf.d

NOTA: a SkoleLinux els fitxers estan a /etc/nagios/debian-edu /etc/nagios/resource.cfg

En aquest fitxer es poden definir MACROS o variables que es poden utilitzar en els fitxers de configuració de Nagios. És útil per enmagatzemar dades crítiques com usuaris i passwords.

  • Fitxer /etc/nagios3/conf.d/generic-host_nagios2.cfg

En aquest fitxers es defineixen les màquines que es volen monitoritzar.

Exemples de la meva configuració:

# Exemple de host
define host{
      use                     generic-host            ; Name of host template to use
      host_name               NomDeLaMaquina
      alias                   Una descripcio
      address                 127.2.2.1
      check_command           check-host-alive
      max_check_attempts      20
      notification_interval   60
      notification_period     24x7
      notification_options    d,u,r
      }

Podem afegir tantes màquines com creiem convenient. Si ens fixem les màquines utilitzen un template (intrucció use generic-host). El template es troba a l'inici del fitxer generic-host_nagios2.cfg

# Generic host definition template - This is NOT a real host, just a template!

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
		check_command                   check-host-alive
		max_check_attempts              10
		notification_interval           0
		notification_period             24x7
		notification_options            d,u,r
		contact_groups                  admins
        register                        0       ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL HOST, JUST A TEMPLATE!
        }
  • Fitxer /etc/nagios3/conf.d/hostgroups_nagios2.cfg

En aquest fitxers es defineixen els grups de màquines (default gateway host group definition)

# Some generic hostgroup definitions

# A simple wildcard hostgroup
define hostgroup {
        hostgroup_name  all
		alias           All Servers
		members         *
        }

# A list of your Debian GNU/Linux servers
define hostgroup {
        hostgroup_name  debian-servers
		alias           Debian GNU/Linux Servers
		members         localhost
        }

# A list of your web servers
define hostgroup {
        hostgroup_name  http-servers
		alias           HTTP servers
		members         localhost
        }

# A list of your ssh-accessible servers
define hostgroup {
        hostgroup_name  ssh-servers
		alias           SSH servers
		members         localhost
        }
  • Fitxer /etc/nagios3/conf.d/generic-service_nagios2.cfg

Aqui és poden definir els serveis que volem monitoritzar dels hosts que hem registrat. El mateix fitxer ens ofereix infinitat d'exemples dels serveis que es poden monitoritzar (HTTP, ports TCP-IP, base de dades, recursos d'espai i memòria,etc)

Igual que el que succeix amb el fitxer generic-host_nagios2.cfg és pot utilitzar un template:

 define service{
       name                            generic-service    ;The 'name' of this service template, referenced in other 
       active_checks_enabled           1       ; Active service checks are enabled
       passive_checks_enabled          0       ; Passive service checks are enabled/disabled
       parallelize_check               1       ; Active service checks should be parallelized
                                               ; (disabling this can lead to major performance problems)
       obsess_over_service             1       ; We should obsess over this service (if necessary)
       check_freshness                 0       ; Default is to NOT check service 'freshness'
       notifications_enabled           0       ; Service notifications are disabled
       event_handler_enabled           0       ; Service event handler is disabled
       flap_detection_enabled          0       ; Flap detection is disabled
       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
       register                        0 ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL SERVICE, JUST A TEMPLATE!
       }
  • Fitxer /etc/nagios3/conf.d/contacts_nagios2.cfg

En aquest fitxer es defineixen les persones i les seves dades de contacte (email, beeper, SMS) encarregades de la monitorització. Aquest contactes són els que, en el cas de que el servei monitoritzat tingui el servei d'alertes instal·lat, rebran les alertes de posibles problemes amb els serveis. Codi d'exemple:

 define contact{
       contact_name                    nagios
       alias                           Nagios Admin
       service_notification_period     24x7
       host_notification_period        24x7
       service_notification_options    w,u,c,r
       host_notification_options       d,u,r
       service_notification_commands   notify-by-email,notify-by-epager
       host_notification_commands      host-notify-by-email,host-notify-by-epager
       email                           emailNagiosAdmin@localhost
       pager                           pagenagios-admin@localhost
       }

Codi del fitxer original:

###############################################################################
# contacts.cfg
###############################################################################



###############################################################################
###############################################################################
#
# CONTACTS
#
###############################################################################
###############################################################################

# In this simple config file, a single contact will receive all alerts.

define contact{
        contact_name                    root
        alias                           Root
        service_notification_period     24x7
        host_notification_period        24x7
        service_notification_options    w,u,c,r
        host_notification_options       d,r
        service_notification_commands   notify-service-by-email
        host_notification_commands      notify-host-by-email
        email                           root@localhost
        }



###############################################################################
###############################################################################
#
# CONTACT GROUPS
#
###############################################################################
###############################################################################

# We only have one contact in this simple configuration file, so there is
# no need to create more than one contact group.

define contactgroup{
        contactgroup_name       admins
        alias                   Nagios Administrators
        members                 root
        }

Verificant la configuració. Execució de Nagios

Nagios té un script que permet verificar si els fitxers de configuració no tenen cap error. Executem:

# /usr/sbin/nagios3 -v /etc/nagios3/nagios.cfg

Si tot està correctament:

 Total Warnings: 0
 Total Errors: 0
 Things look okay - No serious problems were detected during the pre-flight check

Aleshores podem correr el dimoni de nagios

# /etc/init.d/nagios3 start
 Starting network monitor: nagios

Comprovem que s'esta executant

# ps aux | grep nagios
 PID TTY TIME CMD
 29864 ? 00:00:00 nagios

Ja tenim el nagios executant-se. Ara falta configurar Apache i el CGI de nagios per poder accedir a la interface web

Configuració de servidor web per enviament de correus electrònics

En el fitxer /etc/nagios3/conf.cfg/contact_nagios2.cfg, s'ha de configurar el correu electrònic on volem ens arribin les notificacions de nagios:

# In this simple config file, a single contact will receive all alerts.

define contact{
        contact_name                    root
        alias                           Root
        service_notification_period     24x7
        host_notification_period        24x7
        service_notification_options    w,u,c,r
        host_notification_options       d,r
        service_notification_commands   notify-service-by-email
        host_notification_commands      notify-host-by-email
        email                           zikzak@zikzakmedia.com
        }


# Nuevo usuario, creado para el seguimiento de un servicio
define contact{
        contact_name                        usuari
        alias                               Jesús Martín
        service_notification_period         24x7
        host_notification_period            24x7
        service_notification_options        w,u,c,r
        host_notification_options           d,r
        service_notification_commands       notify-service-by-email
        host_notification_commands          notify-host-by-email
        email                               usuari@zikzakmedia.com
        }

Per rebre aquestes notificacions s'ha d'instal·lar i configurar un servidor de correu electrònic. En aquest cas anem instal·lar postfix como servidor de correu:

sudo aptitude install postfix

I en el moment de configurar-ho, s'ha de seleccionar l'opció “Internet amb <smarthost>”. Amb aquesta opció indiquem a postfix que farem servir un servidor de correu extern per enviar els emails. Si per qualsevol motiu postfix ja estès instal·lat, es pot tornar a executar l'assistent de configuració amb la següent ordre:

sudo dpkg-reconfigure postfix

Configuració del CGI de nagios. Configuració d'Apache

Fitxer cgi.cfg

En aquest fitxer es controlen les opcions del cgi nagios. La configuració per defecte normalment ja funciona.

Configuració d'Apache

La instal·lació per defecte ja permet monitoritzar els serveis configurats a nagios i veure'ls amb el servidor web. Per accedir-hi s'ha d'entrar a la següent adreça:

http://adreça_ip_servidor/nagios3

El nom de l'usuari per defecte és: nagiosadmin La contrasenya: la que s'ha posat en el moment d'instal·lació de nagios3

Monitorització via web

L'accés a la web de monitorització de nagios és:

http://yourmachine/nagios

Més info sobre la configuració de la interface web : http://nagios.sourceforge.net/docs/2_0/installweb.html

Canviar el password d'administrador

Nagios ve configurat per defecte amb un usuari nagiosadmin i un password (el que s'ha introduït en el moment d'instal.lar l'aplicació). Es pot canviar executant:

 htpasswd -c /etc/nagios/htpasswd.users nagiosadmin

Es pot utilitzar httacces d'Apache: http://nagios.sourceforge.net/docs/2_0/cgiauth.html

A Skole-Linux els fitxers de configuració del nagios estan a un altre carpeta. Per tant:

sudo htpasswd -c /etc/nagios/debian-edu/htpasswd.users nagiosadmin

Configurar els teus propis serveis

Nagios utilitza un sistema de plugins que permet la seva extensibilitat i la possibilitat d'implementar els teus propis serveis.

Nagios a SkoleLinux

Per tal d'accedir remotament al nagios (fora de la xarxa interna) cal afegir la següent línia al fitxer /etc/hosts

217.149.150.23 tjener.intern tjener

Sinó dóna error que no es pot accedir a tjener.intern.

Errors freqüents

Whoops! Error: Could not read host and service status information!

Aquest error ens indica que hi ha algun problema amb el cgi de nagios. Comproveu que s'està executant Nagios. Llegiu el fitxer de log /var/log/nagios/nagios.log.

Error: Could not connect to MySQL database …

No s'ha configurat l'accés a la base de dades de Nagios en MySql. Si s'ha instalat Nagios utilitzant el paquet Debian (nagios-mysql) podem trobar la solució d'aquest error a:

/usr/share/doc/nagios-mysql

El fitxer README.Debian. Explica com configurar l'accés a base de dades de Nagios

Una solució potser més sencilla és utilitzar nagios en mode text: Es a dir instalar el paquet nagios-text en comptes del nagios-mysql.

Monitoritzar el log de Nagios

 tail -f --lines=200 /var/log/nagios/nagios.log

Recursos. Links d'Interès

Configuració de nagios-nrpe-server i nagios-nrpe-plugins

Els passos següents s'han de fer com a usuari root. S'ha de diferenciar entre el servidor nagios (localhost) i el servidor del servei que es vol monitoritzar remotament però com si fos local (remote host)

Configuració del servidor remot

  • Instal·lar els plugins de nagios:
# aptitude install nagios-plugins
  • Instal·lar el xinetd
# aptitude install xinetd
  • Instal·lar el nagios-nrpe-server i el nagios-nrpe-plugins
# aptitude install nagios-nrpe-plugin nagios-nrpe-server
  • Comprovar que funciona el dimoni local:
# netstat -at | grep nrpe
tcp        0        0 *:nrpe       *:*     LISTEN

Si no funciona s'ha de comprovar el següent:

  1. Hi ha una entrada amb nrpe al fitxer /etc/services
  2. La directiva only_from del fitxer /etc/xinet.d/nrpe conté una entrada per “127.0.0.1” (No procedeix)
  3. xinetd està instal·lat i arrencat
# /usr/lib/nagios/plugins/check_nrpe -H localhost
NRPE v2.12
  • Obrir els ports del firewall:
# iptables -I INPUT -p tcp -m tcp --dport 5666 -j ACCEPT
  • Personalització de les comandes NRPE.

S'ha d'editar el fitxer /etc/nagios/nrpe.cfg i modificar la línia allowed_hosts per autoritzar el servidor amb el servidor nagios a accedir a la màquina:

allowed_hosts=127.0.0.1,192.168.0.33

I permetre el pas de paràmetres a la comanda remota

# COMMAND ARGUMENT PROCESSING
# This option determines whether or not the NRPE daemon will allow clients
# to specify arguments to commands that are executed.  This option only works
# if the daemon was configured with the --enable-command-args configure script
# option.
#
# *** ENABLING THIS OPTION IS A SECURITY RISK! ***
# Read the SECURITY file for information on some of the security implications
# of enabling this variable.
#
# Values: 0=do not allow arguments, 1=allow command arguments

dont_blame_nrpe=1

Cap al final del fitxer, s'han d'afegir les comandes que es volen poder executar des del servidor remot.

Exemple MySQL

Editar el fitxer /etc/nagios/nrpe.cfg i afegir cap al final:

# Check the status of MySQL Database
command[sh_check_mysql]=/usr/lib/nagios/plugins/check_mysql -u $ARG1$ -p $ARG2$

On:

  1. -u: Es refereix a l'usuari creat a l'efecte per monitoritzar MySQL.
  2. -p: És la seva contrasenya.

Exemple PosgreSQL

Editar el fitxer /etc/nagios/nrpe.cfg i afegir cap al final:

# Check the status of PostgreSQL Database
command[sh_check_pgsql]=/usr/lib/nagios/plugins/check_pgsql -d $ARG1$ -l $ARG2$ -p $ARG3$

On:

  1. -d: És refereix a la base de dades que es vol monitoritzar.
  2. -l: És l'usuari propietari de la base de dades anterior.
  3. -p: És la seva contrasenya.

Exemple fitxers backup

Editar el fitxer /etc/nagios/nrpe.cfg i afegir cap al final:

# Check the status of backup file
command[check_backup]=/usr/lib/nagios/plugins/check_backup -f $ARG1$

On:

  1. -f: És el nom del fitxer que es vol comprovar.

Configuració del servidor Nagios

Es parteix de la base que ja s'ha instal·lat i configurat un servidor Nagios.

  • Instal·lar el nagios-nrpe-plugins
# aptitude install nagios-nrpe-plugin
  • Fer un test de connexió al host remot que es vol monitoritzar:
# /usr/lib/nagios/plugins/check_nrpe -H 192.168.0.33
NRPE v2.12

Si no funciona cal assegurar-se que no hi ha cap firewall bloquejant les comunicacions, i que el dimoni nrpe remot està funcionant correctament.

  • Afegir als fitxers de configuració les crides a la comanda remota mitjançant la comanda check_nrpe. Un exemple:

/etc/nagios3/conf.d/host_que_es_vol_monitoritzar.cfg

# Virtual Host

define host{
    name                    linux-box           ; Name of this template
    use                     generic-host        ; Inherit default values
    check_period            24x7
    check_interval          5
    retry_interval          1
    max_check_attempts      10
    check_command           check-host-alive
    notification_period     24x7
    notification_interval   30
    notification_options    d,r
    contact_groups          admins
    register                0           ; DONT REGISTER THIS - ITS A TEMPLATE
}

define host{
        use                     linux-box            ; Name of host template to use
        host_name               virtual_host
        alias                   virtual_host
        address                 192.168.0.11
        }

# Define a service to check disk space
define service{
        use                     generic-service         ; Name of service template to use
        host_name               virtual_host
        service_description     Disk Space
        check_command           check_all_disks!20%!10%
       }

# Define a service to check if remote Host is listening to
define service{
        use                     generic-service         ; Name of service template to use
        host_name               virtual_host
        service_description     PING
        check_command           check_ping!250.0,20%!500.0,60%
	notification_interval   0 ; set > 0 if you want to be renotified
       }

# Define a service to check that http services are running
define service{
        use                     generic-service         ; Name of service template to use
        host_name               virtual_host
        service_description     HTTP
	check_command           check_http
       }

# Define a service to check that ssh services are running
define service {
        use                     generic-service         ; Name of service template to use
        host_name               virtual_host
        service_description     SSH
        check_command           check_ssh
        notification_interval   0 ; set > 0 if you want to be renotified
}

# Define a service to check the load on the local machine. 
define service{
        use                     generic-service         ; Name of service template to use
        host_name               virtual_host
        service_description     Current Load
        check_command           check_load!5.0!4.0!3.0!10.0!6.0!4.0
}

# Define a service to check if port of OpenERP is listening to
define service {
        use                     generic-service
        host_name               virtual_host
        service_description     OpenERP Port
        check_command           check_tcpd!28061
}

# Define a service to check if MySQL database is running
define service {
        use                     generic-service
        host_name               virtual_host
        service_description     MySQL
        check_command           check_nrpe!sh_check_mysql!nagios_user nagios_password
}

# Define a service to check if PostgreSQL database is running
define service {
        use                     generic-service
        host_name               virtual_host
        service_description     PostgreSQL
        check_command           check_nrpe!sh_check_pgsql!Tarim openerp6 admin
}
  • Verificar la configuració del servidor i reengegar Nagios
# /etc/init.d/xinetd restart
# /etc/init.d/nagios3 restart

Monitoritzar bases de dades MySQL

Configuració servidor MySQL

Per poder monitoritzar base de dades de MySQL s'ha de crear un usuari amb tots els permisos a la base de dades. Primer de tot mirem quants usuaris estan donats d'alta:

mysql -u root -p
use mysql
select Host,User,Password from user;

Això mostra els usuaris que actualment estan creats a la base de dades de MySQL.

grant all privileges on *.* to 'nagios'@'localhost' identified by 'admin';
flush privileges;

On:

  • nagios: És l'usuari de la base de dades de MySQL amb que es vol accedir des de nagios (s'ha de vigilar el domini: no és el mateix 'localhost' que '127.0.0.1' que '192.168.0.5' -suposant que aquesta darrera és l'adreça interna del servidor de MySQL-).
  • 127.0.0.1: És l'adreça IP del servidor nagios des d'on es farà la comprovació
  • admin: És la contrasenya de l'usuari nagiosadmin a la base de dades.

Després s'ha de comprovar el port a MySQL per a que escolti a l'adreça anterior: Per fer-ho, s'ha d'editar el fitxer /etc/mysql/my.cnf i comprovar que la línia

bind-addres           = 127.0.0.1

té la mateixa adreça que hem donat abans.A continuació s'ha de reengegar el servidor MySQL:

$ sudo /etc/init.d/mysql restart

Configuració servidor Nagios

Després s'ha de configurar el servidor nagios. Per fer-ho s'ha d'editar el fitxer /etc/nagios3/commands.cfg i afegir la següent definició de comanda:

# 'sh_check_mysql' remote command definition
define command{
        command_name sh_check_mysql
        command_line $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$ -a $ARG2$
}

# 'sh_check_pgsql' remote command definition
define command{
        command_name sh_check_pgsql
        command_line $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$ -a $ARG2$
}

Després s'ha d'editar el fitxer de configuració de serveis del host on s'allotja el servidor (p.e. /etc/nagios3/conf.d/localhost_nagios2.cfg), per afegir el següent servei:

# Define a service to check if MySQL database is running
define service {
        use                     generic-service
        host_name               virtual_host
        service_description     MySQL
        check_command           check_nrpe!sh_check_mysql!nagiosadmin admin
}

# Define a service to check if PostgreSQL database is running
define service {
        use                     generic-service
        host_name               virtual_host
        service_description     PostgreSQL
        check_command           check_nrpe!sh_check_pgsql!Tarim openerp6 admin
}

I finalment s'ha de reiniciar el servidor nagios per a que comenci a fer el monitoreig:

$ sudo /etc/init.d/nagios3 restart

Monitoritzar bases de dades PostgreSQL

Configuració servidor PostgreSQL

Per poder monitoritzar base de dades de PostgreSQL el procediment és molt similar al que s'ha seguit per MySQL, Primer de tot s'ha de crear un usuari amb tots els permisos a la base de dades.

sudo su postgrs
psql -l
createuser --pwprompt nagios

S'introdueixen dues vegades les contrasenyes i se l'hi diu que sí és usuari administrador.

Configuració servidor Nagios

Després s'ha de configurar el servidor nagios. Per fer-ho s'ha d'editar el fitxer /etc/nagios3/commands.cfg i afegir la següent definició de comanda:

# 'sh_check_pgsql' remote command definition
define command{
        command_name sh_check_pgsql
        command_line $USER1$/check_nrpe -H $HOSTADDRESS$ -c $ARG1$ -a $ARG2$
}

Després s'ha d'editar el fitxer de configuració de serveis del host on s'allotja el servidor (p.e. /etc/nagios3/conf.d/localhost_nagios2.cfg), per afegir el següent servei:

# Define a service to check if PostgreSQL database is running
define service {
        use                     generic-service
        host_name               virtual_host
        service_description     PostgreSQL
        check_command           check_nrpe!sh_check_pgsql!Tarim openerp6 admin
}

I finalment s'ha de reiniciar el servidor nagios per a que comenci a fer el monitoreig:

$ sudo /etc/init.d/nagios3 restart

Monitoritzar un servidor OpenERP

El primer que cal fer és instal·lar la llibreria ooop que trobaràs al githup de zikzakmedia. Per fer-ho, seguirem els següents passos.

  1. Descarregar el fitxer:
# cd; mkdir ooop; cd ooop; wget https://github.com/zikzakmedia/ooop/zipball/master

A continuació cal descomprimir-lo:

# unzip master

Entrem dintre del directori creat:

# cd zikzakmedia-ooop-a35e4db/

I instal·lem la llibreria:

# python setup.py install

Crear el fitxer de definició de servei /etc/nagios3/commands.cfg, i afegir el següent codi al final del fitxer:

# 'check_openerp' command definition
define command{
        command_name    check_openerp
        command_line    $USER1$/check_openerp -H '$HOSTADDRESS$' -P '$ARG1$' -d '$ARG2$' -u '$ARG3$' -p '$ARG4$'
}

Al directori /usr/lib/nagios/plugins afegir el fitxer check_openerp amb el següent contingut:

#!/usr/bin/python
# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (c) 2011 Zikzakmedia S.L. (http://zikzakmedia.com) All Rights Reserved.
#                       Jesús Martín <jmartin@zikzakmedia.com>
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from ooop import OOOP
from optparse import OptionParser

OK=0
WARNING=1
CRITICAL=2

def connection(protocol='xml-rpc', host='localhost', port=8069,
                    dbname='training_school', user='admin', pwd='admin'):
    """Connection to OpenERP with OOOP"""
    try:
        conn = OOOP(user=user, pwd=pwd, dbname=dbname, uri=host, port=port, protocol='xmlrpc')
        if conn:
            return True
        return False
    except:
        return False

def main():
    usage = "usage: %prog [options]"
    parser = OptionParser(usage)
    parser.add_option("-H", "--host", dest="host",
                    help="Host IP address.")
    parser.add_option("-P", "--port", dest="port",
                    help="Port of connection (default 8069).")
    parser.add_option("-d", "--database", dest="dbname",
                    help="Database to connect to.")
    parser.add_option("-u", "--user", dest="user",
                    help="Database's user owner.")
    parser.add_option("-p", "--password", dest="pwd",
                    help="Password of the database's user owner.")
    #parser.add_option("-h", "--help", dest="help",
                    #help="Show this help.")
    (options, args) = parser.parse_args()

    if not options.host or not options.port:
        print "Usage:\ncheck_openerp -H <http://host_ip_address> -P <host_port> -d <database> -u <database_user> -p <user_password>"
        exit()

    if connection(
                host = options.host[0:7] == 'http://' and options.host or 'http://' + options.host,
                port = int(options.port),
                dbname= options.dbname,
                user = options.user,
                pwd = options.pwd):
        print "OpenERP %s: OK" % options.dbname
        return OK
    elif connection(
                host = options.host[0:7] == 'http://' and options.host or 'http://' + options.host,
                port = int(options.port),
                dbname= options.dbname,
                user = options.user,
                pwd = options.pwd):
        print "OpenERP %s: WARNING" % options.dbname
        return WARNING
    print "OpenERP %s: CRITICAL" % options.dbname
    return CRITICAL

if __name__ == "__main__":
    exit(main())

Donar permisos d'execució al fitxer i a continuació editar el fitxer /etc/nagios3/conf.d/nom_host.cfg i afegir la següent definició de servei:

# Define a service to check if OpenERP is running
define service {
        use                     generic-service
        host_name               virtual_host
        service_description     OpenERP training
        check_command           check_openerp!8069!nom_db!oerp_user!oerp_pwd
}

On:

  1. 8069: És el port per on cal connectar-se.
  2. nom_db: És la base de dades a la que volem connectar-nos.
  3. oerp_user: És l'usuari d'OpenERP amb que volem connectar-nos.
  4. oerp_pwd: És la contrasenya de l'usuari.

Monitoritzar que es fan correctament les còpies de seguretat (Backups)

  • Configuració al servidor Nagios
  1. Crear el fitxer de definició de servei /etc/nagios3/commands.cfg, i afegir el següent codi al final del fitxer:
    # 'check_backup' command definition
    define command{
            command_name    check_backup 
            command_line    $USER1$/check_openerp -H '$HOSTADDRESS$' -c '$ARG1$' -a '$ARG2$' 
    }
    
  2. Afegir al fitxer de configuració /etc/nagios3/conf.d/host.cfg la següent definició de servei:
    # Define a service to check if Backup is made                
    define service {
            use                     generic-service
            host_name               zzsaas
            service_description     Backup OpenERP Demo
            check_command           check_nrpe!check_backup!/home/backups/backup/backup_demo.sql  
    }
  • Configuració al servidor remot

Al directori /usr/lib/nagios/plugins afegir el fitxer check_openerp amb el següent contingut:

#!/usr/bin/python
# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (c) 2011 Zikzakmedia S.L. (http://zikzakmedia.com) All Rights Reserved.
#                       Jesús Martín <jmartin@zikzakmedia.com>
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from optparse import OptionParser
import time
import os

OK=0
WARNING=1
CRITICAL=2

def main():
    usage = "usage: %prog [options]"
    parser = OptionParser(usage)
    parser.add_option("-f", "--file", dest="file",
                    help="The name of the backup file to check.")
    (options, args) = parser.parse_args()

    if not options.file:
        print "Usage:\ncheck_backup -f <backup_filename>"
        exit()

    if not os.path.exists(options.file):
        print "Backup %s: CRITICAL! This file does not exist." % options.file
        return CRITICAL
        exit()
    today = time.time()
    file_date = os.path.getmtime(options.file)
    difference = today - file_date
    hours = difference / 3600
    days = hours / 24
    if difference > 172800:
        print "Backup %s: CRITICAL! This file is not updated from %s days ago." % (options.file, int(days))
        return CRITICAL
    elif difference > 86400:
        print "Backup %s: WARNING! This file is not updated from %s hours ago." % (options.file, int(hours))
        return WARNING
    print "Backup %s: OK!" % options.file 
    return OK

if __name__ == "__main__":
    exit(main())

Reiniciar ambdós servidors.

Configurar Nagios per escoltar per un port determinat

Com que no hi ha cap plugin específic per escoltar un servidor OpenERP en funcionament, el que farem serà escoltar el port de connexió habitual i suposar que no funciona si no hi ha contestació del servidor.

Configuració servidor Nagios

S'ha d'editar el fitxer /etc/nagios3/commands.cfg i afegir la següent definició de comanda:

# 'check_port' command definition
define command{
        command_name check_port
        command_line $USER1$/check_tcp -H $HOSTADDRESS$ -p $ARG1$
}

Configuració servidor MySQL per escoltar el port 3306

Si no volguessim obrir el port externament, una altra possibilitat és configurar nagios per a que escolti el port 3306 del servidor MySQL i suposar que no funciona si no hi ha contestació del servidor. Per fer-ho s'ha d'editar el fitxer de configuració de serveis del host on s'allotja el servidor (p.e. /etc/nagios3/conf.d/localhost_nagios2.cfg), per afegir el següent servei:

# check if 3306 port of MySQL is listening to
define service {
        use                     generic-service
        host_name               virtual_host
        service_description     MySQL
        check_command           check_port!3306
}

Monitoritzar bases de dades PostgreSQL

Per configurar nagios per a que escolti el port 5432 del servidor PostgreSQL i suposar que no funciona si no hi ha contestació del servidor, s'ha d'editar el fitxer de configuració de serveis del host on s'allotja el servidor (p.e. /etc/nagios3/conf.d/localhost_nagios2.cfg), per afegir el següent servei:

# check that PostgreSQL database is running
define service {
        use                     generic-service
        host_name               virtual_host
        service_description     PostgreSQL
        check_command           check_port!5432
}

Monitoritzar OpenERP

S'ha d'editar el fitxer de configuració de serveis del host on s'allotja el servidor (p.e. /etc/nagios3/conf.d/localhost_nagios2.cfg), per afegir el següent servei:

# check that OpenERP port is listening to
define service {
        use                     generic-service
        host_name               virtual_host
        service_description     OpenERP
        check_command           check_port!28061
}

I finalment s'ha de reiniciar el servidor nagios per a que comenci a fer el monitoreig:

$ sudo /etc/init.d/nagios3 restart

Nagios en 10 segons

/etc/nagios

contacts.cfg

define contact{
        contact_name                    usuari1
        alias                           Raimon Esteve
        service_notification_period     24x7
        host_notification_period        24x7
        service_notification_options    w,u,c,r
        host_notification_options       d,u,r
        service_notification_commands   notify-by-email
        host_notification_commands      host-notify-by-email
        email raimonesteve_arroba_gmail.com
        }

contactgroups.cfg

define contactgroup{
        contactgroup_name       zikzakmedia
        alias                   Webmasters zikzakmedia
        members                 usuari1, usuari2
        }

hosts.cfg

define host{
        use                     generic-host            ; Name of host template to use
        host_name               servidor1
        alias                   Servidor 1 Webstudio
        address                 84.XX.X.XXX
        check_command           check-host-alive
        max_check_attempts      5
        notification_interval   0
        notification_period     24x7
        notification_options    d,u,r
        }

hostgroups.cfg

define hostgroup{
        hostgroup_name  zikzakmedia_servers
        alias           Servidors Zikzakmedia
        contact_groups  zikzakmedia
        members         servidor1, servidor2, servidor3
        }

services.cfg

define service{
        use                             generic-service         ; Name of service template to use
        host_name                       servidor1
        service_description             HTTP
        is_volatile                     0
        check_period                    24x7
        max_check_attempts              3
        normal_check_interval           5
        retry_check_interval            1
        contact_groups                  zikzakmedia, jacintverdaguer
        notification_interval           0
        notification_period             24x7
        notification_options            w,u,c,r
        check_command                   check_http
        }

Serveis mes usuals:

  • check_ping!100.0,20%!500.0,60%
  • check_http
  • check_mysql (recordeu que ha d'estar obert el port Mysql a l'exterior de la màquina que voleu monitoritzar).
  • check_smtp
  • check_pop
 
servers/nagios.txt · Darrera modificació: 2011/12/07 15:21 per jmartin
 
Copyright: Zikzakmedia Llicència Creative Commons By-NC-SA
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki