Aller au contenu | Aller au menu | Aller à la recherche


Mot-clé - monitoring

Fil des billets - Fil des commentaires

lundi 13 mai 2013

Installation d'une sonde Nagios pour ESXi

Contexte

Pour des besoins concernant l’hébergement que propose ma société, j'ai été amené à gérer un serveur ESXi, du coup, il n'y a pas de raison de ne pas le surveiller, je dirai même que c'est encore plus nécessaire ! On a vite tendance à tomber dans les pièges de la virtualisation qui consistent à charger le serveur avec beaucoup VM s'imaginant que celui-ci augmente ces performances au fur et à mesure de la charge ... :D

Prérequis

Installation des paquets nécessaires

# yum install openssl-devel binutils perl perl-Nagios-Plugin perl-Class-MethodMaker mod_perl libuuid uuid-perl perl-XML-LibXML perl-XML-LibXML-Common

Installation du vSphere SDK Perl

Vous téléchargez le tar.gz : VMware-vSphere-Perl-SDK-5.1.0-780721.x86_64.tar.gz

$ tar xvfz VMware-vSphere-Perl-SDK-5.1.0-780721.x86_64.tar.gz

$ cd vmware-vsphere-cli-distrib

Il y a 2 variables à changer afin de permettre sans encombre l'installation du SDK :

my $httpproxy =0;
my $ftpproxy =0;
par :
my $httpproxy =1;
my $ftpproxy =1;

# ./vmware-install.pl

Problème UUID

Si vous avez encore un soucis d'une dépendance non résolue avec UUID, alors effectuez ceci :

# yum install gcc

$ wget http://search.cpan.org/CPAN/authors/id/C/CF/CFABER/UUID-0.03.tar.gz

$ tar xvfz UUID-0.03.tar.gz

$ cd UUID-0.03

# perl Makefile.PL

# make

# make install

Puis relancez ./vmware-install.pl

Installation du plugin Nagios

Télécharger le plugin ici :http://www.op5.org/community/plugin-inventory/op5-projects/check-esx-plugin

$ cd /usr/local/nagios/libexec/

$ wget http://git.op5.org/git/?p=nagios/op5plugins.git;a=blob_plain;f=check_vmware_api.pl;hb=HEAD

# chown nagios:nagios check_vmware_api.pl

# chmod 755 check_vmware_api.pl

Lançons la commande une première fois et nous obtenons ceci :

$ ./check_vmware_api.pl --help

check_vmware_api.pl 0.7.0

This nagios plugin is free software, and comes with ABSOLUTELY NO WARRANTY.
It may be used, redistributed and/or modified under the terms of the GNU
General Public Licence (see http://www.fsf.org/licensing/licenses/gpl.txt).

VMWare Infrastructure plugin

Usage: check_vmware_api.pl -D <data_center> | -H <host_name> [ -C <cluster_name> ] [ -N <vm_name> ]
    -u <user> -p <pass> | -f <authfile>
    -l <command> [ -s <subcommand> ] [ -T <timeshift> ] [ -i <interval> ]
    [ -x <black_list> ] [ -o <additional_options> ]
    [ -t <timeout> ] [ -w <warn_range> ] [ -c <crit_range> ]
    [ -V ] [ -h ]

 -?, --usage
   Print usage information
 -h, --help
   Print detailed help screen
 -V, --version
   Print version information
 --extra-opts=[section][@file]
   Read options from an ini file. See http://nagiosplugins.org/extra-opts
   for usage and examples.
 -H, --host=<hostname>
   ESX or ESXi hostname.
 -C, --cluster=<clustername>
   ESX or ESXi clustername.
 -D, --datacenter=<DCname>
   Datacenter hostname.
 -N, --name=<vmname>
   Virtual machine name.
 -u, --username=<username>
   Username to connect with.
 -p, --password=<password>
   Password to use with the username.
 -f, --authfile=<path>
   Authentication file with login and password. File syntax :
   username=<login>
   password=<password>
 -w, --warning=THRESHOLD
   Warning threshold. See
   http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT
   for the threshold format.
 -c, --critical=THRESHOLD
   Critical threshold. See
   http://nagiosplug.sourceforge.net/developer-guidelines.html#THRESHOLDFORMAT
   for the threshold format.
 -l, --command=COMMAND
   Specify command type (CPU, MEM, NET, IO, VMFS, RUNTIME, ...)
 -s, --subcommand=SUBCOMMAND
   Specify subcommand
 -S, --sessionfile=SESSIONFILE
   Specify a filename to store sessions for faster authentication
 -x, --exclude=<black_list>
   Specify black list
 -o, --options=<additional_options>
   Specify additional command options (quickstats, ...)
 -T, --timestamp=<timeshift>
   Timeshift in seconds that could fix issues with "Unknown error". Use values like 5, 10, 20, etc
 -i, --interval=<sampling period>
   Sampling Period in seconds. Basic historic intervals: 300, 1800, 7200 or 86400. See config for any changes.
   Supports literval values to autonegotiate interval value: r - realtime interval, h<number> - historical interval specified by position.
   Default value is 20 (realtime). Since cluster does not have realtime stats interval other than 20(default realtime) is mandatory.
 -M, --maxsamples=<max sample count>
   Maximum number of samples to retrieve. Max sample number is ignored for historic intervals.
   Default value is 1 (latest available sample).
 --trace=<level>
   Set verbosity level of vSphere API request/respond trace
 -t, --timeout=INTEGER
   Seconds before plugin times out (default: 30)
 -v, --verbose
   Show details for command-line debugging (can repeat up to 3 times)
Supported commands(^ - blank or not specified parameter, o - options, T - timeshift value, b - blacklist) :
    VM specific :
        * cpu - shows cpu info
            + usage - CPU usage in percentage
            + usagemhz - CPU usage in MHz
            + wait - CPU wait time in ms
            + ready - CPU ready time in ms
            ^ all cpu info(no thresholds)
        * mem - shows mem info
            + usage - mem usage in percentage
            + usagemb - mem usage in MB
            + swap - swap mem usage in MB
            + swapin - swapin mem usage in MB
            + swapout - swapout mem usage in MB
            + overhead - additional mem used by VM Server in MB
            + overall - overall mem used by VM Server in MB
            + active - active mem usage in MB
            + memctl - mem used by VM memory control driver(vmmemctl) that controls ballooning
            ^ all mem info(except overall and no thresholds)
        * net - shows net info
            + usage - overall network usage in KBps(Kilobytes per Second)
            + receive - receive in KBps(Kilobytes per Second)
            + send - send in KBps(Kilobytes per Second)
            ^ all net info(except usage and no thresholds)
        * io - shows disk I/O info
            + usage - overall disk usage in MB/s
            + read - read latency in ms (totalReadLatency.average)
            + write - write latency in ms (totalWriteLatency.average)
            ^ all disk io info(no thresholds)
        * runtime - shows runtime info
            + con - connection state
            + cpu - allocated CPU in MHz
            + mem - allocated mem in MB
            + state - virtual machine state (UP, DOWN, SUSPENDED)
            + status - overall object status (gray/green/red/yellow)
            + consoleconnections - console connections to VM
            + guest - guest OS status, needs VMware Tools
            + tools - VMWare Tools status
            + issues - all issues for the host
            ^ all runtime info(except con and no thresholds)
    Host specific :
        * cpu - shows cpu info
            + usage - CPU usage in percentage
                o quickstats - switch for query either PerfCounter values or Runtime info
            + usagemhz - CPU usage in MHz
                o quickstats - switch for query either PerfCounter values or Runtime info
            ^ all cpu info
                o quickstats - switch for query either PerfCounter values or Runtime info
        * mem - shows mem info
            + usage - mem usage in percentage
                o quickstats - switch for query either PerfCounter values or Runtime info
            + usagemb - mem usage in MB
                o quickstats - switch for query either PerfCounter values or Runtime info
            + swap - swap mem usage in MB
                o listvm - turn on/off output list of swapping VM's
            + overhead - additional mem used by VM Server in MB
            + overall - overall mem used by VM Server in MB
            + memctl - mem used by VM memory control driver(vmmemctl) that controls ballooning
                o listvm - turn on/off output list of ballooning VM's
            ^ all mem info(except overall and no thresholds)
        * net - shows net info
            + usage - overall network usage in KBps(Kilobytes per Second)
            + receive - receive in KBps(Kilobytes per Second)
            + send - send in KBps(Kilobytes per Second)
            + nic - makes sure all active NICs are plugged in
            ^ all net info(except usage and no thresholds)
        * io - shows disk io info
            + aborted - aborted commands count
            + resets - bus resets count
            + read - read latency in ms (totalReadLatency.average)
            + write - write latency in ms (totalWriteLatency.average)
            + kernel - kernel latency in ms
            + device - device latency in ms
            + queue - queue latency in ms
            ^ all disk io info
        * vmfs - shows Datastore info
            + (name) - free space info for datastore with name (name)
                o used - output used space instead of free
                o breif - list only alerting volumes
                o regexp - whether to treat name as regexp
                o blacklistregexp - whether to treat blacklist as regexp
                b - blacklist VMFS's
                T (value) - timeshift to detemine if we need to refresh
            ^ all datastore info
                o used - output used space instead of free
                o breif - list only alerting volumes
                o blacklistregexp - whether to treat blacklist as regexp
                b - blacklist VMFS's
                T (value) - timeshift to detemine if we need to refresh
        * runtime - shows runtime info
            + con - connection state
            + health - checks cpu/storage/memory/sensor status
                o listitems - list all available sensors(use for listing purpose only)
                o blackregexpflag - whether to treat blacklist as regexp
                b - blacklist status objects
            + storagehealth - storage status check
                o blackregexpflag - whether to treat blacklist as regexp
                b - blacklist status objects
            + temperature - temperature sensors
                o blackregexpflag - whether to treat blacklist as regexp
                b - blacklist status objects
            + sensor - threshold specified sensor
            + maintenance - shows whether host is in maintenance mode
            + list(vm) - list of VMWare machines and their statuses
            + status - overall object status (gray/green/red/yellow)
            + issues - all issues for the host
                b - blacklist issues
            ^ all runtime info(health, storagehealth, temperature and sensor are represented as one value and no thresholds)
        * service - shows Host service info
            + (names) - check the state of one or several services specified by (names), syntax for (names):<service1>,<service2>,...,<serviceN>
            ^ show all services
        * storage - shows Host storage info
            + adapter - list bus adapters
                b - blacklist adapters
            + lun - list SCSI logical units
                b - blacklist LUN's
            + path - list logical unit paths
                b - blacklist paths
            ^ show all storage info
        * uptime - shows Host uptime
                o quickstats - switch for query either PerfCounter values or Runtime info
        * device - shows Host specific device info
            + cd/dvd - list vm's with attached cd/dvd drives
                o listall - list all available devices(use for listing purpose only)
    DC specific :
        * cpu - shows cpu info
            + usage - CPU usage in percentage
                o quickstats - switch for query either PerfCounter values or Runtime info
            + usagemhz - CPU usage in MHz
                o quickstats - switch for query either PerfCounter values or Runtime info
            ^ all cpu info
                o quickstats - switch for query either PerfCounter values or Runtime info
        * mem - shows mem info
            + usage - mem usage in percentage
                o quickstats - switch for query either PerfCounter values or Runtime info
            + usagemb - mem usage in MB
                o quickstats - switch for query either PerfCounter values or Runtime info
            + swap - swap mem usage in MB
            + overhead - additional mem used by VM Server in MB
            + overall - overall mem used by VM Server in MB
            + memctl - mem used by VM memory control driver(vmmemctl) that controls ballooning
            ^ all mem info(except overall and no thresholds)
        * net - shows net info
            + usage - overall network usage in KBps(Kilobytes per Second)
            + receive - receive in KBps(Kilobytes per Second)
            + send - send in KBps(Kilobytes per Second)
            ^ all net info(except usage and no thresholds)
        * io - shows disk io info
            + aborted - aborted commands count
            + resets - bus resets count
            + read - read latency in ms (totalReadLatency.average)
            + write - write latency in ms (totalWriteLatency.average)
            + kernel - kernel latency in ms
            + device - device latency in ms
            + queue - queue latency in ms
            ^ all disk io info
        * vmfs - shows Datastore info
            + (name) - free space info for datastore with name (name)
                o used - output used space instead of free
                o breif - list only alerting volumes
                o regexp - whether to treat name as regexp
                o blacklistregexp - whether to treat blacklist as regexp
                b - blacklist VMFS's
                T (value) - timeshift to detemine if we need to refresh
            ^ all datastore info
                o used - output used space instead of free
                o breif - list only alerting volumes
                o blacklistregexp - whether to treat blacklist as regexp
                b - blacklist VMFS's
                T (value) - timeshift to detemine if we need to refresh
        * runtime - shows runtime info
            + list(vm) - list of VMWare machines and their statuses
            + listhost - list of VMWare esx host servers and their statuses
            + listcluster - list of VMWare clusters and their statuses
            + tools - VMWare Tools status
                b - blacklist VM's
            + status - overall object status (gray/green/red/yellow)
            + issues - all issues for the host
                b - blacklist issues
            ^ all runtime info(except cluster and tools and no thresholds)
        * recommendations - shows recommendations for cluster
            + (name) - recommendations for cluster with name (name)
            ^ all clusters recommendations
    Cluster specific :
        * cpu - shows cpu info
            + usage - CPU usage in percentage
            + usagemhz - CPU usage in MHz
            ^ all cpu info
        * mem - shows mem info
            + usage - mem usage in percentage
            + usagemb - mem usage in MB
            + swap - swap mem usage in MB
                o listvm - turn on/off output list of swapping VM's
            + memctl - mem used by VM memory control driver(vmmemctl) that controls ballooning
                o listvm - turn on/off output list of ballooning VM's
            ^ all mem info(plus overhead and no thresholds)
        * cluster - shows cluster services info
            + effectivecpu - total available cpu resources of all hosts within cluster
            + effectivemem - total amount of machine memory of all hosts in the cluster
            + failover - VMWare HA number of failures that can be tolerated
            + cpufainess - fairness of distributed cpu resource allocation
            + memfainess - fairness of distributed mem resource allocation
            ^ only effectivecpu and effectivemem values for cluster services
        * runtime - shows runtime info
            + list(vm) - list of VMWare machines in cluster and their statuses
            + listhost - list of VMWare esx host servers in cluster and their statuses
            + status - overall cluster status (gray/green/red/yellow)
            + issues - all issues for the cluster
                b - blacklist issues
            ^ all cluster runtime info
        * vmfs - shows Datastore info
            + (name) - free space info for datastore with name (name)
                o used - output used space instead of free
                o breif - list only alerting volumes
                o regexp - whether to treat name as regexp
                o blacklistregexp - whether to treat blacklist as regexp
                b - blacklist VMFS's
                T (value) - timeshift to detemine if we need to refresh
            ^ all datastore info
                o used - output used space instead of free
                o breif - list only alerting volumes
                o blacklistregexp - whether to treat blacklist as regexp
                b - blacklist VMFS's
                T (value) - timeshift to detemine if we need to refresh


Copyright (c) 2008 op5


Après un test rapide, nous obtenons une erreur de ce type :
CHECK_VMWARE_API.PL CRITICAL - Server version unavailable at ...
La vérification du certificat pose problème, si vous ne voulez pas le passer en paramètre, utiliser cette option :
--no-certificate-checking
ou rajoutez ceci au début du script perl :
$ENV{PERL_LWP_SSL_VERIFY_HOSTNAME} = 0;

Configuration de Nagios

Nous allons stocker les identifiants de connexions de l'ESXi dans le fichiers etc/resource.cfg qui ne doit pas être accessible via les CGI

$USER09$=username
$USER10$=password

Ensuite reste à configurer les commandes :

# 'check_esx_cpu' command definition

define command{
        command_name check_esx_cpu
        command_line $USER1$/check_vmware_api.pl -H $HOSTADDRESS$ -u $USER09$ -p $USER10$ -l cpu -s usage -w $ARG1$ -c $ARG2$
        }
 
# 'check_esx_mem' command definition
define command{
        command_name check_esx_mem
        command_line $USER1$/check_vmware_api.pl -H $HOSTADDRESS$ -u $USER09$ -p $USER10$ -l mem -s usage -w $ARG1$ -c $ARG2$
        }
 
# 'check_esx_net' command definition
define command{
        command_name check_esx_net
        command_line $USER1$/check_vmware_api.pl -H $HOSTADDRESS$ -u $USER09$ -p $USER10$ -l net -s usage -w $ARG1$ -c $ARG2$
        }
 
# 'check_esx_runtime' command definition
define command{
        command_name check_esx_runtime
        command_line $USER1$/check_vmware_api.pl -H $HOSTADDRESS$ -u $USER09$ -p $USER10$ -l runtime -s status
        }
 
# 'check_esx_ioread' command definition
define command{
        command_name check_esx_ioread
        command_line $USER1$/check_vmware_api.pl -H $HOSTADDRESS$ -u $USER09$ -p $USER10$ -l io -s read -w $ARG1$ -c $ARG2$
        }
 
# 'check_esx_iowrite' command definition
define command{
        command_name check_esx_iowrite
        command_line $USER1$/check_vmware_api.pl -H $HOSTADDRESS$ -u $USER09$ -p $USER10$ -l io -s write -w $ARG1$ -c $ARG2$
        }

Puis la traditionnelle configuration :

define host{

    use              generic-host
    host_name    myesx1
    alias             myesx1
    address        XXX.XXX.XXX.XXX
}

Et la définition des services :
 


define service{
        use                                  generic-service
        host_name                        myesx1
        service_description            ESXi CPU Load
        check_command                check_esx_cpu!80!90
        }
 
define service{
        use                                  generic-service
        host_name                        myesx1
        service_description            ESXi Memory usage
        check_command                check_esx_mem!80!90
        }
 
define service{
        use                                  generic-service
        host_name                        myesx1
        service_description            ESXi Network usage
        check_command                check_esx_net!102400!204800
        }
 
define service{
        use                                  generic-service
        host_name                        myesx1
        service_description            ESXi Runtime status
        check_command                check_esx_runtime
        }
 
define service{
        use                                 generic-service
        host_name                       myesx1
        service_description           ESXi IO read
        check_command               check_esx_ioread!40!90
        }
 
define service{
        use                                 generic-service
        host_name                       myesx1
        service_description           ESXi IO write
        check_command               check_esx_iowrite!40!90
        }

Conclusion

Voilà, le tour est joué, vous avez un début de supervision de votre serveur ESX ! Pour avoir un monitoring plus fin, je vous invite à parcourir cette documentation : http://www.op5.com/how-to/monitoring-vmware-esx-3-x-esxi-vsphere-4-and-vcenter-server

À lire également :

lundi 18 mars 2013

check_file_content : Plugin Nagios tout terrain pour consulter le contenu d'un fichier

Présentation

Ce projet est un projet sous licence GPL v2. Cette commande est un plugin pour Nagios 3.x, développé en PERL et oui, on prend les mêmes et on recommence ;) )

Son objectif est de permettre de consulter un fichier local ou sur le réseau et de retourner des alertes selon la présence ou non d'une suite de mots passés en paramètre. Dans un premier temps, le plugin ne prend en compte que le protocol samba, mais ça ne devrait pas être compliqué d'en intégrer d'autres.

Ce plugin permet de :

  • Retourner le nombre d'occurrences d'un mot ou d'une expression contenue dans un fichiers local ou distant.Des alertes peuvent être levées si le nombre d'occurrences est inclue un minimum de fois ou à l'inverse s'il est exclu du fichier (ou présent au maximum n fois). Les limites étant définies par les seuils critique et warning passés en paramètres

Pour le reste, je vous laisse parcourir le fichier, tout doit être dedans ;)  et assez explicite ! Sinon, vous savez où me trouver ;)

Installation

Vous l'aurez compris, pour l'utiliser, il suffit d'un serveur Nagios (Installer Nagios sur CentOS sans RPM) sur lequel vous aurez installé les packages suivant :

# yum install perl perl-Filesys-SmbClient

Une fois fais, il ne vous reste qu'à placer check_file_content.pl dans le répertoire libexec de votre arborescence Nagios :

# chmod +x check_file_content.pl

Et voilà, le tour est joué !

$ perl check_file_content.pl --help

Check_file_content for Nagios, version 1.0
GPL licence, (c)2013 Slobberbone

Site http://www.slobberbone.net

Usage: check_file_content.pl -f <file> -P <protocol> [-u <user> -p <password> -d <domain>] -s <"search_expression"> -t <check_type> [-w <warn_level> -c <crit_level>] -V
-h, --help
print this help message
-f, --filepath=PATHTOFILENAME
full path to file to analyze
-P, --protocol=PROTOCOL
protocol used to acess file :
LOCAL for local file (default),
SMB for CIFS file
-u, --user=USER
user to login
-p, --password=PASSWORD
password
-d, --domain=DOMAIN
domain name
-s, --search="EXPRESSION", if empty looks for lines present in the file
expression to search in the specified file
-t, --check_type=TYPE
Type of search :
INCLUDE for include at least the critical option, then the warning option
EXCLUDE for exclude with a maximum of founded expression smaller than critical option
-w, --warn=INTEGER
number that will cause a warning
-c, --critical=INTEGER
number that will cause an error (Default: 1)
-V, --version
prints version number
Note :
The script will return
* With warn and critical options:
OK if we are able to found expression and the count result respect <warn_level> and depending check_type,
WARNING if we are able to found expression and the count result unrespect <warn_level> and depending check_type,
CRITICAL if we are able to found expression and the count result unrespect <crit_level> and depending check_type,
UNKNOWN if we aren't able to read the file

Configuration

Pour que ce plugin soit opérationnel avec notre serveur de supervision Nagios (ou Shinken), il faut ajouter dans le fichier commands.cfg :

# 'check_file_content' command definition
define command{
    command_name    check_file_content
    command_line    $USER1$/check_file_content.pl -f $ARG1$ -P $ARG2$ -u $ARG3$ -p $ARG4$ -d $ARG5$ -t $ARG6$ -s $ARG7$ -w $ARG8$ -c $ARG9$
    }

Puis, il ne vous reste plus qu'à l'appeler de la manière suivante :

define service{
    use            generic-service
    host_name        my_file_server
    service_description    Include at least 4 instances of "Provider : OK" in mytest.log
    check_command        check_file_content!smb://server/dir/file.log!SMB!user!password!domain!INCLUDE!"Provider : OK"!5!3
    normal_check_interval    10
}

Et voilà, il ne reste plus qu'à modifier ce projet pour vos propres besoins ! Pour ça, direction SourceForge.net !

Si vous avez des questions, les commentaires sont ouverts !

À lire également :

vendredi 1 mars 2013

check_bdd_request : Plugin Nagios tout terrain pour requêter des bases de données

Bonjour à tous, j'ai eu un besoin particulier concernant le monitoring en place au sein d'Opti-Time. du coup, ni une, ni deux après une brève recherche, je n'ai pas trouvé mon bonheur, alors hier soir , j'ai pris mes 2 mains et hop au boulot ! Ce fût rapide et vous le verrez il n'y a rien d'extraordinaire ! Mais voilà que ça a donnée naissance à un projet de plus : http://www.slobberbone.net/dotclear/index.php?pages/check_bdd_request

Je vous recopie la page ici même pour en faire profiter un maximum ;) !

Présentation

Ce projet est un projet sous licence GPL v2. Cette commande est un plugin pour Nagios 3.x, développé en PERL.

Son objectif est de permettre d’exécuter n'importe quelle requête à un serveur de base de données. Dans un premier temps, cela ne fonctionne qu'avec un serveur MySQL, mais ça ne doit aps être compliqué de faire ce qu'il faut pour PostgreSQL, Oracle, etc ...

Ce plugin permet 2 choses pour le moment :

  • Retourner une information dans Nagios sans qu'elle est un impact en terme d'alerte (check_type=TEXT). Le but est de remonter par exemple la version d'un logiciel stockée en base, ou tout autre indicateur quelconque qu'il soit un chiffre ou du texte.
  • Retourner un compteur de résultat de la requête SQL exécutée (check_type=NUMERIC). D'autres plugin Nagios font déjà ce travail, hors j'ai un premier besoin qui est de pouvoir lever une alerte alors que nous passons les seuils fixés, ou à l'inverse, lorsque la valeur n'atteint pas le seuil voulu. Parcourant le résultat, cette commande pourra très facilement être adaptée pour traiter des résultats plus complexes (prochaines versions).

Pour le reste, je vous laisse parcourir le fichier, tout doit être dedans ;)  et assez explicite ! Sinon, vous savez où me trouver ;)

Installation

Vous l'aurez compris, pour l'utiliser, il suffit d'un serveur Nagios (Installer Nagios sur CentOS sans RPM) sur lequel vous aurez installé les packages suivant :

# yum install perl perl-DBD-MySQL perl-DBI

Une fois fais, il ne vous reste qu'à placer check_bdd_request.pl dans le répertoire libexec de votre arborescence Nagios :

# chmod +x check_bdd_request.pl

Et voilà, le tour est joué !

$ perl check_bdd_request.pl --help

Check_MySQL_request for Nagios, version 1.0
GPL licence, (c)2013 Slobberbone

Site http://www.slobberbone.net

Usage: ./check_bdd_request.pl -H <host> -u <user> -p <password> -d <database> -P <port> -q request -t check_type -o <operator> [-w <warn_level> -c <crit_level> -T <timeout>] -V
-h, --help
print this help message
-H, --hostname=HOST
name or IP address of MySQL server
-u, --user=USER
mysql user to login
-p, --password=PASSWORD
mysql password
-d, --database=DATABASE
mysql database name
-P, --port=PORT
Http port
-q, --request="REQUEST"
Request to execute on the server
-t, --check_type=TYPE
Type of return :
NUMERIC,
TEXT
-o, --operator=OPERATOR
Operator :
EQ for =,
LT for <,
GT for >,
LE for <=,
GE for >=,
DIF for !=
-w, --warn=INTEGER
number that will cause a warning completed by the OPERATOR
-1 for no warning
-c, --critical=INTEGER
number that will cause an error completed by the OPERATOR
-T, --timeout=INTEGER
timeout in seconds (Default: 15)
-V, --version
prints version number
Note :
The script will return
* With warn and critical options:
OK if we are able to connect to the MySQL server and #request count result respect <warn_level>,
WARNING if we are able to connect to the MySQL server and #request count result unrespect <warn_level>,
CRITICAL if we are able to connect to the MySQL server and #request count result unrespect <crit_level>,
UNKNOWN if we aren't able to connect to the MySQL server

Configuration

Pour que ce plugin soit opérationnel avec notre serveur de supervision Nagios (ou Shinken), il faut ajouter dans le fichier commands.cfg :

# 'check_bdd_request_numeric' command definition
define command{
    command_name    check_bdd_request_numeric
    command_line    $USER1$/check_bdd_request.pl -H $HOSTADDRESS$ -u $ARG1$ -p $ARG2$ -d $ARG3$ -P $ARG4$ -q $ARG5$ -t $ARG6$ -o $ARG7$ -w $ARG8$ -c $ARG9$
    }

# 'check_bdd_request_text' command definition
define command{
    command_name    check_bdd_request_text
    command_line    $USER1$/check_bdd_request.pl -H $HOSTADDRESS$ -u $ARG1$ -p $ARG2$ -d $ARG3$ -P $ARG4$ -q $ARG5$ -t $ARG6$
    }

Puis, il ne vous reste plus qu'à l'appeler de la manière suivante :

define service{
    use            generic-service
    host_name        my_bdd_server
    service_description    A text value for display information like a version for example
    check_command        check_bdd_request_text!user!password!database!3307!"Select column_name from my table where row_text='value'"!TEXT
    normal_check_interval    60
}

define service{
    use            generic-service
    host_name        my_bdd_server
    service_description    A numeric value for display information and compare with operator to the Warning or Critical values
    check_command        check_bdd_request_text!user!password!database!3307!"Select column_name from my table where row_text='value'"!NUMERIC!LT!2!5
    normal_check_interval    60
}

Et voilà, il ne reste plus qu'à modifier ce projet pour vos propres besoins ! Pour ça, direction SourceForge.net !
Pour le reste, les commentaires sont ouverts sur la page du projet !

À lire également :

lundi 16 juillet 2012

Installation de NagVis sur CentOS

Aujourd'hui, je vous propose d'installer NagVis 1.6 ! Cette procédure suit celle précédemment rédigée : Installation de Nagios dur CentOS

NagVis_accueil

Installation des prérequis

Comme d'habitude, on installe les paquets qui nous manquent, j'avais déjà installer le dépôt de RPMForge, si besoin, voici la procédure : http://wiki.centos.org/AdditionalResources/Repositories/RPMForge/#head-5aabf02717d5b6b12d47edbc5811404998926a1b !

$ su -

# yum install php php-mysql
# yum install graphviz rsync

Et voilà,passons à l'installation de NagVis.

Installation de NagVis

Nagios étant initialement installé dans /usr/local/nagios, nous allons continuer de mettre les autres composants à coté !

# cd /usr/local/
# wget http://downloads.sourceforge.net/project/nagvis/NagVis%201.6/nagvis-1.6.6.tar.gz?r=http%3A%2F%2Fwww.nagvis.org%2Fdownloads&ts=1342001584&use_mirror=kent

Une fois téléchargé, on décompresse l'archive ( NagVis ) :


# tar xvfz nagvis-1.6.6.tar.gz
# mv nagvis-1.6.6 nagvis

Nous nous retrouvons avec Nagvis, prêt à être compilé dans /usr/local/nagvis/ !

Configuration de NagVis

Attention, c'est ici que ça devient extrêmement technique ^^ ! Il faut juste suivre les questions du script en donnant le chemin de Nagios (/usr/local/nagios) et de bien demander de modifier les fichiers de configuration de Nagios ainsi que de modifier la configuration d'Apache.

# cd nagvis
# ./install.sh

Vous devriez avoir un résultat du genre :

| Installation complete                                                                                                                                             |
|                                                                                                                                                                               |
| You can safely remove this source directory.                                                                                                          |
|                                                                                                                                                                               |
| For later update/upgrade you may use this command to have a faster update:                                                    |
| ./install.sh -n /usr/local/nagios -p /usr/local/nagvis -b ndo2db -u apache -g apache -w /etc/httpd/conf.d -a y         |
|                                                                                                                                                                               |
| What to do next?                                                                                                                                                    |
| - Read the documentation                                                                                                                                      |
| - Maybe you want to edit the main configuration file?                                                                                             |
|   Its location is: /usr/local/nagvis/etc/nagvis.ini.php                                                                                                |
| - Configure NagVis via browser                                                                                                                               |
|   <http://localhost/nagvis/config.php>                                                                                                                   |
| - Initial admin credentials:                                                                                                                                      |
|     Username: admin                                                                                                                                               |
|     Password: admin                                                                                                                                                |   

En ce qui me concerne, j'ai dû modifier directement dans le fichier de configuration de NagVis, les infos pour attaquer la base de données de Nagios alimentée par NDO.

# vi /usr/local/nagvis/etc/nagvis.ini.php

Voici les infos que j'ai modifié (retrouvée dans le fichier ndo2db.cfg) :

;statushost=""
; hostname for NDO-db
dbhost="momn_nom_de_serveur"
; portname for NDO-db
;dbport=3306
; database name for NDO-db
;dbname="nagios"
; username for NDO-db
dbuser="nagios"
; password for NDO-db
dbpass="nagios"
; prefix for tables in NDO-db
dbprefix="npc_"
; instance name for tables in NDO-db
;dbinstancename="default"
; maximum delay of the NDO Database in seconds
;maxtimewithoutupdate=180
; path to the cgi-bin of this backend
;htmlcgi="/nagios/cgi-bin"


Voilà, à priori, après avoir paramétré via la page http://localhost/nagvis/config.php (et notamment définir NDO comme plugin BDD), une modification des droits pour l'utilisateur nagios est nécessaire, puis redémarrage d'Apache et c'est bon !

# chown -Rf nagios:nagios /usr/local/nagvis/
# /etc/init.d/httpd restart

J'ai cependant eu un problème, mes tables alimentées par NDO, n'étaient pas confirme à ce qu'attendait NagVis ...

Il suffit donc d'exécuter via la commande $ mysql -u nagios -pnagios sur les tables de ndo :

ALTER TABLE npc_eventhandlers ADD long_output TEXT NOT NULL after output;
ALTER TABLE npc_hostchecks ADD long_output TEXT NOT NULL after output;
ALTER TABLE npc_hoststatus ADD long_output TEXT NOT NULL after output;
ALTER TABLE npc_notifications ADD long_output TEXT NOT NULL after output;
ALTER TABLE npc_servicechecks ADD long_output TEXT NOT NULL after output;
ALTER TABLE npc_servicestatus ADD long_output TEXT NOT NULL after output;
ALTER TABLE npc_statehistory ADD long_output TEXT NOT NULL after output;
ALTER TABLE npc_systemcommands ADD long_output TEXT NOT NULL after output;

Et voilà ! NagVis est fonctionnel !

En ce qui me concerne, j'ai voulu avoir accès à NagVis depuis l'interface de Nagios (modifiée avec le thème Vautour). Pour cela, un peu de php/html de base afin de modifier les fichiers présent dans /usr/local/nagios/share/ et notamment le menu.html ;)

Seul hic, comment utiliser une même authentification ?

Authentification Nagios / NagVis

Via Apache, comme pour Nagios !

# vi /etc/httpd/conf.d/nagvis.cnf

On ajoute ceci :

AuthName "NagVis Access"
AuthType Basic
AuthUserFile /usr/local/nagios/etc/htpasswd.users
Require valid-user

...

SetEnv REMOTE_USER guest
RequestHeader set Cookie "nagvis_session=1"

On recharge la configuration Apache :

# /etc/init.d/httpd reload

Et le tour est joué ! (par défaut on indique que tout utilisateur utilise le login guest, si vous créez l'utilisateur dans NagVis, les droits lui seront alors appliqués !

NagVis_ex1

Aller plus loin ...

Au cas où, on peut ajouter des icônes, des gadgets, des map personnalisées, etc ... Donc voici quelques liens intéressants que je complèterai si besoin :

- Pack d'icônes : http://exchange.nagvis.org/exchange/func-finishdown/9/

À lire également :

jeudi 28 juillet 2011

Installation de Nagios sur CentOS sans RPM

Depuis le temps que j'en parlais ... voilà enfin ma procédure d'installation de Nagios 3.2 sous CentOS 5.CentOS
Alors tout d'abord, à l'époque il n'y avait pas de rpm (j'ai trouvé il y a peu un dépôt ... j'y reviendrais dans un autre billet). Donc compilation à la main !

Ensuite, les puristes crierons lorsqu'ils verront où j'installe Nagios ... le but était d'avoir quelque chose d'opérationnel assez rapidement. Faire mieux étant remis à plus tard. Si vous avez des modifications à apporter à cette procédure, je vous invite à laisser un commentaire ! Je la compléterai avec joie ! :)

Préparation de la machine

Avant toute chose, penser à bien configurer votre parefeu et SELinux. Pour un premier test, il faut désactiver le tout ! Pour le parefeu :
service iptables stop

Pour SELinux : vi /etc/selinux/config

# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
# enforcing - SELinux security policy is enforced.
# permissive - SELinux prints warnings instead of enforcing.
# disabled - SELinux is fully disabled.
SELINUX=disabled
# SELINUXTYPE= type of policy in use. Possible values are:
# targeted - Only targeted network daemons are protected.
# strict - Full SELinux protection.
SELINUXTYPE=targeted

Installation des pré-requis

Passage en root
su -

Installation prérequis
yum install gcc httpd mysql-server mysql-devel openssl yum install gd gd-devel libpng libpng-devel libjpeg libjpeg-devel zlib zlib-devel

Téléchargement des sources Nagios
cd /usr/local/
wget http://prdownloads.sourceforge.net/sourceforge/nagios/nagios-3.2.1.tar.gz
wget http://prdownloads.sourceforge.net/sourceforge/nagiosplug/nagios-plugins-1.4.14.tar.gz
wget http://prdownloads.sourceforge.net/sourceforge/nagios/nrpe-2.12.tar.gz
wget http://prdownloads.sourceforge.net/sourceforge/nagios/ndoutils-1.4b9.tar.gz

Décompression de Nagios Core
tar xfvz nagios-3.2.1.tar.gz
cd nagios-3.2.1/

Création du groupe et utilisateur nagios
groupadd nagios
groupadd nagcmd
useradd nagios -g nagios,nagcmd

Installation de Nagios

Nagios

Compilation de Nagios Core
./configure --prefix=/usr/local/nagios --enable-mysql --disable-pgsql --with-ndo2db-user=nagios --with-ndo2db-group=nagios --with-command-group=nagcmd

Résultats :

#*** Configuration summary for nagios 3.2.1 03-09-2010 ***:
#
# General Options:
# -
# Nagios executable: nagios
# Nagios user/group: nagios,nagios
# Command user/group: nagios,nagcmd
# Embedded Perl: no
# Event Broker: yes
# Install ${prefix}: /usr/local/nagios/
# Lock file: ${prefix}/var/nagios.lock
# Check result directory: ${prefix}/var/spool/checkresults
# Init directory: /etc/rc.d/init.d
# Apache conf.d directory: /etc/httpd/conf.d
# Mail program: /bin/mail
# Host OS: linux-gnu
#
# Web Interface Options:
#
# HTML URL: http://localhost/nagios/
# CGI URL: http://localhost/nagios/cgi-bin/
# Traceroute (used by WAP): /bin/traceroute
#
#
#Review the options above for accuracy. If they look okay,
#type 'make all' to compile the main program and CGIs.

make all

Résultats :

#*** Compile finished ***
#
#If the main program and CGIs compiled without any errors, you
#can continue with installing Nagios as follows (type 'make'
#without any arguments for a list of all possible options):
#
# make install
# - This installs the main program, CGIs, and HTML files
#
# make install-init
# - This installs the init script in /etc/rc.d/init.d
#
# make install-commandmode
# - This installs and configures permissions on the
# directory for holding the external command file
#
# make install-config
# - This installs *SAMPLE* config files in /usr/local/nagios//etc
# You'll have to modify these sample files before you can
# use Nagios. Read the HTML documentation for more info
# on doing this. Pay particular attention to the docs on
# object configuration files, as they determine what/how
# things get monitored!
#
# make install-webconf
# - This installs the Apache config file for the Nagios
# web interface
#
#
#*** Support Notes *******************************************
#
#If you have questions about configuring or running Nagios,
#please make sure that you:
#
# - Look at the sample config files
# - Read the HTML documentation
# - Read the FAQs online at http://www.nagios.org/faqs
#
#before you post a question to one of the mailing lists.
#Also make sure to include pertinent information that could
#help others help you. This might include:
#
# - What version of Nagios you are using
# - What version of the plugins you are using
# - Relevant snippets from your config files
# - Relevant error messages from the Nagios log file
#
#For more information on obtaining support for Nagios, visit:
#
# http://www.nagios.org/support/
#
#*************************************************************

make install
make install-init
make install-commandmode
make install-config
make install-webconf

Démarrage à  vide de Nagios
/etc/init.d/nagios start

Résultat :

#Starting nagios: done.

Installation et Configuration de MySQL si non installée

yum install mysql-server mysql
/etc/init.d/mysqld start
/usr/bin/mysql_secure_installation

Préparation de MySQL

Ici l'option "-proot" où "root" est mon mot de passe pour l'utilisateur root ... il va sans dire que ce n'est qu'un exemple :-) mysql -u root -proot

Résultats :

#Welcome to the MySQL monitor. Commands end with ; or \g.
#Your MySQL connection id is 7
#Server version: 5.0.77 Source distribution
#
#Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> create database nagios;

#Query OK, 1 row affected (0.01 sec)

mysql> grant all on nagios.* to 'nagios'@'localhost' identified by 'nagios';

#Query OK, 0 rows affected (0.00 sec)

mysql> flush privileges;

#Query OK, 0 rows affected (0.00 sec)

mysql> quit

#Bye

Installation du module base de données NDO
architecture_ndo.jpg

Décompression de NDO
cd /usr/local/
tar xvfz ndoutils-1.4b9.tar.gz
cd ndoutils-1.4b9

Compilation NDO
./configure

Résultats :

#*** Configuration summary for ndoutils 1.4b9 10-27-2009 ***:
#
# General Options:
# -
# NDO2DB user: nagios
# NDO2DB group: nagios
#
#
#Review the options above for accuracy. If they look okay,
#type 'make' to compile the NDO utilities.

make

Mise en place de la librairie NDO dans Nagios
cp src/ndomod-3x.o /usr/local/nagios/bin/ndomod.o
cp src/ndo2db-3x /usr/local/nagios/bin/ndo2db

Création base Nagios
cd db
./installdb -u nagios -p nagios -h localhost -d nagios

Résultats :

#DBD::mysql::db do failed: Table 'nagios.nagios_dbversion' doesn't exist at ./installdb line 51.
#** Creating tables for version 1.4b9
# Using mysql.sql for installation...
#** Updating table nagios_dbversion
#Done!

cp /usr/local/ndoutils-1.4b9/config/ndo2db.cfg-sample /usr/local/nagios/etc/ndo2db.cfg
cp /usr/local/ndoutils-1.4b9/config/ndomod.cfg-sample /usr/local/nagios/etc/ndomod.cfg

Éditer les fichiers de configuration
cd /usr/local/nagios/etc/
vi ndo2db.cfg

Dans ce fichier vous renseignerez l'utilisateur de mysql :

# SOCKET TYPE
# This option determines what type of socket the daemon will create
# an accept connections from.
# Value:
# unix = Unix domain socket (default)
# tcp = TCP socket

#socket_type=unix
socket_type=tcp
...
# DATABASE USERNAME/PASSWORD
# This is the username/password that will be used to authenticate to the DB.
# The user needs at least SELECT, INSERT, UPDATE, and DELETE privileges on
# the database.

db_user=nagios
db_pass=nagios

vi ndomod.cfg
Modifier le type socket :

...
#output_type=file
output_type=tcpsocket
#output_type=unixsocket
...
#output=/usr/local/nagios/var/ndo.dat
output=127.0.0.1
#output=/usr/local/nagios/var/ndo.sock

vi nagios.cfg

Modifier le partie event_broker (/event_broker pour rechercher sous Vi)
-
# EVENT BROKER OPTIONS
# Accepte des datas de l'extérieur (dont NDO)
# Controls what (if any) data gets sent to the event broker.
# Values: 0 = Broker nothing
# -1 = Broker everything
# <other> = See documentation
event_broker_options=-1
broker_module=/usr/local/nagios/bin/ndomod.o config_file=/usr/local/nagios/etc/ndomod.cfg
-

Arrêt de Nagios
/etc/init.d/nagios stop

Démarrage du deamon NDO2DB
/usr/local/nagios/bin/ndo2db -c /usr/local/nagios/etc/ndo2db.cfg

Démarrage de Nagios
/etc/init.d/nagios start

Vérification du démarrage de Nagios
vi /usr/local/nagios/var/nagios.log
NB : Si Code 127 : Nagios Plugin non compilé

Installation des plugins Nagios

Décompression de Nagios Plugin
cd /usr/local
tar xvfz nagios-plugins-1.4.14.tar.gz

Compilation de Nagios Plugin
cd nagios-plugins-1.4.14
./configure

Résultats :

# --with-apt-get-command:
# --with-ping6-command: /bin/ping6 -n -U -w %d -c %d %s
# --with-ping-command: /bin/ping -n -U -w %d -c %d %s
# --with-ipv6: yes
# --with-mysql: /usr/bin/mysql_config
# --with-openssl: yes
# --with-gnutls: no
# --enable-extra-opts: no
# --with-perl: /usr/bin/perl
# --enable-perl-modules: no
# --with-cgiurl: /nagios/cgi-bin
# --with-trusted-path: /bin:/sbin:/usr/bin:/usr/sbin
# --enable-libtap: no

make
make install

Vérification des modules
ls /usr/local/nagios/libexec/
/etc/init.d/nagios restart

Changer authentification
vi /usr/local/nagios/etc/cgi.cfg
Exemple de configuration :

...
use_authentication=1
use_ssl_authentication=0
...

Pour le reste voici une brève explication :

  • authorized_for_system_information : indiquent quels sont les utilisateurs pouvant voir l'état des services
  • authorized_for_configuration_information : indiquent quels sont les utilisateurs pouvant voir la configuration de serveur Nagios
  • authorized_for_system_commands : indiquent quels sont les utilisateurs pouvant exécuter des commandes systèmes au travers de l'interface de Nagios
  • authorized_for_all_services : indiquent quels sont les utilisateurs pouvant voir l'état de tout les services (par défaut, on voit uniquement les services pour lesquels l'utilisateur est une personne de contact)
  • authorized_for_all_hosts : idem que ci-dessus mais pour les hôtes (les machines)
  • authorized_for_all_service_commands : indiquent quels sont les utilisateurs pouvant exécuter des commandes pour tous les services (par défaut, on peut exécuter des commandes uniquement sur les services pour lesquels l'utilisateur est une personne de contact)
  • authorized_for_all_host_commands : idem que ci-dessus mais pour les hôtes (les machines)

Je vous laisse le soin de compléter la configuration des personnes autorisées ou non à agir sur l'interface de Nagios !

Déclarer le user nagiosadmin
htpasswd -c /usr/local/nagios/etc/htpasswd.users nagiosadmin

NB :Pour ajouter un utilisateur
htpasswd /usr/local/nagios/etc/htpasswd.users <username>

Changer le propriétaire du répertoire Nagios
chown -Rf nagios:nagios /usr/local/nagios/

Redemarrer le module NDO et Nagios
ps -e | grep ndo2db
kill PID
/usr/local/nagios/bin/ndo2db -c /usr/local/nagios/etc/ndo2db.cfg
/etc/init.d/nagios restart

Modification du script de démarrage de nagios pour prendre en compte ndo2db
vi /etc/init.d/nagios

-
...
start) echo -n "Starting nagios:"
$NagiosBin -v $NagiosCfgFile > /dev/null 2>&1;
if $? -eq 0; then
########################################################################
###############################A Ajouter################################
su - $NagiosUser -c "/usr/local/nagios/bin/ndo2db -c /usr/local/nagios/etc/ndo2db.cfg"
########################################################################
su - $NagiosUser -c "touch $NagiosVarDir/nagios.log $NagiosRetentionFile"
...
stop)
echo -n "Stopping nagios: "
pid_nagios
killproc_nagios nagios
########################################################################
###############################A Ajouter################################
su - $NagiosUser -c "skill ndo2db"
########################################################################
...
-

Installation du skin Vautour
J'utilise un skin très agréable nommé Vautour car il faut avouer que l'interface de base de Nagios est repoussante ... Comme tout projet il faut savoir le vendre et celà passe par l'esthétique !
wget http://www.be-root.com/downloads/nagios/vautour/vautour_style.zip
unzip vautour_style.zip -d /usr/local/nagios/share/

Merci à l'équipe de Be-Root !

Voici un exemple :
Vautour

Et voilà votre installation de Nagios doit être prête ! Il ne reste plus qu'à configurer notre nagios pour qu'il surveille nos serveurs ! Mais ça c'est dans un prochain billet ;) !

Rappel

Vérifier la configuration
/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg

Faire des propositions d'optimisation (juste pour avoir la commande ;) )
/usr/local/nagios/bin/nagios -s /usr/local/nagios/etc/nagios.cfg

À lire également :