From dbceba8b64d5b482b771c02b02691f814a11b8ed Mon Sep 17 00:00:00 2001 From: Antoine Nguyen Date: Mon, 11 Mar 2013 13:07:59 +0100 Subject: [PATCH 001/458] Perl code refactoring. * New centreon perl library * Rewritten script (purge, logAnalyser) Conflicts: www/install/sql/centstorage/Update-CSTG-2.4.1_to_2.4.2.sql --- centreon/lib/perl/centreon/db.pm | 283 +++++++++++ centreon/lib/perl/centreon/lock.pm | 141 ++++++ centreon/lib/perl/centreon/logger.pm | 129 +++++ centreon/lib/perl/centreon/script.pm | 98 ++++ .../perl/centreon/script/centstorage_purge.pm | 106 ++++ .../lib/perl/centreon/script/logAnalyser.pm | 466 ++++++++++++++++++ 6 files changed, 1223 insertions(+) create mode 100644 centreon/lib/perl/centreon/db.pm create mode 100644 centreon/lib/perl/centreon/lock.pm create mode 100644 centreon/lib/perl/centreon/logger.pm create mode 100644 centreon/lib/perl/centreon/script.pm create mode 100644 centreon/lib/perl/centreon/script/centstorage_purge.pm create mode 100644 centreon/lib/perl/centreon/script/logAnalyser.pm diff --git a/centreon/lib/perl/centreon/db.pm b/centreon/lib/perl/centreon/db.pm new file mode 100644 index 00000000000..ec5fd17d784 --- /dev/null +++ b/centreon/lib/perl/centreon/db.pm @@ -0,0 +1,283 @@ +################################################################################ +# Copyright 2005-2011 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# +# SVN : $URL +# SVN : $Id +# +#################################################################################### +package centreon::db; + +use strict; +use warnings; +use DBI; + + +sub new { + my ($class, %options) = @_; + my %defaults = + ( + logger => undef, + db => undef, + host => "localhost", + user => undef, + password => undef, + port => 3306, + force => 0 + ); + my $self = {%defaults, %options}; + + $self->{"instance"} = undef; + $self->{"type"} = "mysql"; + $self->{"args"} = []; + bless $self, $class; + return $self; +} + +# Getter/Setter DB name +sub db { + my $self = shift; + if (@_) { + $self->{"db"} = shift; + } + return $self->{"db"}; +} + +# Getter/Setter DB host +sub host { + my $self = shift; + if (@_) { + $self->{"host"} = shift; + } + return $self->{"host"}; +} + +# Getter/Setter DB port +sub port { + my $self = shift; + if (@_) { + $self->{"port"} = shift; + } + return $self->{"port"}; +} + +# Getter/Setter DB user +sub user { + my $self = shift; + if (@_) { + $self->{"user"} = shift; + } + return $self->{"user"}; +} + +# Getter/Setter DB force +sub force { + my $self = shift; + if (@_) { + $self->{"force"} = shift; + } + return $self->{"force"}; +} + +# Getter/Setter DB password +sub password { + my $self = shift; + if (@_) { + $self->{"password"} = shift; + } + return $self->{"password"}; +} + +sub last_insert_id { + my $self = shift; + return $self->{instance}->last_insert_id(undef, undef, undef, undef); +} + +sub quote { + my $self = shift; + + if (defined($self->{'instance'})) { + return $self->{'instance'}->quote($_[0]); + } + my $num = scalar(@{$self->{"args"}}); + push @{$self->{"args"}}, $_[0]; + return "##__ARG__$num##"; +} + +sub set_inactive_destroy { + my $self = shift; + + if (defined($self->{'instance'})) { + $self->{'instance'}->{InactiveDestroy} = 1; + } +} + +sub transaction_mode { + my ($self, $status) = @_; + + if ($status) { + $self->{instance}->begin_work; + $self->{instance}->{RaiseError} = 1; + } else { + $self->{instance}->{AutoCommit} = 1; + $self->{instance}->{RaiseError} = 0; + } +} + +sub commit { shift->{instance}->commit; } + +sub rollback { shift->{instance}->rollback; } + +sub kill { + my $self = shift; + + if (defined($self->{'instance'})) { + $self->{"logger"}->writeLogInfo("KILL QUERY\n"); + my $rv = $self->{'instance'}->do("KILL QUERY " . $self->{'instance'}->{'mysql_thread_id'}); + if (!$rv) { + my ($package, $filename, $line) = caller; + $self->{'logger'}->writeLogError("MySQL error : " . $self->{'instance'}->errstr . " (caller: $package:$filename:$line)\n"); + } + } +} + +# Connection initializer +sub connect() { + my $self = shift; + my $logger = $self->{logger}; + my $status = 0; + + while (1) { + $self->{"instance"} = DBI->connect( + "DBI:".$self->{"type"} + .":".$self->{"db"} + .":".$self->{"host"} + .":".$self->{"port"}, + $self->{"user"}, + $self->{"password"}, + { "RaiseError" => 0, "PrintError" => 0, "AutoCommit" => 1 } + ); + if (defined($self->{"instance"})) { + last; + } + + my ($package, $filename, $line) = caller; + $logger->writeLogError("MySQL error : cannot connect to database " . $self->{"db"} . ": " . $DBI::errstr . " (caller: $package:$filename:$line)\n"); + if ($self->{'force'} == 0) { + $status = -1; + last; + } + sleep(5); + } + return $status; +} + +# Destroy connection +sub disconnect { + my $self = shift; + my $instance = $self->{"instance"}; + if (defined($instance)) { + $instance->disconnect; + $self->{"instance"} = undef; + } +} + +sub do { + my ($self, $query) = @_; + + if (!defined $self->{instance}) { + if ($self->connect() == -1) { + $self->{logger}->writeLogError("Can't connect to the database"); + return -1; + } + } + my $numrows = $self->{instance}->do($query); + die $self->{instance}->errstr if !defined $numrows; + return $numrows; +} + +sub error { + my ($self, $error, $query) = @_; + my ($package, $filename, $line) = caller 1; + + chomp($query); + $self->{logger}->writeLogError(<<"EOE"); +MySQL error: $error (caller: $package:$filename:$line) +Query: $query +EOE + $self->disconnect(); + $self->{"instance"} = undef; +} + +sub query { + my $self = shift; + my $query = shift; + my $logger = $self->{logger}; + my $status = 0; + my $statement_handle; + + while (1) { + if (!defined($self->{"instance"})) { + $status = $self->connect(); + if ($status != -1) { + for (my $i = 0; $i < scalar(@{$self->{"args"}}); $i++) { + my $str_quoted = $self->quote(${$self->{"args"}}[0]); + $query =~ s/##__ARG__$i##/$str_quoted/; + } + $self->{"args"} = []; + } + if ($status == -1 && $self->{'force'} == 0) { + $self->{"args"} = []; + last; + } + } + + $statement_handle = $self->{"instance"}->prepare($query); + if (!defined $statement_handle) { + $self->error($statement_handle->errstr, $query); + $status = -1; + last if $self->{'force'} == 0; + next; + } + + my $rv = $statement_handle->execute; + if (!$rv) { + $self->error($statement_handle->errstr, $query); + $status = -1; + last if $self->{force} == 0; + next; + } + last; + } + return ($status, $statement_handle); +} + +1; diff --git a/centreon/lib/perl/centreon/lock.pm b/centreon/lib/perl/centreon/lock.pm new file mode 100644 index 00000000000..f4fd55369af --- /dev/null +++ b/centreon/lib/perl/centreon/lock.pm @@ -0,0 +1,141 @@ +package centreon::lock; + +use strict; +use warnings; + +sub new { + my ($class, $name, %options) = @_; + my %defaults = (name => $name, timeout => 10); + my $self = {%defaults, %options}; + + bless $self, $class; + return $self; +} + +sub is_set { + die "Not implemented"; +} + +sub set { + my $self = shift; + + for (my $i = 0; $self->is_set() && $i < $self->{timeout}; $i++) { + sleep 1; + } + die "Failed to set lock for $self->{name}" if $self->is_set(); +} + +package centreon::lock::file; + +use base qw(centreon::lock); + +sub new { + my $class = shift; + my $self = $class->SUPER::new(@_); + + if (!defined $self->{pid} || !defined $self->{storagedir}) { + die "Can't build lock, required arguments not provided"; + } + bless $self, $class; + $self->{pidfile} = "$self->{storagedir}/$self->{name}.lock"; + return $self; +} + +sub is_set { + return -e shift->{pidfile}; +} + +sub set { + my $self = shift; + + $self->SUPER::set(); + open LOCK, ">", $self->{pidfile}; + print LOCK $self->{pid}; + close LOCK; +} + +sub DESTROY { + my $self = shift; + + if (defined $self->{pidfile} && -e $self->{pidfile}) { + unlink $self->{pidfile}; + } +} + +package centreon::lock::sql; + +use base qw(centreon::lock); + +sub new { + my $class = shift; + my $self = $class->SUPER::new(@_); + + if (!defined $self->{dbc}) { + die "Can't build lock, required arguments not provided"; + } + bless $self, $class; + $self->{launch_time} = time(); + return $self; +} + +sub is_set { + my $self = shift; + my ($status, $sth) = $self->{dbc}->query( + "SELECT id,running,time_launch FROM cron_operation WHERE name LIKE '$self->{name}'" + ); + my $data = $sth->fetchrow_hashref(); + + if (!defined $data->{id}) { + $self->{not_created_yet} = 1; + $self->{previous_launch_time} = 0; + return 0; + } + $self->{id} = $data->{id}; + $self->{previous_launch_time} = $data->{time_launch}; + if (defined $data->{running} && $data->{running} == 1) { + return 1; + } + return 0; +} + +sub set { + my $self = shift; + my $status; + + $self->SUPER::set(); + if (defined $self->{not_created_yet}) { + $status = $self->{dbc}->do(<<"EOQ"); +INSERT INTO cron_operation +(name, system, activate) +VALUES ('$self->{name}', '1', '1') +EOQ + goto error if $status == -1; + $self->{id} = $self->{dbc}->last_insert_id(); + return; + } + $status = $self->{dbc}->do(<<"EOQ"); +UPDATE cron_operation +SET running = '1', time_launch = '$self->{launch_time}' +WHERE id = '$self->{id}' +EOQ + goto error if $status == -1; + return; + + error: + die "Failed to set lock for $self->{name}"; +} + +sub DESTROY { + my $self = shift; + + if (defined $self->{dbc}) { + my $exectime = time() - $self->{launch_time}; + $self->{dbc}->do(<<"EOQ"); +UPDATE cron_operation +SET running = '0', last_execution_time = '$exectime' +WHERE id = '$self->{id}' +EOQ + } +} + +1; diff --git a/centreon/lib/perl/centreon/logger.pm b/centreon/lib/perl/centreon/logger.pm new file mode 100644 index 00000000000..1e53f19a4e7 --- /dev/null +++ b/centreon/lib/perl/centreon/logger.pm @@ -0,0 +1,129 @@ +package centreon::logger; + +=head1 NOM + +centreon::logger - Simple logging module + +=head1 SYNOPSIS + + #!/usr/bin/perl -w + + use strict; + use warnings; + + use centreon::polling; + + my $logger = new centreon::logger(); + + $logger->writeLogInfo("information"); + +=head1 DESCRIPTION + +This module offers a simple interface to write log messages to various output: + +* standard output +* file +* syslog + +=cut + +use strict; +use warnings; +use Sys::Syslog qw(:standard :macros); +use IO::Handle; + +my %severities = (1 => LOG_INFO, + 2 => LOG_ERR); + +sub new { + my $class = shift; + + my $self = bless + { + file => 0, + filehandler => undef, + # 0 = nothing, 1 = critical, 3 = info + severity => 3, + # 0 = stdout, 1 = file, 2 = syslog + log_mode => 0, + # syslog + log_facility => undef, + log_option => LOG_PID, + }, $class; + return $self; +} + +sub file_mode($$) { + my ($self, $file) = @_; + + if (open($self->{filehandler}, ">>", $file)){ + $self->{log_mode} = 1; + $self->{filehandler}->autoflush(1); + return 1; + } + $self->{filehandler} = undef; + print STDERR "Cannot open file $file: $!\n"; + return 0; +} + +sub syslog_mode($$$) { + my ($self, $logopt, $facility) = @_; + + $self->{log_mode} = 2; + openlog($0, $logopt, $facility); + return 1; +} + +# Getter/Setter Log severity +sub severity { + my $self = shift; + if (@_) { + $self->{"severity"} = $_[0]; + } + return $self->{"severity"}; +} + +sub get_date { + my $self = shift; + my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time()); + return sprintf("%04d-%02d-%02d %02d:%02d:%02d", + $year+1900, $mon+1, $mday, $hour, $min, $sec); +} + +sub writeLog($$$%) { + my ($self, $severity, $msg, %options) = @_; + my $withdate = (defined $options{withdate}) ? $options{withdate} : 1; + my $newmsg = ($withdate) + ? $self->get_date . " - $msg" : $msg; + + if (($self->{severity} & $severity) == 0) { + return; + } + if ($self->{log_mode} == 0) { + print "$newmsg\n"; + } elsif ($self->{log_mode} == 1) { + if (defined $self->{filehandler}) { + print { $self->{filehandler} } "$newmsg\n"; + } + } elsif ($self->{log_mode} == 2) { + syslog($severities{$severity}, $msg); + } +} + +sub writeLogInfo { + shift->writeLog(1, @_); +} + +sub writeLogError { + shift->writeLog(2, @_); +} + +sub DESTROY { + my $self = shift; + + if (defined $self->{filehandler}) { + $self->{filehandler}->close(); + } +} + +1; diff --git a/centreon/lib/perl/centreon/script.pm b/centreon/lib/perl/centreon/script.pm new file mode 100644 index 00000000000..48edffde999 --- /dev/null +++ b/centreon/lib/perl/centreon/script.pm @@ -0,0 +1,98 @@ +package centreon::script; + +use strict; +use warnings; +use Getopt::Long; +use Pod::Usage; +use centreon::logger; +use centreon::db; +use centreon::lock; + +use vars qw($centreon_config); + +sub new { + my ($class, $name, %options) = @_; + my %defaults = + ( + config_file => "/etc/centreon/centreon-config.pm", + log_file => undef, + centreon_db_conn => 0, + centstorage_db_conn => 0, + debug_mode => 0 + ); + my $self = {%defaults, %options}; + + bless $self, $class; + $self->{name} = $name; + $self->{logger} = centreon::logger->new(); + $self->{options} = { + "config=s" => \$self->{config_file}, + "logfile=s" => \$self->{log_file}, + "debug" => \$self->{debug_mode}, + "help|?" => \$self->{help} + }; + return $self; +} + +sub init { + my $self = shift; + + if (defined $self->{log_file}) { + $self->{logger}->file_mode($self->{log_file}); + } + + if ($self->{centreon_db_conn}) { + $self->{cdb} = centreon::db->new + (db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + logger => $self->{logger}); + $self->{lock} = centreon::lock::sql->new($self->{name}, dbc => $self->{cdb}); + $self->{lock}->set(); + } + if ($self->{centstorage_db_conn}) { + $self->{csdb} = centreon::db->new + (db => $self->{centreon_config}->{centstorage_db}, + host => $self->{centreon_config}->{db_host}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + logger => $self->{logger}); + } +} + +sub DESTROY { + my $self = shift; + + if (defined $self->{cdb}) { + $self->{cdb}->disconnect(); + } + if (defined $self->{csdb}) { + $self->{csdb}->disconnect(); + } +} + +sub add_options { + my ($self, %options) = @_; + + $self->{options} = {%{$self->{options}}, %options}; +} + +sub parse_options { + my $self = shift; + + Getopt::Long::Configure('bundling'); + die "Command line error" if !GetOptions(%{$self->{options}}); + pod2usage(1) if $self->{help}; + require $self->{config_file}; + $self->{centreon_config} = $centreon_config; +} + +sub run { + my $self = shift; + + $self->parse_options(); + $self->init(); +} + +1; diff --git a/centreon/lib/perl/centreon/script/centstorage_purge.pm b/centreon/lib/perl/centreon/script/centstorage_purge.pm new file mode 100644 index 00000000000..4136c9cd01d --- /dev/null +++ b/centreon/lib/perl/centreon/script/centstorage_purge.pm @@ -0,0 +1,106 @@ +package centreon::script::centstorage_purge; + +use strict; +use warnings; +use centreon::script; +use centreon::lock; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("centstorage_purge", + centreon_db_conn => 1, + centstorage_db_conn => 1 + ); + + bless $self, $class; + $self->{broker} = "ndo"; + my ($status, $sth) = $self->{csdb}->query(<<"EOQ"); +SELECT len_storage_mysql,archive_retention,reporting_retention +FROM config +EOQ + die "Failed to retrieve configuration from database" if $status == -1; + $self->{config} = $sth->fetchrow_hashref(); + + ($status, $sth) = $self->{cdb}->query(<<"EOQ"); +SELECT `value` FROM `options` WHERE `key` = 'broker' +EOQ + die "Failed to retrieve the broker type from database" if $status == -1; + $self->{broker} = $sth->fetchrow_hashref()->{value}; + return $self; +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + if (defined $self->{config}->{len_storage_mysql} && + $self->{config}->{len_storage_mysql} != 0) { + my $delete_limit = time() - 60 * 60 * 24 * $self->{config}->{len_storage_mysql}; + + $self->{logger}->writeLogInfo("Purging centstorage.data_bin table..."); + $self->{csdb}->do("DELETE FROM data_bin WHERE ctime < '$delete_limit'"); + $self->{logger}->writeLogInfo("Done"); + } + + if (defined($self->{config}->{archive_retention}) + && $self->{config}->{archive_retention} != 0) { + my $last_log = time() - ($self->{config}->{archive_retention} * 24 * 60 * 60); + my $table = ($self->{broker} eq "broker") ? "logs" : "log"; + + $self->{logger}->writeLogInfo("Purging centstorage.$table table..."); + eval { + my $lock = undef; + if ($self->{broker} eq "ndo") { + $lock = centreon::lock::sql("logAnalyser", dbc => $self->{cdb}); + $lock->set(); + } + $self->{csdb}->do("DELETE FROM `$table` WHERE `ctime` < '$last_log'"); + }; + if ($@) { + $self->{logger}->writeLogError("Failed: $@"); + } else { + $self->{logger}->writeLogInfo("Done"); + } + } + + if (defined($self->{config}->{reporting_retention}) + && $self->{config}->{reporting_retention} != 0) { + my $last_log = time() - ($self->{config}->{reporting_retention} * 24 * 60 * 60); + + $self->{logger}->writeLogInfo("Purging log archive tables..."); + $self->{csdb}->do("DELETE FROM `log_archive_host` WHERE `date_end` < '$last_log'"); + $self->{csdb}->do("DELETE FROM `log_archive_service` WHERE `date_end` < '$last_log'"); + $self->{logger}->writeLogInfo("Done"); + } +} + +1; + +__END__ + +=head1 NAME + +centstorage_purge - purge centstorage database + +=head1 SYNOPSIS + +centstorage_purge [options] + +=head1 OPTIONS + +=over 8 + +=item B<-help> + +Print a brief help message and exits. + +=back + +=head1 DESCRIPTION + +B will read the given input file(s) and do something +useful with the contents thereof. + +=cut diff --git a/centreon/lib/perl/centreon/script/logAnalyser.pm b/centreon/lib/perl/centreon/script/logAnalyser.pm new file mode 100644 index 00000000000..c4a801a7820 --- /dev/null +++ b/centreon/lib/perl/centreon/script/logAnalyser.pm @@ -0,0 +1,466 @@ +package centreon::script::logAnalyser; + +use strict; +use warnings; +use File::Path qw(mkpath); +use centreon::script; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("logAnalyser", + centreon_db_conn => 1, + centstorage_db_conn => 1 + ); + + bless $self, $class; + $self->add_options( + "a" => \$self->{opt_a}, "archives" => \$self->{opt_a}, + "p=s" => \$self->{opt_p}, "poller" => \$self->{opt_p}, + "s=s" => \$self->{opt_s}, "startdate" => \$self->{opt_s} + ); + $self->{launch_time} = time(); + $self->{msg_type5_disabled} = 0; + $self->{queries_per_transaction} = 500; + return $self; +} + +sub read_config { + my $self = shift; + my ($status, $sth) = $self->{cdb}->query("SELECT `value` FROM `options` WHERE `key` = 'broker'"); + + goto error if $status == -1; + if ($sth->fetchrow_hashref()->{value} eq "broker") { + die "This script is only suitable for NDO"; + } + ($status, $sth) = $self->{csdb}->query(<<"EOQ"); +SELECT archive_log, archive_retention FROM config +EOQ + goto error if $status == -1; + $self->{config} = $sth->fetchrow_hashref(); + die "No configuration found in database" if !defined $self->{config}->{archive_log}; + return; + + error: + die "Failed to read configuration from database" +} + +=head2 date_to_time($date) + +Convert $date to a timestamp. + +=cut +sub date_to_time($$) { + my ($self, $date) = @_; + + $date =~ s|-|/|g; + return int(`date -d $date +%s`); +} + +=head2 time_to_date($timestamp) + +Convert $timestamp to a human readable date. + +=cut +sub time_to_date($$) { + my ($self, $timestamp) = @_; + chomp(my $result = `date -d \@$timestamp +%m-%d-%Y`); + + return $result; +} + +sub reset_position_flag { + my ($self, $instance) = @_; + my $status = $self->{csdb}->do(<<"EOQ"); +UPDATE instance SET log_flag = '0' WHERE instance_id = '$instance' +EOQ + die "Failed to reset the position flag into database" if $status == -1; +} + +sub commit_to_log { + my ($self, $instance, $ctime, $counter) = @_; + + $self->{csdb}->do(<<"EOQ"); +UPDATE instance SET log_flag='$counter', last_ctime='$ctime' WHERE instance_id = '$instance' +EOQ + $self->{csdb}->commit; + $self->{csdb}->transaction_mode(1); +} + +=head2 parse_file($logFile, $instance) + +Parse a nagios log file. + +=cut +sub parse_file($$$) { + my ($self, $logfile, $instance) = @_; + my $ctime = 0; + my $logdir = "$self->{centreon_config}->{VarLib}/log/$instance"; + my ($last_position, $nbqueries, $counter) = (0, 0, 0); + + if (!-d $logdir) { + mkpath($logdir); + } + my ($status, $sth) = $self->{csdb}->query(<<"EOQ"); +SELECT `log_flag`,`last_ctime` FROM `instance` WHERE `instance_id`='$instance' +EOQ + die "Cannot read previous run information from database" if $status == -1; + my $prev_run_info = $sth->fetchrow_hashref(); + + # Get History Flag + if (open LOG, $logfile) { + my $fline = ; + close LOG; + if ($fline =~ m/\[([0-9]*)\]\ /) { + chomp($ctime = $1); + } else { + $self->{logger}->writeLogError("Cannot find ctime in first line for poller $instance"); + } + } + + # Decide if we have to read the nagios.log from the begining + if ($ctime && $prev_run_info->{ctime} && $ctime == $prev_run_info->{ctime}) { + $last_position = $prev_run_info->{log_flag}; + } + + # Open Log File for parsing + if (!open FILE, $logfile) { + $self->{logger}->writeLogError("Cannot open file: $logfile"); + return; + } + + # Skip old lines (already read) + if (!$self->{opt_a} && $last_position) { + while ($counter < $last_position && ) { + $counter++; + } + } + + $self->{csdb}->transaction_mode(1); + eval { + while () { + my $cur_ctime; + + if ($_ =~ m/^\[([0-9]*)\]\sSERVICE ALERT\:\s(.*)$/) { + my @tab = split(/;/, $2); + $cur_ctime = $1; + $tab[0] =~ s/\\/\\\\/g; + $tab[0] =~ s/\'/\\\'/g; + $tab[1] =~ s/\\/\\\\/g; + $tab[1] =~ s/\'/\\\'/g; + $tab[5] =~ s/\\/\\\\/g; + $tab[5] =~ s/\'/\\\'/g; + my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `host_name` , `service_description`, `status`, `type`, `retry`, `output`, `instance`) VALUES ('0', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."','".$tab[4]."','".$tab[5]."', '".$instance."')"; + my $res = $self->{csdb}->do($rq); + } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST ALERT\:\s(.*)$/) { + my @tab = split(/;/, $2); + $cur_ctime = $1; + $tab[0] =~ s/\\/\\\\/g; + $tab[0] =~ s/\'/\\\'/g; + if (defined($tab[4]) && $tab[4]) { + $tab[4] =~ s/\\/\\\\/g; + $tab[4] =~ s/\'/\\\'/g; + } + my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `host_name` , `status`, `type`, `retry`, `output`, `instance`) VALUES ('1', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."','".$tab[3]."','".$tab[4]."', '".$instance."')"; + my $res = $self->{csdb}->do($rq); + } elsif ($_ =~ m/^\[([0-9]*)\]\sSERVICE NOTIFICATION\:\s(.*)$/) { + my @tab = split(/;/, $2); + $cur_ctime = $1; + $tab[2] =~ s/\\/\\\\/g; + $tab[2] =~ s/\'/\\\'/g; + $tab[1] =~ s/\\/\\\\/g; + $tab[1] =~ s/\'/\\\'/g; + if (defined($tab[5])) { + $tab[5] =~ s/\\/\\\\/g; + $tab[5] =~ s/\'/\\\'/g; + } else { + $tab[5] = ""; + } + my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `host_name` , `service_description`, `status`, `notification_cmd`, `notification_contact`, `output`, `instance`) VALUES ('2', '$cur_ctime', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."', '".$tab[4]."','".$tab[0]."','".$tab[5]."', '".$instance."')"; + my $res = $self->{csdb}->do($rq); + } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST NOTIFICATION\:\s(.*)$/) { + my @tab = split(/;/, $2); + $cur_ctime = $1; + if (defined($tab[4])) { + $tab[4] =~ s/\\/\\\\/g; + $tab[4] =~ s/\'/\\\'/g; + } else { + $tab[4] = ""; + } + my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `notification_contact`, `host_name` , `status`, `notification_cmd`, `output`, `instance`) VALUES ('3', '$cur_ctime', '".$tab[0]."','".$tab[1]."', '".$tab[2]."', '".$tab[3]."','".$tab[4]."', '".$instance."')"; + my $res = $self->{csdb}->do($rq); + } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sHOST\sSTATE\:\s(.*)$/) { + my @tab = split(/;/, $2); + $cur_ctime = $1; + $tab[0] =~ s/\\/\\\\/g; + $tab[0] =~ s/\'/\\\'/g; + my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name` , `status`, `type`, `instance`) VALUES ('7', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$instance."')"; + my $res = $self->{csdb}->do($rq); + } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sSERVICE\sSTATE\:\s(.*)$/) { + my @tab = split(/;/, $2); + $cur_ctime = $1; + $tab[0] =~ s/\\/\\\\/g; + $tab[0] =~ s/\'/\\\'/g; + $tab[1] =~ s/\\/\\\\/g; + $tab[1] =~ s/\'/\\\'/g; + my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `service_description` , `status`, `type`, `instance`) VALUES ('6', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."', '".$instance."')"; + my $res = $self->{csdb}->do($rq); + } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sHOST\sSTATE\:\s(.*)$/) { + my @tab = split(/;/, $2); + $cur_ctime = $1; + $tab[0] =~ s/\\/\\\\/g; + $tab[0] =~ s/\'/\\\'/g; + my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name` , `status`, `type`, `instance`) VALUES ('9', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$instance."')"; + my $res = $self->{csdb}->do($rq); + } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sSERVICE\sSTATE\:\s(.*)$/) { + my @tab = split(/;/, $2); + $cur_ctime = $1; + $tab[0] =~ s/\\/\\\\/g; + $tab[0] =~ s/\'/\\\'/g; + $tab[1] =~ s/\\/\\\\/g; + $tab[1] =~ s/\'/\\\'/g; + my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `service_description` , `status`, `type`, `instance`) VALUES ('8', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."', '".$instance."')"; + my $res = $self->{csdb}->do($rq); + } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_SVC\_PROBLEM\;(.*)$/) { + $cur_ctime = $1; + my @tab = split(/;/, $2); + $tab[0] =~ s/\\/\\\\/g; + $tab[0] =~ s/\'/\\\'/g; + $tab[1] =~ s/\\/\\\\/g; + $tab[1] =~ s/\'/\\\'/g; + if (!defined($tab[6])) { + $tab[6] = ""; + } + $tab[6] =~ s/\\/\\\\/g; + $tab[6] =~ s/\'/\\\'/g; + my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `service_description`, `notification_contact`, `output`, `instance`) VALUES ('10', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[5]."', '".$tab[6]."','".$instance."')"; + my $res = $self->{csdb}->do($rq); + } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_HOST\_PROBLEM\;(.*)$/) { + $cur_ctime = $1; + my @tab = split(/;/, $2); + $tab[0] =~ s/\\/\\\\/g; + $tab[0] =~ s/\'/\\\'/g; + $tab[5] =~ s/\\/\\\\/g; + $tab[5] =~ s/\'/\\\'/g; + my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `notification_contact`, `output`, `instance`) VALUES ('11', '$cur_ctime', '".$tab[0]."', '".$tab[4]."', '".$tab[5]."','".$instance."')"; + my $res = $self->{csdb}->do($rq); + } elsif ($_ =~ m/^\[([0-9]*)\]\sWarning\:\s(.*)$/) { + my $tab = $2; + $cur_ctime = $1; + $tab =~ s/\\/\\\\/g; + $tab =~ s/\'/\\\'/g; + my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `output`, `instance`) VALUES ('4','$cur_ctime', '".$tab."', '".$instance."')"; + my $res = $self->{csdb}->do($rq); + } elsif ($_ =~ m/^\[([0-9]*)\]\s(.*)$/ && (!$self->{msg_type5_disabled})) { + $cur_ctime = $1; + my $tab = $2; + $tab =~ s/\\/\\\\/g; + $tab =~ s/\'/\\\'/g; + my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `output`, `instance`) VALUES ('5','$cur_ctime', '".$tab."', '".$instance."')"; + my $res = $self->{csdb}->do($rq); + } + $counter++; + $nbqueries++; + if ($nbqueries == $self->{queries_per_transaction}) { + $self->commit_to_log($instance, $ctime, $counter); + $nbqueries = 0; + } + } + $self->commit_to_log($instance, $ctime, $counter); + }; + close FILE; + if ($@) { + $self->{csdb}->rollback; + die "Database error: $@"; + } + $self->{csdb}->transaction_mode(0); +} + +=head2 parse_archives($instance, $localhost, $startdate) + +Parse log file archices for a given poller (B<$instance>). An +optionnal B<$startdate> can be provided. + +=cut +sub parse_archives { + my ($self, $instance, $localhost, $startdate) = @_; + my $archives; + + if ($localhost) { + my ($status, $sth) = $self->{cdb}->query(<<"EOQ"); +SELECT `log_archive_path` FROM `cfg_nagios`, `nagios_server` +WHERE `nagios_server_id` = '$instance' +AND `nagios_server`.`id` = `cfg_nagios`.`nagios_server_id` +AND `nagios_server`.`ns_activate` = '1' +AND `cfg_nagios`.`nagios_activate` = '1' +EOQ + die "Failed to read instance configuration" if $status == -1; + $archives = $sth->fetchrow_hashref()->{log_archive_path}; + } else { + $archives = "$self->{centreon_config}->{VarLib}/log/$instance/archives/"; + } + + $archives .= "/" if (!($archives =~ /\/$/)); + if (!-d $archives) { + $self->{logger}->writeLogError("No archives for poller $instance"); + return; + } + + my @log_files = split /\s/, `ls $archives`; + my $last_log = undef; + + if (!defined $startdate) { + $last_log = time() - ($self->{config}->{archive_retention} * 24 * 60 * 60); + } else { + $last_log = $self->date_to_time($startdate); + } + foreach (@log_files) { + $_ =~ /nagios\-([0-9\-]+).log/; + my @time = split /\-/, $1; + my $temp = "$time[0]/$time[1]/$time[2]"; + $temp = `date -d $temp +%s`; + if ($temp > $last_log) { + my $curarchive = "$archives$_"; + + $self->{logger}->writeLogInfo("Parsing log file: $curarchive"); + if (!-r $curarchive) { + $self->{logger}->writeLogError("Cannot read file $curarchive"); + next; + } + $self->parse_file($curarchive, $instance); + } + } +} + +=head2 parse_logfile($instance, $localhost, $previous_launch_time) + +Parse the current nagios log file for a given poller. + +=cut +sub parse_logfile($$$) { + my ($self, $instance, $localhost, $previous_launch_time) = @_; + my ($logfile, $archivepath); + + if ($localhost) { + my ($status, $sth) = $self->{cdb}->query(<<"EOQ"); +SELECT `log_file`, `log_archive_path` +FROM `cfg_nagios`, `nagios_server` +WHERE `nagios_server_id` = '$instance' +AND `nagios_server`.`id` = `cfg_nagios`.`nagios_server_id` +AND `nagios_server`.`ns_activate` = '1' +AND `cfg_nagios`.`nagios_activate` = '1' +EOQ + die "Cannot read logfile from database" if $status == -1; + my $data = $sth->fetchrow_hashref(); + $logfile = $data->{log_file}; + $archivepath = $data->{log_archive_path}; + $archivepath .= "/" if ($archivepath !~ /\/$/); + die "Failed to open $logfile" if !-r $logfile; + + my @now = localtime(); + my $archname = "$archivepath/nagios-" . $self->time_to_date($self->{launch_time}) . "-$now[2].log"; + if (-f $archname) { + my $st = stat($archname); + if ($st->mtime > $previous_launch_time) { + $self->{logger}->writeLogInfo("Parsing rotated file for instance $instance"); + $self->parse_file($archname, $instance); + } + } + } else { + $logfile = "$self->{centreon_config}->{VarLib}/log/$instance/nagios.log"; + my $rotate_file = "$logfile.rotate"; + + if (-e $rotate_file) { + $self->{logger}->writeLogInfo("Parsing rotated file for instance $instance"); + $self->parse_file($rotate_file, $instance); + unlink $rotate_file; + } + } + + $self->parse_file($logfile, $instance); +} + +=head2 run() + +Main method. + +Several working modes: + +* Parse the current log file of each poller (default) +* Parse the archives of each poller (-a) +* Parse the archives of a given poller (-p) + +When parsing the archives, a start date can be specified. + +=cut +sub run { + my $self = shift; + + $self->SUPER::run(); + $self->read_config(); + + if (defined $self->{opt_s}) { + if ($self->{opt_s} !~ m/\d{2}-\d{2}-\d{4}/) { + $self->{logger}->writeLogError("Invalid start date provided"); + exit 1; + } + } + + if (defined $self->{opt_p}) { + $self->reset_position_flag($self->{opt_p}); + $self->{csdb}->do("DELETE FROM `log` WHERE instance='$self->{opt_p}'"); + $self->parse_archives($self->{opt_p}, 0, $self->{opt_s}); + return; + } + + my $flag = 0; + my ($status, $list_sth) = $self->{cdb}->query(<<"EOQ"); +SELECT `id`, `name`, `localhost` FROM `nagios_server` WHERE `ns_activate`=1 +EOQ + die "Cannot read pollers list from database" if $status == -1; + + while (my $ns_server = $list_sth->fetchrow_hashref()) { + my $sth; + ($status, $sth) = $self->{csdb}->query(<<"EOQ"); +SELECT `instance_name` FROM `instance` WHERE `instance_id` = '$ns_server->{id}' LIMIT 1 +EOQ + die "Cannot read instance name from database" if $status == -1; + if (!$sth->rows()) { + $status = $self->{csdb}->do(<<"EOQ"); +INSERT INTO `instance` +(`instance_id`, `instance_name`, `log_flag`) +VALUES ('$ns_server->{id}', '$ns_server->{name}', '0') +EOQ + die "Cannot save instance to database" if $status == -1; + } else { + $status = $self->{csdb}->do(<<"EOQ"); +UPDATE `instance` SET `instance_name` = '$ns_server->{name}' +WHERE `instance_id` = '$ns_server->{id}' LIMIT 1 +EOQ + die "Cannot update instance from database" if $status == -1; + } + $self->{logger}->writeLogInfo("Poller: $ns_server->{name}"); + if ($self->{opt_a}) { + if (!$flag) { + if (!defined $self->{opt_s}) { + $status = $self->{csdb}->do("TRUNCATE TABLE `log`"); + $self->{logger}->writeLogError("Failed to truncate 'log' table") if $status == -1; + } else { + my $limit = $self->date_to_time($self->{opt_s}); + $status = $self->{csdb}->do("DELETE FROM `log` WHERE `ctime` >= $limit"); + $self->{logger}->writeLogError("Failed to purge 'log' table") if $status == -1; + } + $flag = 1; + } + $self->reset_position_flag($ns_server->{id}); + $self->parse_archives($ns_server->{id}, $ns_server->{localhost}, $self->{opt_s}); + } else { + $self->parse_logfile($ns_server->{id}, $ns_server->{localhost}, + $self->{lock}->{previous_launch_time}); + } + } + $self->{logger}->writeLogInfo("Done"); +} + +1; From ad818b59baaeb671e3b063dc9d6c0206aba08573 Mon Sep 17 00:00:00 2001 From: Antoine Nguyen Date: Tue, 12 Mar 2013 09:01:02 +0100 Subject: [PATCH 002/458] Proper help messages and default DIE handler. --- centreon/lib/perl/centreon/script.pm | 9 ++++- .../perl/centreon/script/centstorage_purge.pm | 34 ++++--------------- .../lib/perl/centreon/script/logAnalyser.pm | 8 +++++ 3 files changed, 23 insertions(+), 28 deletions(-) diff --git a/centreon/lib/perl/centreon/script.pm b/centreon/lib/perl/centreon/script.pm index 48edffde999..93144057918 100644 --- a/centreon/lib/perl/centreon/script.pm +++ b/centreon/lib/perl/centreon/script.pm @@ -2,6 +2,7 @@ package centreon::script; use strict; use warnings; +use FindBin; use Getopt::Long; use Pod::Usage; use centreon::logger; @@ -10,6 +11,12 @@ use centreon::lock; use vars qw($centreon_config); +$SIG{__DIE__} = sub { + my $error = shift; + print "Error: $error"; + exit 1; +}; + sub new { my ($class, $name, %options) = @_; my %defaults = @@ -83,7 +90,7 @@ sub parse_options { Getopt::Long::Configure('bundling'); die "Command line error" if !GetOptions(%{$self->{options}}); - pod2usage(1) if $self->{help}; + pod2usage(-exitval => 1, -input => $FindBin::Bin . "/" . $FindBin::Script) if $self->{help}; require $self->{config_file}; $self->{centreon_config} = $centreon_config; } diff --git a/centreon/lib/perl/centreon/script/centstorage_purge.pm b/centreon/lib/perl/centreon/script/centstorage_purge.pm index 4136c9cd01d..a709297fe95 100644 --- a/centreon/lib/perl/centreon/script/centstorage_purge.pm +++ b/centreon/lib/perl/centreon/script/centstorage_purge.pm @@ -16,6 +16,11 @@ sub new { bless $self, $class; $self->{broker} = "ndo"; + return $self; +} + +sub read_config { + my $self = shift; my ($status, $sth) = $self->{csdb}->query(<<"EOQ"); SELECT len_storage_mysql,archive_retention,reporting_retention FROM config @@ -28,13 +33,14 @@ SELECT `value` FROM `options` WHERE `key` = 'broker' EOQ die "Failed to retrieve the broker type from database" if $status == -1; $self->{broker} = $sth->fetchrow_hashref()->{value}; - return $self; } sub run { my $self = shift; $self->SUPER::run(); + $self->read_config(); + if (defined $self->{config}->{len_storage_mysql} && $self->{config}->{len_storage_mysql} != 0) { my $delete_limit = time() - 60 * 60 * 24 * $self->{config}->{len_storage_mysql}; @@ -78,29 +84,3 @@ sub run { 1; -__END__ - -=head1 NAME - -centstorage_purge - purge centstorage database - -=head1 SYNOPSIS - -centstorage_purge [options] - -=head1 OPTIONS - -=over 8 - -=item B<-help> - -Print a brief help message and exits. - -=back - -=head1 DESCRIPTION - -B will read the given input file(s) and do something -useful with the contents thereof. - -=cut diff --git a/centreon/lib/perl/centreon/script/logAnalyser.pm b/centreon/lib/perl/centreon/script/logAnalyser.pm index c4a801a7820..27fa5a0faa4 100644 --- a/centreon/lib/perl/centreon/script/logAnalyser.pm +++ b/centreon/lib/perl/centreon/script/logAnalyser.pm @@ -464,3 +464,11 @@ EOQ } 1; + +__END__ + +=head1 NAME + + sample - Using GetOpt::Long and Pod::Usage + +=cut From 7a5b2b5b5d24b1809c71dfa9044c6f94891d4b97 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 19 Mar 2013 17:51:40 +0100 Subject: [PATCH 003/458] Fix #5140 --- .../lib/perl/centreon/script/centstorage.pm | 428 +++++++ .../lib/perl/centstorage/CentstorageAction.pm | 287 +++++ .../lib/perl/centstorage/CentstorageLib.pm | 195 +++ .../centstorage/CentstoragePerfdataFile.pm | 124 ++ .../lib/perl/centstorage/CentstoragePool.pm | 1098 +++++++++++++++++ .../lib/perl/centstorage/CentstorageRRD.pm | 365 ++++++ .../perl/centstorage/CentstorageRebuild.pm | 99 ++ 7 files changed, 2596 insertions(+) create mode 100644 centreon/lib/perl/centreon/script/centstorage.pm create mode 100644 centreon/lib/perl/centstorage/CentstorageAction.pm create mode 100644 centreon/lib/perl/centstorage/CentstorageLib.pm create mode 100644 centreon/lib/perl/centstorage/CentstoragePerfdataFile.pm create mode 100644 centreon/lib/perl/centstorage/CentstoragePool.pm create mode 100644 centreon/lib/perl/centstorage/CentstorageRRD.pm create mode 100644 centreon/lib/perl/centstorage/CentstorageRebuild.pm diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm new file mode 100644 index 00000000000..aeccd00b69a --- /dev/null +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -0,0 +1,428 @@ + +package centreon::script::centstorage; + +use strict; +use warnings; +use POSIX; +use IO::Select; +use IO::Handle; +use centreon::script; +use centreon::db; +use centstorage::CentstorageLib; +use centstorage::CentstoragePool; +use centstorage::CentstoragePerfdataFile; +use centstorage::CentstorageAction; +use centstorage::CentstorageAction; +use centstorage::CentstorageRRD; + +use base qw(centreon::script); +use vars qw($centstorage_config); + +my %handlers = ('TERM' => {}, 'CHLD' => {}, 'DIE' => {}); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("centstorage", + centreon_db_conn => 0, + centstorage_db_conn => 0 + ); + + bless $self, $class; + $self->add_options( + "config-extra" => \$self->{opt_extra}, + ); + + %{$self->{pool_pipes}} = (); + %{$self->{return_child}} = (); + %{$self->{routing_services}} = (); + $self->{roundrobin_pool_current} = 0; + $self->{read_select} = undef; + $self->{pid_delete_child} = undef; + %{$self->{delete_pipes}} = (); + %{$self->{fileno_save_read}} = (); + $self->{centreon_db_centreon} = undef; + $self->{centstorage_perfdata_file} = undef; + + # When you lost a pool: to say that a rebuild in progress + $self->{rebuild_progress} = 0; + $self->{rebuild_pool_choosen} = 0; + + if (defined($self->{opt_extra})) { + require $self->{opt_extra}; + } else { + require "/etc/centreon/centstorage.pm"; + } + $self->{centstorage_config} = $centstorage_config; + + $self->set_signal_handlers; + + return $self; +} + +sub set_signal_handlers { + my $self = shift; + + $SIG{TERM} = \&class_handle_TERM; + $handlers{TERM}->{$self} = sub { $self->handle_TERM() }; + $SIG{__DIE__} = \&class_handle_DIE; + $handlers{DIE}->{$self} = sub { $self->handle_DIE($_[0]) }; + $SIG{CHLD} = \&class_handle_CHLD; + $handlers{CHLD}->{$self} = sub { $self->handle_CHLD() }; +} + +sub class_handle_TERM { + foreach (keys %{$handlers{TERM}}) { + &{$handlers{TERM}->{$_}}(); + } + exit(0); +} + +sub class_handle_DIE { + my ($msg) = @_; + + foreach (keys %{$handlers{DIE}}) { + &{$handlers{DIE}->{$_}}($msg); + } +} + +sub class_handle_CHLD { + foreach (keys %{$handlers{CHLD}}) { + &{$handlers{CHLD}->{$_}}(); + } +} + + +# Init Log +#my $logger = CentstorageLogger->new(); +#$logger->severity($log_crit); + +#if ($log_mode == 1) { +# open my $centstorage_fh, '>>', $LOG; +# open STDOUT, '>&', $centstorage_fh; +# open STDERR, '>&', $centstorage_fh; +# $logger->log_mode(1, $LOG); +#} +#if ($log_mode == 2) { +# $logger->log_mode(2, $openlog_option, $log_facility); +#} +######### + +sub handle_DIE { + my $self = shift; + my $msg = shift; + + # We get SIGCHLD signals + $self->{logger}->writeLogInfo($msg); + + ### + # Send -TERM signal + ### + for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { + if (defined($self->{pool_pipes}{$i}) && $self->{pool_pipes}{$i}->{'running'} == 1) { + kill('TERM', $self->{pool_pipes}{$i}->{'pid'}); + $self->{logger}->writeLogInfo("Send -TERM signal to pool process.."); + } + } + if (defined($self->{delete_pipes}{'running'}) && $self->{delete_pipes}{'running'} == 1) { + $self->{logger}->writeLogInfo("Send -TERM signal to delete process.."); + kill('TERM', $self->{pid_delete_child}); + } + + ### Write file + if (defined($self->{centstorage_perfdata_file})) { + $self->{centstorage_perfdata_file}->finish(); + } + + if (scalar(keys %{$self->{pool_pipes}}) == 0) { + exit(0); + } + + my $kill_or_not = 1; + for (my $i = 0; $i < $self->{centstorage_config}->{TIMEOUT}; $i++) { + $self->verify_pool(0); + my $running = 0; + for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { + $running += $self->{pool_pipes}{$i}->{'running'} == 1; + } + $running += $self->{delete_pipes}{'running'}; + if ($running == 0) { + $kill_or_not = 0; + last; + } + sleep(1); + } + + if ($kill_or_not == 1) { + for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { + if ($self->{pool_pipes}{$i}->{'running'} == 1) { + kill('KILL', $self->{pool_pipes}{$i}->{'pid'}); + $self->{logger}->writeLogInfo("Send -KILL signal to pool process.."); + } + } + if ($self->{delete_pipes}{'running'} == 1) { + kill('KILL', $self->{pid_delete_child}); + $self->{logger}->writeLogInfo("Send -KILL signal to delete process.."); + } + } + + exit(0); +} + +sub handle_TERM { + my $self = shift; + $self->{logger}->writeLogInfo("$$ Receiving order to stop..."); + die("Quit"); +} + +#### +# First Part +# - Create Pool of child process +#### + +sub verify_pool { + my $self = shift; + my ($create_pool) = @_; + + foreach my $child_pid (keys %{$self->{return_child}}) { + foreach my $pool_num (keys %{$self->{pool_pipes}}) { + if ($self->{pool_pipes}{$pool_num}->{'pid'} == $child_pid) { + $self->{logger}->writeLogInfo("Pool child '$pool_num' is dead"); + $self->{read_select}->remove($self->{pool_pipes}{$pool_num}->{'reader_one'}); + $self->{pool_pipes}{$pool_num}->{'running'} = 0; + if (defined($create_pool) && $create_pool == 1) { + # We have lost one. And if it's the pool rebuild, send progress finish + if ($pool_num == $self->{rebuild_pool_choosen}) { + centstorage::CentstorageLib::call_pool_rebuild_finish(\%{$self->{pool_pipes}}, $self->{centstorage_config}->{pool_childs}, \%{$self->{delete_pipes}}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); + } + $self->create_pool_child($pool_num); + } + delete $self->{return_child}{$child_pid}; + last; + } + } + if ($child_pid == $self->{pid_delete_child}) { + $self->{logger}->writeLogInfo("Delete child is dead"); + $self->{read_select}->remove($self->{delete_pipes}{'reader_one'}); + $self->{delete_pipes}{'running'} = 0; + if (defined($create_pool) && $create_pool == 1) { + $self->create_delete_child(); + } + delete $self->{return_child}{$child_pid}; + } + } +} + +sub create_pool_child { + my $self = shift; + my $pool_num = $_[0]; + + my ($reader_pipe_one, $writer_pipe_one); + my ($reader_pipe_two, $writer_pipe_two); + + pipe($reader_pipe_one, $writer_pipe_one); + pipe($reader_pipe_two, $writer_pipe_two); + $writer_pipe_one->autoflush(1); + $writer_pipe_two->autoflush(1); + + $self->{pool_pipes}{$pool_num} = {}; + $self->{pool_pipes}{$pool_num}->{'reader_one'} = \*$reader_pipe_one; + $self->{pool_pipes}{$pool_num}->{'writer_one'} = \*$writer_pipe_one; + $self->{pool_pipes}{$pool_num}->{'reader_two'} = \*$reader_pipe_two; + $self->{pool_pipes}{$pool_num}->{'writer_two'} = \*$writer_pipe_two; + + $self->{logger}->writeLogInfo("Create Pool child '$pool_num'"); + my $current_pid = fork(); + if (!$current_pid) { + close $self->{pool_pipes}{$pool_num}->{'reader_one'}; + close $self->{pool_pipes}{$pool_num}->{'writer_two'}; + my $centreon_db_centreon = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 1, + logger => $self->{logger}); + $centreon_db_centreon->connect(); + my $centreon_db_centstorage = centreon::db->new(db => $self->{centreon_config}->{centstorage_db}, + host => $self->{centreon_config}->{db_host}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 1, + logger => $self->{logger}); + $centreon_db_centstorage->connect(); + + my $centstorage_rrd = centstorage::CentstorageRRD->new($self->{logger}); + + my $centstorage_pool = centstorage::CentstoragePool->new($self->{logger}, $centstorage_rrd, $self->{rebuild_progress}); + $centstorage_pool->main($centreon_db_centreon, $centreon_db_centstorage, + $self->{pool_pipes}{$pool_num}->{'reader_two'}, $self->{pool_pipes}{$pool_num}->{'writer_one'}, $pool_num, + $self->{centstorage_config}->{rrd_cache_mode}, $self->{centstorage_config}->{rrd_flush_time}, $self->{centstorage_config}->{perfdata_parser_stop}); + exit(0); + } + $self->{pool_pipes}{$pool_num}->{'pid'} = $current_pid; + $self->{pool_pipes}{$pool_num}->{'running'} = 1; + close $self->{pool_pipes}{$pool_num}->{'writer_one'}; + close $self->{pool_pipes}{$pool_num}->{'reader_two'}; + $self->{fileno_save_read}{fileno($self->{pool_pipes}{$pool_num}->{'reader_one'})} = []; + $self->{read_select}->add($self->{pool_pipes}{$pool_num}->{'reader_one'}); +} + +sub create_delete_child { + my $self = shift; + my ($reader_pipe_one, $writer_pipe_one); + my ($reader_pipe_two, $writer_pipe_two); + + + pipe($reader_pipe_one, $writer_pipe_one); + pipe($reader_pipe_two, $writer_pipe_two); + $writer_pipe_one->autoflush(1); + $writer_pipe_two->autoflush(1); + + $self->{delete_pipes}{'reader_one'} = \*$reader_pipe_one; + $self->{delete_pipes}{'writer_one'} = \*$writer_pipe_one; + $self->{delete_pipes}{'reader_two'} = \*$reader_pipe_two; + $self->{delete_pipes}{'writer_two'} = \*$writer_pipe_two; + + $self->{logger}->writeLogInfo("Create delete child"); + my $current_pid = fork(); + if (!$current_pid) { + close $self->{delete_pipes}{'reader_one'}; + close $self->{delete_pipes}{'writer_two'}; + my $centreon_db_centreon = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 1, + logger => $self->{logger}); + $centreon_db_centreon->connect(); + my $centreon_db_centstorage = centreon::db->new(db => $self->{centreon_config}->{centstorage_db}, + host => $self->{centreon_config}->{db_host}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 1, + logger => $self->{logger}); + $centreon_db_centstorage->connect(); + + my $centstorage_action = centstorage::CentstorageAction->new($self->{logger}, $self->{rebuild_progress}, $self->{centstorage_config}->{centreon_23_compatibility}); + $centstorage_action->main($centreon_db_centreon, $centreon_db_centstorage, + $self->{delete_pipes}{'reader_two'}, $self->{delete_pipes}{'writer_one'}); + exit(0); + } + $self->{pid_delete_child} = $current_pid; + close $self->{delete_pipes}{'writer_one'}; + close $self->{delete_pipes}{'reader_two'}; + $self->{delete_pipes}{'running'} = 1; + $self->{fileno_save_read}{fileno($self->{delete_pipes}{'reader_one'})} = []; + $self->{read_select}->add($self->{delete_pipes}{'reader_one'}); +} + +sub handle_CHLD { + my $self = shift; + my $child_pid; + + while (($child_pid = waitpid(-1, &WNOHANG)) > 0) { + $self->{return_child}{$child_pid} = {'exit_code' => $? >> 8}; + } + $SIG{CHLD} = \&class_handle_CHLD; +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + + #### + # Get Main perfdata and status + #### + my $main_perfdata; + my $status; + my $pools_perfdata_filename; + + $self->{centreon_db_centreon} = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 1, + logger => $self->{logger}); + $self->{centreon_db_centreon}->connect(); + $self->handle_DIE("Censtorage option is '0'. Don't have to start") if (centstorage::CentstorageLib::start_or_not($self->{centreon_db_centreon}) == 0); + while (!defined($main_perfdata) || $main_perfdata eq "") { + ($status, $main_perfdata) = centstorage::CentstorageLib::get_main_perfdata_file($self->{centreon_db_centreon}); + if (defined($main_perfdata)) { + $pools_perfdata_filename = centstorage::CentstorageLib::check_pool_old_perfdata_file($main_perfdata, $self->{centstorage_config}->{pool_childs}); + } + } + $self->{centreon_db_centreon}->disconnect(); + + ### + # Check write + ### + if (defined($pools_perfdata_filename)) { + foreach (@$pools_perfdata_filename) { + $self->handle_DIE("Don't have righs on file '$_' (or the directory)") if (centstorage::CentstorageLib::can_write($_) == 0); + } + } + $self->handle_DIE("Don't have righs on file '$main_perfdata' (or the directory)") if (centstorage::CentstorageLib::can_write($main_perfdata) == 0); + + ### + # Create Childs + ### + $self->{read_select} = new IO::Select(); + for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { + $self->create_pool_child($i); + } + $self->create_delete_child(); + + ################## + ################## + + + #### + # Main loop + #### + while (1) { + $self->verify_pool(1); + + ### + # Do pool perfdata if needed + ### + if (defined($pools_perfdata_filename)) { + foreach (@$pools_perfdata_filename) { + $self->{centstorage_perfdata_file} = centstorage::CentstoragePerfdataFile->new($self->{logger}); + $self->{centstorage_perfdata_file}->compute($_, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + } + $pools_perfdata_filename = undef; + } + + ### + # Do main file + ### + $self->{centstorage_perfdata_file} = centstorage::CentstoragePerfdataFile->new($self->{logger}); + $self->{centstorage_perfdata_file}->compute($main_perfdata, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + + ### + # Check response from rebuild + ### + my @rh_set = $self->{read_select}->can_read(10); + foreach my $rh (@rh_set) { + my $read_done = 0; + while ((my ($status_line, $data_element) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{fileno_save_read}{fileno($rh)}}, \$read_done))) { + last if ($status_line <= 0); + if ($data_element =~ /^REBUILDBEGIN/) { + centstorage::CentstorageLib::call_pool_rebuild($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); + } elsif ($data_element =~ /^REBUILDFINISH/) { + centstorage::CentstorageLib::call_pool_rebuild_finish(\%{$self->{pool_pipes}}, $self->{centstorage_config}->{pool_childs}, \%{$self->{delete_pipes}}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); + } elsif ($data_element =~ /^RENAMECLEAN/) { + centstorage::CentstorageLib::call_pool_rename_clean($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + } elsif ($data_element =~ /^RENAMEFINISH/) { + centstorage::CentstorageLib::call_pool_rename_finish($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + } elsif ($data_element =~ /^DELETECLEAN/) { + centstorage::CentstorageLib::call_pool_delete_clean($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + } + } + } + } +} + +1; + +__END__ diff --git a/centreon/lib/perl/centstorage/CentstorageAction.pm b/centreon/lib/perl/centstorage/CentstorageAction.pm new file mode 100644 index 00000000000..ec237f4cb93 --- /dev/null +++ b/centreon/lib/perl/centstorage/CentstorageAction.pm @@ -0,0 +1,287 @@ + +use strict; +use warnings; + +package centstorage::CentstorageAction; + +use centstorage::CentstorageLib; +my %handlers = ('TERM' => {}); + +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"rebuild_progress"} = shift; + $self->{"centreon_23_compatibility"} = shift; + $self->{"dbcentreon"} = undef; + $self->{"dbcentstorage"} = undef; + $self->{"purge_delay"} = 3600; + $self->{"last_purge_time"} = time() - $self->{"purge_delay"} - 5; + + $self->{"deleted_delay"} = 120; + $self->{"last_deleted_time"} = time() - $self->{"deleted_delay"} - 5; + + $self->{"rrd_metrics_path"} = undef; + $self->{"rrd_status_path"} = undef; + + $self->{"save_read"} = []; + + + bless $self, $class; + $self->set_signal_handlers; + return $self; +} + +sub set_signal_handlers { + my $self = shift; + + $SIG{TERM} = \&class_handle_TERM; + $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; +} + +sub handle_TERM { + my $self = shift; + $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); + + $self->{'dbcentreon'}->disconnect() if (defined($self->{'dbcentreon'})); + $self->{'dbcentstorage'}->disconnect() if (defined($self->{'dbcentstorage'})); +} + +sub class_handle_TERM { + foreach (keys %{$handlers{'TERM'}}) { + &{$handlers{'TERM'}->{$_}}(); + } + exit(0); +} + +sub check_deleted { + my $self = shift; + my $pipe_write = $_[0]; + + if (defined($self->{'centreon_23_compatibility'}) && $self->{'centreon_23_compatibility'} == 1) { + return ; + } + + if (time() < ($self->{"last_deleted_time"} + $self->{"deleted_delay"})) { + return ; + } + + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `host_name`, `service_description`, `metrics`.metric_id FROM `index_data` LEFT JOIN `metrics` ON (index_data.id = metrics.index_id) WHERE index_data.to_delete = '1' ORDER BY id"); + return -1 if ($status == -1); + my $current_index_id = -1; + while ((my $data = $stmt->fetchrow_hashref())) { + if ($current_index_id != $data->{'id'}) { + if ($self->delete_rrd_file($self->{"rrd_status_path"}, $data->{'id'}) == 0) { + $self->{'dbcentstorage'}->query("DELETE FROM index_data WHERE id = " . $data->{'id'}); + } + $current_index_id = $data->{'id'}; + print $pipe_write "DELETECLEAN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\n"; + } + if (defined($data->{'metric_id'})) { + if ($self->delete_rrd_file($self->{"rrd_metrics_path"}, $data->{'metric_id'}) == 0) { + $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data->{'metric_id'}); + } + } + } + + ### + # Check metrics alone + ### + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `host_name`, `service_description`, `metrics`.metric_id, `metrics`.metric_name FROM `metrics` LEFT JOIN `index_data` ON (index_data.id = metrics.index_id) WHERE metrics.to_delete = '1'"); + return -1 if ($status == -1); + while ((my $data = $stmt->fetchrow_hashref())) { + if (defined($data->{'host_name'})) { + print $pipe_write "DELETECLEAN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\t" . $data->{'metric_name'} . "\n"; + } + if ($self->delete_rrd_file($self->{"rrd_metrics_path"}, $data->{'metric_id'}) == 0) { + $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data->{'metric_id'}); + } + } + + $self->{"last_deleted_time"} = time(); +} + +sub check_rebuild { + my $self = shift; + my $pipe_write = $_[0]; + + return if ($self->{"rebuild_progress"} == 1); + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `host_name`, `service_description` FROM `index_data` WHERE `must_be_rebuild` IN ('1', '2') LIMIT 1"); + return -1 if ($status == -1); + my $data = $stmt->fetchrow_hashref(); + if (defined($data)) { + $self->{"rebuild_progress"} = 1; + $self->{"logger"}->writeLogInfo("Rebuild detected: " . $data->{'host_name'} . "/" . $data->{'service_description'}); + print $pipe_write "REBUILDBEGIN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\n"; + } +} + +sub delete_rrd_file { + my $self = shift; + my ($path, $id) = @_; + + + if (-e $path . "/" . $id . ".rrd") { + if (unlink($path . "/" . $id . ".rrd")) { + $self->{'logger'}->writeLogInfo("Delete RRD file " . $path . "/" . $id . ".rrd"); + } else { + $self->{'logger'}->writeLogError("Cannot delete RRD file " . $path . "/" . $id . ".rrd: " . $!); + return 1; + } + } + return 0; +} + +sub purge_mysql_and_rrd { + my $self = shift; + my ($status, $stmt, $rows, $data); + my %cache_index_data = (); + my %cache_services = (); + + # Get By direct + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT host_host_id, service_service_id FROM host_service_relation WHERE hostgroup_hg_id IS NULL"); + return -1 if ($status == -1); + $rows = []; + while ($data = (shift(@$rows) || + shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { + $cache_services{$$data[0] . ";" . $$data[1]} = 1; + } + + # Get By Hostgroup + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT host.host_id, host_service_relation.service_service_id FROM host, host_service_relation, hostgroup_relation WHERE host.host_id = hostgroup_relation.host_host_id AND hostgroup_relation.hostgroup_hg_id = host_service_relation.hostgroup_hg_id"); + return -1 if ($status == -1); + $rows = []; + while ($data = (shift(@$rows) || + shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { + $cache_services{$$data[0] . ";" . $$data[1]} = 1; + } + + #### + # Cache Dir + #### + my @files = (); + if (opendir(DIR, $self->{"rrd_status_path"})) { + @files = grep { $_ ne '.' and $_ ne '..' } readdir DIR; + } else { + $self->{'logger'}->writeLogError("Can't opendir " . $self->{"rrd_status_path"} . ": $!"); + } + + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT host_id, service_id, id FROM index_data"); + return -1 if ($status); + $rows = []; + while ($data = (shift(@$rows) || + shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { + $cache_index_data{$$data[2]} = 1; + if (defined($$data[0]) && defined($$data[1]) && !defined($cache_services{$$data[0] . ";" . $$data[1]})) { + ($status, my $stmt2) = $self->{'dbcentstorage'}->query("SELECT metric_id FROM metrics WHERE index_id = '" . $$data[2] . "'"); + next if ($status == -1); + while ((my $data2 = $stmt2->fetchrow_hashref())) { + $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data2->{'metric_id'}); + $self->delete_rrd_file($self->{"rrd_metrics_path"}, $data2->{'metric_id'}); + } + $self->{'dbcentstorage'}->query("DELETE FROM index_data WHERE id = '" . $$data[2] . "'"); + $self->{'logger'}->writeLogInfo("Delete MySQL metrics " . $$data[0] . "/" . $$data[1]); + $self->delete_rrd_file($self->{"rrd_status_path"}, $$data[2]); + } + } + + ### + # Purge RRD Status + ### + foreach (@files) { + if ($_ =~ /(.*)\.rrd$/ && !defined($cache_index_data{$1})) { + $self->delete_rrd_file($self->{"rrd_status_path"}, $1); + } + } + + ### + # Purge RRD Metrics + ### + @files = (); + if (opendir(DIR, $self->{"rrd_metrics_path"})) { + @files = grep { $_ ne '.' and $_ ne '..' } readdir DIR; + } else { + $self->{'logger'}->writeLogError("Can't opendir " . $self->{"rrd_metrics_path"} . ": $!"); + } + + my %cache_metrics_data = (); + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id FROM metrics"); + return -1 if ($status == -1); + $rows = []; + while ($data = (shift(@$rows) || + shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { + $cache_metrics_data{$$data[0]} = 1; + } + + foreach (@files) { + if ($_ =~ /(.*)\.rrd$/ && !defined($cache_metrics_data{$1})) { + $self->delete_rrd_file($self->{"rrd_metrics_path"}, $1); + } + } +} + +sub get_centstorage_information { + my $self = shift; + my ($rrd_metrics_path, $rrd_status_path); + + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT RRDdatabase_path, RRDdatabase_status_path FROM config"); + my $data = $stmt->fetchrow_hashref(); + if (defined($data)) { + $rrd_metrics_path = $data->{'RRDdatabase_path'}; + $rrd_status_path = $data->{'RRDdatabase_status_path'}; + } + return ($status, $rrd_metrics_path, $rrd_status_path); +} + +sub check_purge { + my $self = shift; + + if (time() < ($self->{"last_purge_time"} + $self->{"purge_delay"})) { + return ; + } + + $self->purge_mysql_and_rrd(); + $self->{"last_purge_time"} = time(); +} + +sub main { + my $self = shift; + my ($dbcentreon, $dbcentstorage, $pipe_read, $pipe_write) = @_; + my $status; + + $self->{'dbcentreon'} = $dbcentreon; + $self->{'dbcentstorage'} = $dbcentstorage; + + ($status, $self->{"rrd_metrics_path"}, $self->{"rrd_status_path"}) = $self->get_centstorage_information(); + + # We have to manage if you don't need infos + $self->{'dbcentreon'}->force(0); + $self->{'dbcentstorage'}->force(0); + + my $read_select = new IO::Select(); + $read_select->add($pipe_read); + while (1) { + my @rh_set = $read_select->can_read(5); + if (scalar(@rh_set) > 0) { + foreach my $rh (@rh_set) { + my $read_done = 0; + while ((my ($status_line, $readline) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + class_handle_TERM() if ($status_line == -1); + last if ($status_line == 0); + my ($method, @fields) = split(/\t/, $readline); + + # Check Type + if (defined($method) && $method eq "REBUILDFINISH") { + $self->{"rebuild_progress"} = 0; + } + } + } + } else { + $self->check_rebuild($pipe_write); + $self->check_deleted($pipe_write); + $self->check_purge(); + } + } +} + +1; diff --git a/centreon/lib/perl/centstorage/CentstorageLib.pm b/centreon/lib/perl/centstorage/CentstorageLib.pm new file mode 100644 index 00000000000..3c5e012e4b4 --- /dev/null +++ b/centreon/lib/perl/centstorage/CentstorageLib.pm @@ -0,0 +1,195 @@ + +package centstorage::CentstorageLib; +use File::Basename; + +my $read_size = 1*1024*1024*10; # 10Mo + +sub start_or_not { + my ($centreon_db_centreon) = @_; + my $status = 1; + + my ($status2, $stmt) = $centreon_db_centreon->query("SELECT value FROM options WHERE `key` = 'centstorage' LIMIT 1"); + my $data = $stmt->fetchrow_hashref(); + if (defined($data) && int($data->{'value'}) == 0) { + $status = 0; + } + return $status; +} + +sub get_main_perfdata_file { + my ($centreon_db_centreon) = @_; + my $filename; + + my ($status, $stmt) = $centreon_db_centreon->query("SELECT `nagios_perfdata` FROM `nagios_server` WHERE `localhost` = '1'"); + my $data = $stmt->fetchrow_hashref(); + if (defined($data)) { + $filename = $data->{'nagios_perfdata'}; + } + return ($status, $filename); +} + +sub check_pool_old_perfdata_file { + my ($main_filename, $num_pool) = @_; + + my @files = (); + for (my $i = 0; $i < $num_pool; $i++) { + if (-e $main_filename . "_" . $i . ".bckp_read") { + push @files, $main_filename . "_" . $i . ".bckp_read"; + } + if (-e $main_filename . "_" . $i . ".bckp") { + push @files, $main_filename . "_" . $i . ".bckp"; + } + } + + if (-e $main_filename . "_read") { + push @files, $main_filename . "_read"; + } + return \@files; +} + +sub call_pool_rebuild { + my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs, $rebuild_progress, $rebuild_pool_choosen) = @_; + + # Send Info + my ($method, $host_name, $service_description) = split(/\t/, $line); + my $pool_choosen; + if (!defined($routing_services->{$host_name . ";" . $service_description})) { + my $pool_num = $$roundrobin_pool_current % $pool_childs; + $$roundrobin_pool_current++; + $routing_services->{$host_name . ";" . $service_description} = $pool_num; + } + $pool_choosen = $routing_services->{$host_name . ";" . $service_description}; + for ($i = 0; $i < $pool_childs; $i++) { + if ($i == $pool_choosen) { + my $fh = $pool_pipes->{$i}->{'writer_two'}; + # It's when you loose a pool. You have to know + $$rebuild_progress = 1; + $$rebuild_pool_choosen = $pool_choosen; + print $fh "REBUILDBEGIN\t$host_name\t$service_description\n"; + } else { + my $fh = $pool_pipes->{$i}->{'writer_two'}; + print $fh "REBUILDBEGIN\n"; + } + } +} + +sub call_pool_rebuild_finish { + my ($pool_pipes, $pool_childs, $delete_pipes, $rebuild_progress, $rebuild_pool_choosen) = @_; + my $fh; + + $$rebuild_progress = 0; + $$rebuild_pool_choosen = -1; + for ($i = 0; $i < $pool_childs; $i++) { + if ($rebuild_pool_choosen != $i) { + $fh = $pool_pipes->{$i}->{'writer_two'}; + print $fh "REBUILDFINISH\n"; + } + } + $fh = $delete_pipes->{'writer_two'}; + print $fh "REBUILDFINISH\n"; +} + +sub call_pool_rename_clean { + my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs) = @_; + + my ($method, $old_host_name, $old_service_description, $new_host_name, $new_service_description) = split(/\t/, $line); + my $pool_choosen; + if (!defined($routing_services->{$old_host_name . ";" . $old_service_description})) { + # There is no for the old name. Can go back + my $fh = $pool_pipes->{$routing_services->{$new_host_name . ";" . $new_service_description}}->{'writer_two'}; + print $fh "RENAMEFINISH\t" . $new_host_name . "\t" . $new_service_description . "\n"; + return ; + } + # Send to clean + my $fh = $pool_pipes->{$routing_services->{$old_host_name . ";" . $old_service_description}}->{'writer_two'}; + print $fh "RENAMECLEAN\t" . $old_host_name . "\t" . $old_service_description . "\t" . $new_host_name . "\t" . $new_service_description . "\n"; +} + +sub call_pool_rename_finish { + my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs) = @_; + + my ($method, $new_host_name, $new_service_description) = split(/\t/, $line); + if (defined($routing_services->{$new_host_name . ";" . $new_service_description})) { + my $fh = $pool_pipes->{$routing_services->{$new_host_name . ";" . $new_service_description}}->{'writer_two'}; + print $fh "RENAMEFINISH\t" . $new_host_name . "\t" . $new_service_description . "\n"; + return ; + } +} + +sub call_pool_delete_clean { + my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs) = @_; + + my ($method, $host_name, $service_description) = split(/\t/, $line); + if (!defined($routing_services->{$host_name . ";" . $service_description})) { + # No cache. so we return + return ; + } + my $fh = $pool_pipes->{$routing_services->{$host_name . ";" . $service_description}}->{'writer_two'}; + print $fh "$line\n"; +} + +sub can_write { + my $file = $_[0]; + my $dir = dirname($file); + + return 0 if (-d $dir && ! -w $dir); + return 0 if (-e $file && ! -w $file); + return 1; +} + +sub get_line_file { + my ($fh, $datas, $readed) = @_; + my $line; + my $size = scalar(@$datas); + + return (1, shift(@$datas)) if ($size > 1); + while ((my $eof = sysread($fh, $line, $read_size))) { + my @result = split("\n", $line); + if ($line =~ /\n$/) { + push @result, ""; + } + if ($size == 1) { + $$datas[0] .= shift(@result); + } + push @$datas, @result; + $$readed += $eof; + $size = scalar(@$datas); + if ($size > 1) { + return (1, shift(@$datas)); + } + } + return (1, shift(@$datas)) if ($size > 1); + return -1; +} + +sub get_line_pipe { + my ($fh, $datas, $read_done) = @_; + my $line; + my $size = scalar(@$datas); + + if ($size > 1) { + return (1, shift(@$datas)); + } elsif ($size == 1 && $$read_done == 1) { + return 0; + } + while ((my $eof = sysread($fh, $line, 10000))) { + $$read_done = 1; + my @result = split("\n", $line); + if ($line =~ /\n$/) { + push @result, ""; + } + if ($size == 1) { + $$datas[0] .= shift(@result); + } + push @$datas, @result; + $size = scalar(@$datas); + if ($size > 1) { + return (1, shift(@$datas)); + } else { + return 0; + } + } + return -1; +} + +1; diff --git a/centreon/lib/perl/centstorage/CentstoragePerfdataFile.pm b/centreon/lib/perl/centstorage/CentstoragePerfdataFile.pm new file mode 100644 index 00000000000..9b5cf8bf73b --- /dev/null +++ b/centreon/lib/perl/centstorage/CentstoragePerfdataFile.pm @@ -0,0 +1,124 @@ + +use strict; +use warnings; +use File::Copy; + +package centstorage::CentstoragePerfdataFile; +use centstorage::CentstorageLib; +my $end_size_buffer = 1*1024*1024*10; # 10Mo + +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"filehandler"} = undef; + $self->{"filename"} = undef; + $self->{"eof_file"} = 0; + $self->{"readed"} = 0; + $self->{"buffer"} = []; + bless $self, $class; + return $self; +} + +sub compute { + my $self = shift; + $self->{'filename'} = $_[0]; + my ($pool_pipes, $routing_services, $roundrobin_pool_current, $total_pool) = ($_[1], $_[2], $_[3], $_[4]); + + if ($self->{'filename'} !~ /_read$/) { + if (!(File::Copy::move($self->{'filename'}, $self->{'filename'} . "_read"))) { + $self->{"logger"}->writeLogError("Cannot move " . $self->{'filename'} . " file : $!"); + return -1; + } + if (!open($self->{"filehandler"}, '+< ' . $self->{"filename"} . "_read")) { + $self->{"logger"}->writeLogError("Cannot open " . $self->{'filename'} . "_read file : $!"); + return -1; + } + } else { + $self->{'filename'} =~ s/_read$//; + if (!open($self->{"filehandler"}, '+< ' . $self->{"filename"} . "_read")) { + $self->{"logger"}->writeLogError("Cannot open " . $self->{'filename'} . "_read file : $!"); + return -1; + } + } + + # Get offset if exist + if (-e $self->{'filename'} . "_read.offset") { + if (!open(FILE, "<", $self->{'filename'} . "_read.offset")) { + $self->{"logger"}->writeLogError("Can't read " . $self->{'filename'} . "_read.offset file: $!"); + return -1; + } + my $offset = ; + close FILE; + chomp $offset; + $offset = int($offset); + if ($offset =~ /^[0-9]+$/) { + seek($self->{"filehandler"}, $offset, 1); + $self->{"readed"} = $offset; + } + unlink($self->{'filename'} . "_read.offset"); + } + + my $fh = $self->{"filehandler"}; + while ((my ($status, $readline) = centstorage::CentstorageLib::get_line_file($fh, \@{$self->{"buffer"}}, \$self->{"readed"}))) { + last if ($status == -1); + $readline =~ /([0-9]+?)\t+?([^\t]+?)\t+?([^\t]+?)\t/; + if (defined($1) && defined($2) && defined($3)) { + if (defined($routing_services->{$2 . ";" . $3})) { + my $tmp_fh = $pool_pipes->{$routing_services->{$2 . ";" . $3}}->{'writer_two'}; + print $tmp_fh "UPDATE\t$readline\n"; + } else { + # Choose a pool + my $pool_num = $$roundrobin_pool_current % $total_pool; + $$roundrobin_pool_current++; + my $tmp_fh = $pool_pipes->{$pool_num}->{'writer_two'}; + print $tmp_fh "UPDATE\t$readline\n"; + $routing_services->{$2 . ";" . $3} = $pool_num; + } + } + } + + $self->{"eof_file"} = 1; + $self->finish(); + return 0; +} + +sub finish { + my $self = shift; + + if (defined($self->{"filehandler"})) { + my $fh = $self->{"filehandler"}; + if ($self->{"eof_file"} == 1) { + if (!unlink($self->{"filename"} . "_read")) { + $self->{"logger"}->writeLogError("Cannot unlink " . $self->{'filename'} . "_read file : $!\n"); + } + close($fh); + } else { + $self->{"logger"}->writeLogInfo("Write Offset File " . $self->{'filename'} . "_read.offset file\n"); + if (open(FILE, ">", $self->{'filename'} . "_read.offset")) { + require bytes; + + my $offset = $self->{"readed"}; + for (my $i = scalar(@{$self->{"buffer"}}) - 1; $i >= 0; $i--) { + $offset = $offset - bytes::length(${$self->{"buffer"}}[$i]) - 1; # -1 = \n + } + # Last: Don't have \n + $offset += 1; + print FILE $offset . "\n"; + close FILE; + } else { + $self->{"logger"}->writeLogError("Can't write offset " . $self->{'filename'} . "_read.offset file: $!\n"); + # Slurp File + my $rs_save = $/; + undef $/; + my $content_file = <$fh>; + seek($fh, 0, 0); + truncate($fh, 0); + print $fh $content_file; + $/ = $rs_save; + } + } + } +} + +1; diff --git a/centreon/lib/perl/centstorage/CentstoragePool.pm b/centreon/lib/perl/centstorage/CentstoragePool.pm new file mode 100644 index 00000000000..975af4beb75 --- /dev/null +++ b/centreon/lib/perl/centstorage/CentstoragePool.pm @@ -0,0 +1,1098 @@ + +use strict; +use warnings; + +package centstorage::CentstoragePool; + +use centreon::db; +use centstorage::CentstorageLib; +use centstorage::CentstorageRebuild; +my %handlers = ('TERM' => {}, 'CHLD' => {}); +my %rrd_trans = ("g" => 0, "c" => 1, "d" => 2, "a" => 3); + +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"rrd"} = shift; + $self->{"rebuild_progress"} = shift; + $self->{"dbcentreon"} = undef; + $self->{"dbcentstorage"} = undef; + + $self->{"len_storage_rrd"} = undef; + $self->{"rrd_metrics_path"} = undef; + $self->{"rrd_status_path"} = undef; + $self->{"main_perfdata_file"} = undef; + $self->{"interval_time"} = undef; + $self->{"do_rrd_status"} = 1; + $self->{"TIMEOUT"} = 30; + $self->{"num_pool"} = undef; + # If rebuild in progress, we don't try to insert in DATA_BIN + + $self->{"storage_type"} = undef; + # { + # 'metrics' => {'name1' => {}, 'name2' => {} } + # 'service_id' => + # 'host_id' => + # 'storage_type' => + # 'check_interval' => + # 'index_id' => + # 'rebuild' => + # 'rrd_retention' => + # } + $self->{"cache_service"} = {}; + + # Perfdata parsing vars + $self->{"perfdata_pos"} = undef; + $self->{"perfdata_size"} = undef; + $self->{"perfdata_chars"} = undef; + + $self->{"perfdata_parser_stop"} = 0; + + $self->{"service_perfdata"} = undef; + $self->{"metric_name"} = undef; + $self->{"metric_value"} = undef; + $self->{"metric_unit"} = undef; + $self->{"metric_warn"} = undef; + $self->{"metric_crit"} = undef; + $self->{"metric_min"} = undef; + $self->{"metric_max"} = undef; + + # By service + $self->{"cache_services_failed"} = {}; + $self->{"last_check_failed"} = time(); + $self->{"check_failed_every"} = 60 * 10; # 20 minutes + + # Rename + $self->{"cache_services_rename"} = {}; + $self->{"rename_rebuild_wait"} = 0; + $self->{"rename_old_new"} = {}; + + $self->{"group_databin_stmt"} = ""; + $self->{"group_databin_total"} = 0; + $self->{"group_databin_append"} = ""; + $self->{"group_databin_max"} = 500; + + $self->{"rebuild_index_id"} = undef; + $self->{"rebuild_key"} = undef; + $self->{"current_pid"} = undef; + + $self->{"save_read"} = []; + $self->{"read_select"} = undef; + $self->{"pipe_write"} = undef; + bless $self, $class; + $self->set_signal_handlers; + return $self; +} + +sub set_signal_handlers { + my $self = shift; + + $SIG{TERM} = \&class_handle_TERM; + $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; + $SIG{CHLD} = \&class_handle_CHLD; + $handlers{'CHLD'}->{$self} = sub { $self->handle_CHLD() }; +} + +sub handle_TERM { + my $self = shift; + $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); + + if (defined($self->{"current_pid"})) { + $self->{'logger'}->writeLogInfo("Send -TERM signal to rebuild process.."); + kill('TERM', $self->{"current_pid"}); + } + + ### + # Flush Data_bin + ### + eval { + local $SIG{ALRM} = sub { die "alarm\n" }; + alarm 5; + $self->flush_mysql(1); + alarm 0; + }; + if ($@) { + $self->{'dbcentstorage'}->kill(); + } + $self->{'dbcentreon'}->disconnect() if (defined($self->{'dbcentreon'})); + $self->{'dbcentstorage'}->disconnect() if (defined($self->{'dbcentstorage'})); + + ### + # Flush RRD + ### + $self->{'rrd'}->flush_all(1); + + ### + # Write In File + ### + if (open(FILE, '>> ' . $self->{"main_perfdata_file"} . "_" . $self->{'num_pool'} . ".bckp")) { + foreach my $id (keys %{$self->{"cache_services_failed"}}) { + foreach (@{$self->{"cache_services_failed"}->{$id}}) { + print FILE join("\t", @$_) . "\n"; + } + } + + # Rename + foreach my $id (keys %{$self->{"cache_services_rename"}}) { + foreach (@{$self->{"cache_services_rename"}->{$id}}) { + print FILE join("\t", @$_) . "\n"; + } + } + + + ### Try to read pipe + my @rh_set = $self->{'read_select'}->can_read(1); + if (scalar(@rh_set) > 0) { + foreach my $rh (@rh_set) { + my $read_done = 0; + while ((my ($status_line, $readline) = CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + last if ($status_line <= 0); + if ($readline =~ /^UPDATE/) { + $readline =~ s/^UPDATE\t//; + print FILE $readline . "\n"; + } + } + } + } + close FILE; + } else { + $self->{"logger"}->writeLogError("Cannot open " . $self->{"main_perfdata_file"} . "_" . $self->{'num_pool'} . ".bckp file : $!"); + } + + ### + # Check Child + ### + my $kill_or_not = 1; + for (my $i = 0; $i < $self->{"TIMEOUT"}; $i++) { + if (!defined($self->{"current_pid"})) { + $kill_or_not = 0; + last; + } + sleep(1); + } + + if ($kill_or_not == 1) { + $self->{'logger'}->writeLogInfo("Send -KILL signal to rebuild process.."); + kill('KILL', $self->{"current_pid"}); + } +} + +sub handle_CHLD { + my $self = shift; + my $child_pid; + my $exit_code; + + $self->{'logger'}->writeLogInfo("Received SIGCHLD..."); + $self->{"current_pid"} = undef; + if ($self->{"rename_rebuild_wait"} == 1) { + my ($new_host_name, $new_service_description) = split(';', $self->{"rename_old_new"}->{$self->{"rebuild_key"}}); + $self->force_flush_rrd($self->{"rebuild_key"}); + delete $self->{"cache_service"}->{$self->{"rebuild_key"}}; + delete $self->{"cache_services_failed"}->{$self->{"rebuild_key"}}; + delete $self->{"rename_old_new"}->{$self->{"rebuild_key"}}; + $self->send_rename_finish($new_host_name, $new_service_description); + } + $self->rebuild_finish(); + while (($child_pid = waitpid(-1, &POSIX::WNOHANG)) > 0) { + $exit_code = $? >> 8; + } + $SIG{CHLD} = \&class_handle_CHLD; +} + +sub class_handle_TERM { + foreach (keys %{$handlers{'TERM'}}) { + &{$handlers{'TERM'}->{$_}}(); + } + exit(0); +} + +sub class_handle_CHLD { + foreach (keys %{$handlers{'CHLD'}}) { + &{$handlers{'CHLD'}->{$_}}(); + } +} + +sub add_data_mysql { + my $self = shift; + my ($metric_id, $ctime, $value) = @_; + + $self->{"group_databin_stmt"} .= $self->{"group_databin_append"} . "('$metric_id', '$ctime', '$value')"; + $self->{"group_databin_append"} = ", "; + $self->{"group_databin_total"}++; +} + +sub force_flush_rrd { + my $self = shift; + my ($key) = @_; + + if (defined($self->{"cache_service"}->{$key})) { + foreach (keys %{$self->{"cache_service"}->{$key}->{'metrics'}}) { + $self->{'rrd'}->flush_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$_}->{'metric_id'}); + } + + $self->{'rrd'}->flush_status($self->{"cache_service"}->{$key}->{'index_id'}); + } +} + +sub flush_mysql { + my $self = shift; + my ($force) = @_; + + return 0 if ($self->{"rebuild_progress"} == 1 && (!defined($force) || $force == 0)); + if ((defined($force) && $force == 1 && $self->{"group_databin_total"} > 0) || $self->{"group_databin_total"} > $self->{"group_databin_max"}) { + my $rq = "INSERT INTO `data_bin` (`id_metric`, `ctime`, `value`) VALUES " . $self->{"group_databin_stmt"}; + my ($status, $stmt) = $self->{'dbcentstorage'}->query($rq); + $self->{"group_databin_total"} = 0; + $self->{"group_databin_append"} = ""; + $self->{"group_databin_stmt"} = ""; + } +} + +sub flush_failed { + my $self = shift; + + if (time() > ($self->{"last_check_failed"} + $self->{"check_failed_every"})) { + # Need to reconnect (maybe a gone away. So we try) + $self->{'dbcentreon'}->disconnect(); + $self->{'dbcentreon'}->connect(); + + $self->{'logger'}->writeLogInfo("Begin Cache Services Failed"); + foreach my $id (keys %{$self->{"cache_services_failed"}}) { + next if ($self->{"rebuild_progress"} == 1 && $id == $self->{"rebuild_key"}); + my @tmp_ar = (); + my $lerror = 0; + foreach (@{$self->{"cache_services_failed"}->{$id}}) { + if ($lerror == 0 && $self->update(1, @$_) != 0) { + push @tmp_ar, \@$_; + $lerror = 1; + } else { + push @tmp_ar, \@$_; + } + } + if (scalar(@tmp_ar) != 0) { + @{$self->{"cache_services_failed"}->{$id}} = @tmp_ar; + } else { + delete $self->{"cache_services_failed"}->{$id}; + } + } + $self->{"last_check_failed"} = time(); + } +} + +sub remove_special_char_metric { + my $self = shift; + my $remove_special_char = $_[0]; + + $remove_special_char =~ s/\./\-/g; + $remove_special_char =~ s/\,/\-/g; + $remove_special_char =~ s/\:/\-/g; + $remove_special_char =~ s/\ /\-/g; + return $remove_special_char; +} + +sub create_metric { + my $self = shift; + my ($index_id, $cache_metrics, $metric_name) = @_; + + # Check if exists already + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT * FROM `metrics` WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($metric_name) . " LIMIT 1"); + return -1 if ($status == -1); + my $data = $stmt->fetchrow_hashref(); + # move part for compat with old centstorage name + if (!defined($data)) { + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT * FROM `metrics` WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($self->remove_special_char_metric($metric_name)) . " LIMIT 1"); + return -1 if ($status == -1); + $data = $stmt->fetchrow_hashref(); + if (defined($data)) { + ($status) = $self->{'dbcentstorage'}->query("UPDATE `metrics` SET `metric_name` = " . $self->{'dbcentstorage'}->quote($metric_name) . " WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($self->remove_special_char_metric($metric_name)) . " LIMIT 1"); + return -1 if ($status == -1); + } else { + # Insert + ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `metrics` (`index_id`, `metric_name`, `unit_name`, `warn`, `crit`, `min`, `max`, `data_source_type`) VALUES ('" . $index_id . "', " . $self->{'dbcentstorage'}->quote($metric_name) . ", '" . $self->{"metric_unit"} . "', '" . $self->{"metric_warn"} . "', '" . $self->{"metric_crit"} . "', '" . $self->{"metric_min"} . "', '" . $self->{"metric_max"} . "', '" . $self->{"metric_type"} . "')"); + return -1 if ($status); + my $last_insert_id = $self->{'dbcentstorage'}->last_insert_id(); + $$cache_metrics->{$metric_name} = {'metric_id' => $last_insert_id, 'metric_unit' => $self->{"metric_unit"}, 'metric_warn' => $self->{"metric_warn"}, 'metric_crit' => $self->{"metric_crit"}, 'metric_min' => $self->{"metric_min"}, 'metric_max' => $self->{"metric_max"}, 'data_source_type' => $self->{"metric_type"}}; + + return 0; + } + } + # We get + $$cache_metrics->{$metric_name} = {'metric_id' => $data->{'metric_id'}, 'metric_unit' => defined($data->{"unit_name"}) ? $data->{"unit_name"} : "", 'metric_warn' => defined($data->{"warn"}) ? $data->{"warn"} : "", 'metric_crit' => defined($data->{"crit"}) ? $data->{"crit"} : "", 'metric_min' => defined($data->{"min"}) ? $data->{"min"} : "", 'metric_max' => defined($data->{"max"}) ? $data->{"max"} : "", 'data_source_type' => $data->{"data_source_type"}}; + return 0; +} + +sub check_update_extra_metric { + my $self = shift; + my $cache_metric = $_[0]; + + if ($$cache_metric->{'metric_unit'} ne $self->{"metric_unit"} || + $$cache_metric->{'metric_warn'} ne $self->{"metric_warn"} || + $$cache_metric->{'metric_crit'} ne $self->{"metric_crit"} || + $$cache_metric->{'metric_min'} ne $self->{"metric_min"} || + $$cache_metric->{'metric_max'} ne $self->{"metric_max"}) { + $self->{'dbcentstorage'}->query("UPDATE `metrics` SET `unit_name` = " . $self->{'dbcentstorage'}->quote($self->{"metric_unit"}) . ", `warn` = '" . $self->{"metric_warn"} . "', `crit` = '" . $self->{"metric_crit"} . "', `min` = '" . $self->{"metric_min"} . "', `max` = '" . $self->{"metric_max"} . "' WHERE `metric_id` = " . $$cache_metric->{'metric_id'}); + $$cache_metric->{'metric_unit'} = $self->{"metric_unit"}; + $$cache_metric->{'metric_warn'} = $self->{"metric_warn"}; + $$cache_metric->{'metric_crit'} = $self->{"metric_crit"}; + $$cache_metric->{'metric_min'} = $self->{"metric_min"}; + $$cache_metric->{'metric_max'} = $self->{"metric_max"}; + } +} + +sub send_rename_command { + my $self = shift; + my ($old_host_name, $old_service_description, $new_host_name, $new_service_description) = @_; + + $self->{'logger'}->writeLogInfo("Hostname/Servicename changed had been detected " . $old_host_name . "/" . $old_service_description); + my $fh = $self->{'pipe_write'}; + print $fh "RENAMECLEAN\t" . $old_host_name . "\t" . $old_service_description . "\t" . $new_host_name . "\t" . $new_service_description . "\n"; +} + +sub create_service { + my $self = shift; + my ($host_id, $service_id, $interval, $host_name, $service_description) = @_; + my ($status, $stmt); + + if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `storage_type`, `host_name`, `service_description`, `rrd_retention` FROM `index_data` WHERE `host_name` = " . $self->{'dbcentstorage'}->quote($host_name) . " AND `service_description` = " . $self->{'dbcentstorage'}->quote($service_description) . " LIMIT 1"); + } else { + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `storage_type`, `host_name`, `service_description`, `rrd_retention` FROM `index_data` WHERE `host_id` = " . $host_id . " AND `service_id` = " . $service_id . " LIMIT 1"); + } + return -1 if ($status == -1); + my $data = $stmt->fetchrow_hashref(); + if (defined($data) && ($data->{'host_name'} ne $host_name || $data->{'service_description'} ne $service_description)) { + ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE `index_data` SET `host_name` = " . $self->{'dbcentstorage'}->quote($host_name) . ", `service_description` = " . $self->{'dbcentreon'}->quote($service_description) . " WHERE id = " . $data->{'id'}); + if ($status != -1) { + $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = int($data->{'storage_type'}); + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $data->{'id'}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; + # Send command to clean cache + $self->send_rename_command($data->{'host_name'}, $data->{'service_description'}, $host_name, $service_description); + return -2; + } + } elsif (defined($data) && ($data->{'host_name'} eq $host_name || $data->{'service_description'} eq $service_description)) { + # same name but exist already + $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = int($data->{'storage_type'}); + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $data->{'id'}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; + } else { + # create + if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { + ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `index_data` (`host_name`, `service_description`, `host_id`, `service_id`, `special`, `storage_type`) VALUES (" . $self->{'dbcentstorage'}->quote($host_name) . ", " . $self->{'dbcentstorage'}->quote($service_description) . ", " . $host_id . ", " . $service_id . ", '1', '" . $self->{'storage_type'} . "')"); + } else { + ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `index_data` (`host_name`, `service_description`, `host_id`, `service_id`, `storage_type`) VALUES (" . $self->{'dbcentstorage'}->quote($host_name) . ", " . $self->{'dbcentstorage'}->quote($service_description) . ", " . $host_id . ", " . $service_id . ", '" . $self->{'storage_type'} . "')"); + } + if ($status != -1) { + $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = $self->{'storage_type'}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $self->{'dbcentstorage'}->last_insert_id(); + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = -1; + } + } + + return $status; +} + +sub get_centstorage_information { + my $self = shift; + my ($len_storage_rrd, $rrd_metrics_path, $rrd_status_path, $storage_type); + + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT len_storage_rrd, RRDdatabase_path, RRDdatabase_status_path, storage_type FROM config"); + my $data = $stmt->fetchrow_hashref(); + if (defined($data)) { + $len_storage_rrd = int($data->{'len_storage_rrd'}); + $rrd_metrics_path = $data->{'RRDdatabase_path'}; + $rrd_status_path = $data->{'RRDdatabase_status_path'}; + $storage_type = int($data->{'storage_type'}); + } + return ($status, $len_storage_rrd, $rrd_metrics_path, $rrd_status_path, $storage_type); +} + +sub get_centreon_intervaltime { + my $self = shift; + my $interval = 60; + + my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT `value` AS interval_length FROM options WHERE `key` = 'interval_length'"); + my $data = $stmt->fetchrow_hashref(); + if (defined($data)) { + $interval = $data->{'interval_length'}; + } + return (0, $interval); +} + +############################# +### Perfdata Handle +############################# + +sub trim { + my $self = shift; + $_[0] =~ s/^[ \t]*?//; + $_[0] =~ s/[ \t]*?$//; + return $_[0]; +} + +sub skip_chars { + my $self = shift; + $self->{"perfdata_pos"}++ while ($self->{"perfdata_pos"} < $self->{"perfdata_size"} && (${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] =~ /$_[0]/)); +} + +sub continue_to { + my $self = shift; + my ($forbidden, $stop1, $not_stop_after) = @_; + my $value = ""; + + while ($self->{"perfdata_pos"} < $self->{"perfdata_size"}) { + if (defined($forbidden) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] =~ /$forbidden/) { + return undef; + } + if (${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] =~ /$stop1/) { + if (!defined($not_stop_after)) { + return $value; + } + if (!($self->{"perfdata_pos"} + 1 < $self->{"perfdata_size"} && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"} + 1] =~ /$not_stop_after/)) { + $self->{"perfdata_pos"}++; + return $value; + } + $self->{"perfdata_pos"}++; + } + + $value .= ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]; + $self->{"perfdata_pos"}++; + } + + return $value; +} + +sub parse_label { + my $self = shift; + my $label; + + if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "'") { + $self->{"perfdata_pos"}++; + $label = $self->continue_to(undef, "'", "'"); + } else { + $label = $self->continue_to("[ \t]", "="); + } + $self->{"perfdata_pos"}++; + + return $label; +} + +sub parse_value { + my $self = shift; + my $value = ""; + my $neg = 1; + + if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "-") { + $neg = -1; + $self->{"perfdata_pos"}++; + } + + $value = $self->continue_to(undef, "[^0-9\.,]"); + if (defined($value) && $value ne "") { + $value =~ s/,/./g; + $value = $value * $neg; + } + $self->skip_chars(";"); + return $value; +} + +sub parse_unit { + my $self = shift; + my $value = ""; + + $value = $self->continue_to(undef, "[ \t;]"); + $self->skip_chars(";"); + return $value; +} + +sub parse_threshold { + my $self = shift; + my $value = ""; + + $value = $self->continue_to(undef, "[ \t;]"); + $self->skip_chars(";"); + return $value; +} + +sub get_perfdata { + my $self = shift; + my ($counter_type, $perf_label, $perf_value, $perf_unit, $perf_warn, $perf_crit, $perf_min, $perf_max); + + if (!defined($self->{'service_perfdata'}) || $self->{"perfdata_pos"} >= $self->{"perfdata_size"}) { + return 0; + } + + $self->skip_chars("[ \t]"); + $perf_label = $self->parse_label(); + if (!defined($perf_label) || $perf_label eq '') { + $self->{"logger"}->writeLogError("Wrong perfdata format: " . $self->{'service_perfdata'}); + return 0 if ($self->{'perfdata_parser_stop'} == 1); + return 1; + } + + $perf_value = $self->parse_value(); + if (!defined($perf_value) || $perf_value eq '') { + $self->{"logger"}->writeLogError("Wrong perfdata format: " . $self->{'service_perfdata'}); + return 0 if ($self->{'perfdata_parser_stop'} == 1); + return 1; + } + + $perf_unit = $self->parse_unit(); + + $perf_warn = $self->parse_threshold(); + $perf_crit = $self->parse_threshold(); + $perf_min = $self->parse_value(); + $perf_max = $self->parse_value(); + + $perf_label = $self->trim($perf_label); + $counter_type = 'g'; + if ($perf_label =~ /^([adc])\[(.*?)\]$/) { + $counter_type = $1; + $perf_label = $2; + if (!defined($perf_label) || $perf_label eq '') { + $self->{"logger"}->writeLogError("Wrong perfdata format: " . $self->{'service_perfdata'}); + return 0 if ($self->{'perfdata_parser_stop'} == 1); + return 1; + } + } + + # Can't manage threshold well (db not ready) + if ($perf_warn =~ /[^0-9-.,]/) { + $perf_warn = ""; + } + if ($perf_crit =~ /[^0-9-.,]/) { + $perf_crit = ""; + } + + $self->{"metric_name"} = $perf_label; + $self->{"metric_value"} = $perf_value; + $self->{"metric_unit"} = $perf_unit; + $self->{"metric_warn"} = $perf_warn; + $self->{"metric_crit"} = $perf_crit; + $self->{"metric_min"} = $perf_min; + $self->{"metric_max"} = $perf_max; + $self->{"metric_type"} = $rrd_trans{$counter_type}; + + return 1; +} + +sub init_perfdata { + my $self = shift; + + if (!defined($self->{'service_perfdata'})) { + return ; + } + @{$self->{"perfdata_chars"}} = split //, $self->trim($self->{'service_perfdata'}); + $self->{"perfdata_pos"} = 0; + $self->{"perfdata_size"} = scalar(@{$self->{"perfdata_chars"}}); +} + +###################################################### + +sub cache_update_service_index_data { + my $self = shift; + my ($key) = @_; + + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT rrd_retention FROM index_data WHERE id = " . $self->{"cache_service"}->{$key}->{'index_id'}); + if ($status == -1) { + $self->{'logger'}->writeLogError("Cannot get index_data"); + return -1; + } + my $data = $stmt->fetchrow_hashref(); + if (!defined($data)) { + $self->{'logger'}->writeLogError("Can't find index_data"); + return -1; + } + $self->{"cache_service"}->{$key}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; + return 0; +} + + +# Module meta/bam or normal are specified in tables +sub get_host_service_ids { + my $self = shift; + my ($host_name, $service_description) = @_; + my ($host_id, $service_id); + my ($status, $stmt, $data); + my $host_register = 1; + + # For Modules + if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { + $host_register = 2; + } + # Get Host_Id + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT `host_id` FROM `host` WHERE `host_name` = " . $self->{'dbcentreon'}->quote($host_name) . " AND `host_register` = '$host_register' LIMIT 1"); + return -1 if ($status); + $data = $stmt->fetchrow_hashref(); + if (!defined($data)) { + $self->{'logger'}->writeLogError("Can't find 'host_id' $host_name"); + return -1; + } + + $host_id = $data->{'host_id'}; + # For 'BAM' module: in 'host' and 'service' table but there is no relations + # For 'meta' module: in 'host' and 'meta_service_relation' (we can't purge) + if ($host_register == 2) { + return (0, $host_id, undef); + } + + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM service, host_service_relation hsr WHERE hsr.host_host_id = '" . $host_id . "' AND hsr.service_service_id = service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN ('1', '3') LIMIT 1"); + return -1 if ($status == -1); + $data = $stmt->fetchrow_hashref(); + if (!defined($data)) { + # Search in service By hostgroup + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM hostgroup_relation hgr, service, host_service_relation hsr WHERE hgr.host_host_id = '" . $host_id . "' AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id AND service_id = hsr.service_service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN ('1', '3') LIMIT 1"); + return -1 if ($status == -1); + $data = $stmt->fetchrow_hashref(); + } + + if (!defined($data)) { + $self->{'logger'}->writeLogError("Can't find 'service_id' for $host_name/$service_description"); + return -1; + } + + $service_id = $data->{'service_id'}; + return (0, $host_id, $service_id); +} + +sub get_check_interval_normal { + my $self = shift; + my $service_id = shift; + my $rotation_check = shift; + + if (!defined($service_id)) { + return (0, 5); + } + $rotation_check = {} if (!defined($rotation_check)); + return (0, 5) if (defined($rotation_check->{$service_id})); + + my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_normal_check_interval, service_template_model_stm_id FROM service WHERE service_id = " . $service_id); + return -1 if ($status == -1); + my $data = $stmt->fetchrow_hashref(); + return (0, 5) if (!defined($data)); + + if (!defined($data->{'service_normal_check_interval'}) || $data->{'service_normal_check_interval'} eq '') { + $rotation_check->{$service_id} = 1; + $self->get_check_interval_normal($data->{'service_template_model_stm_id'}, $rotation_check); + } else { + return (0, $data->{'service_normal_check_interval'}); + } +} + +sub get_check_interval_module { + my $self = shift; + my ($host_name, $service_description) = @_; + + my $interval = 1; + $service_description =~ /([a-zA-Z0-9]*)_([0-9]*)/; + if ($1 eq "meta"){ + my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT normal_check_interval FROM meta_service WHERE meta_id = '" . $2 . "' LIMIT 1"); + return -1 if ($status == -1); + my $data = $stmt->fetchrow_hashref(); + if (defined($data->{'normal_check_interval'})){ + $interval = $data->{'normal_check_interval'}; + } + } elsif ($1 eq "ba") { + my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT normal_check_interval FROM mod_bam WHERE ba_id = '" . $2 . "' LIMIT 1"); + return -1 if ($status == -1); + my $data = $stmt->fetchrow_hashref(); + if (defined($data->{'normal_check_interval'})) { + $interval = $data->{'normal_check_interval'}; + } + } + return (0, $interval); +} + +sub get_check_interval { + my $self = shift; + my ($host_name, $service_description, $service_id) = @_; + + if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { + return $self->get_check_interval_module($host_name, $service_description); + } else { + return $self->get_check_interval_normal($service_id); + } +} + +########################### + +sub get_information_service { + my $self = shift; + my ($key_service, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $no_cache) = @_; + + # Need to identify it + my ($status, $host_id, $service_id) = $self->get_host_service_ids($host_name, $service_description); + if ($status != 0) { + if (!defined($no_cache) || $no_cache == 0) { + push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + } + return 1; + } + + # Get Interval + ($status, my $interval) = $self->get_check_interval($host_name, $service_description, $service_id); + if ($status != 0) { + if (!defined($no_cache) || $no_cache == 0) { + push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + } + return 1; + } + + # Create It + $status = $self->create_service($host_id, $service_id, $interval * $self->{"interval_time"}, $host_name, $service_description); + if ($status != 0) { + if ($status == -1 && (!defined($no_cache) || $no_cache == 0)) { + push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + } + if ($status == -2 && (!defined($no_cache) || $no_cache == 0)) { + push @{$self->{"cache_services_rename"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + } + return 1; + } + + return 0; +} + +sub update { + my $self = shift; + my ($play_failed, $timestamp, $host_name, $service_description, $last_service_state, $service_state); + ($play_failed, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}) = @_; + + if ($timestamp !~ /^[0-9]+$/ || $timestamp > (time() + 86400)) { + $self->{'logger'}->writeLogError("Unknown timestamp format or in future: $timestamp"); + return 0; + } + # Not good number field + if (!defined($service_state)) { + $self->{'logger'}->writeLogError("Line not well formed"); + return 0; + } + + my $key_service = $host_name . ";" . $service_description; + # We quit because we have failed to retest before || rebuild + if ((defined($self->{"cache_services_failed"}->{$key_service}) && $play_failed == 0) || + defined($self->{"cache_service"}->{$key_service}) && $self->{"cache_service"}->{$key_service}->{'rebuild'} == 1) { + push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + return 1; + } + # We quit because we wait rename finish + if (defined($self->{"cache_services_rename"}->{$key_service}) && $play_failed == 0) { + push @{$self->{"cache_services_rename"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + return 1; + } + + + if (!defined($self->{"cache_service"}->{$key_service})) { + my $status = $self->get_information_service($key_service, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $play_failed); + return 1 if ($status == 1); + } + + $self->init_perfdata(); + while (($self->get_perfdata())) { + if (!defined($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}})) { + # Need to identify metrics + # if failed, we go 'next' + my $status = $self->create_metric($self->{"cache_service"}->{$key_service}->{'index_id'}, \$self->{"cache_service"}->{$key_service}->{'metrics'}, $self->{"metric_name"}); + next if ($status == -1); + } + + $self->check_update_extra_metric(\$self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}); + + ### + # Check data source type: DB + ### + if ($self->{"cache_service"}->{$key_service}->{'storage_type'} == 2) { + # Do DataBin Add + $self->add_data_mysql($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'metric_id'}, + $timestamp, + $self->{"metric_value"}); + } + + ### + # Do RRDs: metric + ### + $self->{"rrd"}->add_metric($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'metric_id'}, + $self->{"metric_name"}, + $self->{"cache_service"}->{$key_service}->{'check_interval'}, + $self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'data_source_type'}, + $timestamp, + $self->{"metric_value"}, + $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); + } + + ### + # Do RRD Status + ### + if ($self->{"do_rrd_status"} == 1) { + $self->{"rrd"}->add_status($self->{"cache_service"}->{$key_service}->{'index_id'}, + $self->{"cache_service"}->{$key_service}->{'check_interval'}, + $timestamp, + $service_state, + $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); + } + + return 0; +} + +sub rebuild_finish { + my $self = shift; + + $self->{"rebuild_progress"} = 0; + if (defined($self->{"cache_service"}->{$self->{"rebuild_key"}})) { + $self->{"cache_service"}->{$self->{"rebuild_key"}}->{'rebuild'} = 0; + } + my $fh = $self->{'pipe_write'}; + print $fh "REBUILDFINISH\n"; +} + +sub rebuild { + my $self = shift; + my ($host_name, $service_description) = @_; + my $status; + my $current_interval; + + $self->{"rebuild_progress"} = 1; + if (!defined($host_name)) { + # A rebuild is in progress + return 0; + } + + my $key_service = $host_name . ";" . $service_description; + $self->{"rebuild_key"} = $key_service; + + ###### + # To do the rebuild + # Force flush data_bin + $self->flush_mysql(1); + + ###### + # Maybe we have to create cache service and metrics + # We'll get information for rebuild fork + # + if (!defined($self->{"cache_service"}->{$key_service})) { + $status = $self->get_information_service($key_service, undef, $host_name, $service_description, undef, undef, 1); + if ($status == 1) { + $self->{'logger'}->writeLogError("rebuild cannot get information service"); + $self->rebuild_finish(); + return ; + } + } else { + ###### + # Update Interval + # + ($status, $current_interval) = $self->get_check_interval($host_name, $service_description, $self->{"cache_service"}->{$key_service}->{'service_id'}); + if ($status == -1) { + $self->{'logger'}->writeLogError("rebuild cannot get interval service"); + $self->rebuild_finish(); + return ; + } + $self->{"cache_service"}->{$key_service}->{'check_interval'} = $current_interval * $self->{"interval_time"}; + + ##### + # Update cache to get 'rrd_retention' + ($status) = $self->cache_update_service_index_data($key_service); + if ($status == -1) { + $self->rebuild_finish(); + return ; + } + } + $self->{"cache_service"}->{$key_service}->{'rebuild'} = 1; + + ###### + # Get List Metrics and Flush if needed + # + ($status, my $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id, data_source_type FROM metrics WHERE index_id = " . $self->{"cache_service"}->{$key_service}->{'index_id'}); + if ($status == -1) { + $self->{'logger'}->writeLogError("rebuild cannot get metrics list"); + $self->rebuild_finish(); + return ; + } + while ((my $data = $stmt->fetchrow_hashref())) { + $self->{"rrd"}->delete_cache_metric($data->{'metric_id'}); + # Update cache + $self->{"cache_service"}->{$key_service}->{'metrics'}->{'data_source_type'} = $data->{'data_source_type'}; + } + + ###### + # Fork and launch rebuild (we'll rebuild each metric) + # + $self->{"rebuild_index_id"} = $self->{"cache_service"}->{$key_service}->{'index_id'}; + my $rebuild_index_id = $self->{"rebuild_index_id"}; + + $self->{"current_pid"} = fork(); + if (!defined($self->{"current_pid"})) { + $self->{'logger'}->writeLogError("rebuild cannot fork: $!"); + $self->rebuild_finish(); + } elsif (!$self->{"current_pid"}) { + $self->{'dbcentstorage'}->set_inactive_destroy(); + $self->{'dbcentreon'}->set_inactive_destroy(); + + my $centreon_db_centstorage = centreon::db(logger => $self->{'logger'}, db => $self->{'dbcentstorage'}->db(), host => $self->{'dbcentstorage'}->host(), + user => $self->{'dbcentstorage'}->user(), password => $self->{'dbcentstorage'}->password(), "port" => $self->{'dbcentstorage'}->port(), force => 0); + $status = $centreon_db_centstorage->connect(); + exit 1 if ($status == -1); + my $centstorage_rebuild = centstorage::CentstorageRebuild->new($self->{'logger'}); + $status = $centstorage_rebuild->main($centreon_db_centstorage, $rebuild_index_id, $self->{"cache_service"}->{$key_service}->{'check_interval'}, $self->{'rrd'}, $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); + $centreon_db_centstorage->disconnect(); + exit $status; + } + if ($self->{"current_pid"} == -1) { + $self->{"current_pid"} = undef; + } +} + +sub rename_finish { + my $self = shift; + my ($host_name, $service_description) = @_; + + if (defined($self->{"cache_services_rename"}->{$host_name . ";" . $service_description})) { + $self->{'logger'}->writeLogInfo("rename finish received $host_name/$service_description"); + my @tmp_ar = (); + my $lerror = 0; + foreach (@{$self->{"cache_services_rename"}->{$host_name . ";" . $service_description}}) { + if ($lerror == 0 && $self->update(1, @$_) != 0) { + push @tmp_ar, \@$_; + $lerror = 1; + } else { + push @tmp_ar, \@$_; + } + } + if (scalar(@tmp_ar) != 0) { + @{$self->{"cache_services_failed"}->{$host_name . ";" . $service_description}} = @tmp_ar; + } + $self->{'logger'}->writeLogInfo("rename finish $host_name/$service_description ok"); + delete $self->{"cache_services_rename"}->{$host_name . ";" . $service_description}; + } +} + +sub send_rename_finish { + my $self = shift; + my ($host_name, $service_description) = @_; + + $self->{"rename_rebuild_wait"} = 0; + my $fh = $self->{'pipe_write'}; + print $fh "RENAMEFINISH\t$host_name\t$service_description\n"; +} + +sub rename_clean { + my $self = shift; + my ($host_name, $service_description, $new_host_name, $new_service_description) = @_; + my $key = $host_name . ";" . $service_description; + + $self->{'logger'}->writeLogInfo("rename clean received $host_name/$service_description"); + $self->{"rename_old_new"}->{$key} = $new_host_name . ";" . $new_service_description; + if ($self->{"rebuild_progress"} == 1 && $self->{"rebuild_key"} eq $key) { + $self->{"rename_rebuild_wait"} = 1; + $self->{'logger'}->writeLogInfo("Wait rebuild finish..."); + return ; + } + + # Do RRD flush + $self->force_flush_rrd($key); + delete $self->{"cache_service"}->{$key}; + delete $self->{"cache_services_failed"}->{$key}; + delete $self->{"rename_old_new"}->{$key}; + $self->send_rename_finish($new_host_name, $new_service_description); +} + +sub delete_clean { + my $self = shift; + my ($host_name, $service_description, $metric_name) = @_; + my $key = $host_name . ";" . $service_description; + + if (defined($metric_name)) { + $self->{'rrd'}->delete_cache_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$metric_name}->{'metric_id'}); + delete $self->{"cache_service"}->{$key}->{'metrics'}->{$metric_name}; + } else { + foreach (keys %{$self->{"cache_service"}->{$key}->{'metrics'}}) { + $self->{'rrd'}->delete_cache_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$_}->{'metric_id'}); + } + $self->{'rrd'}->delete_cache_status($self->{"cache_service"}->{$key}->{'index_id'}); + delete $self->{"cache_service"}->{$key}; + delete $self->{"cache_services_failed"}->{$key}; + } +} + +sub main { + my $self = shift; + my ($dbcentreon, $dbcentstorage, $pipe_read, $pipe_write, $num_pool, $rrd_cache_mode, $rrd_flush_time, $perfdata_parser_stop) = @_; + my $status; + + $self->{'dbcentreon'} = $dbcentreon; + $self->{'dbcentstorage'} = $dbcentstorage; + $self->{'num_pool'} = $num_pool; + $self->{'perfdata_parser_stop'} = $perfdata_parser_stop if (defined($perfdata_parser_stop)); + + ($status, $self->{"main_perfdata_file"}) = centstorage::CentstorageLib::get_main_perfdata_file($self->{'dbcentreon'}); + ($status, $self->{"len_storage_rrd"}, $self->{"rrd_metrics_path"}, $self->{"rrd_status_path"}, $self->{"storage_type"}) = $self->get_centstorage_information(); + ($status, $self->{"interval_time"}) = $self->get_centreon_intervaltime(); + $self->{"rrd"}->metric_path($self->{"rrd_metrics_path"}); + $self->{"rrd"}->status_path($self->{"rrd_status_path"}); + $self->{"rrd"}->len_rrd($self->{"len_storage_rrd"}); + $self->{"rrd"}->cache_mode($rrd_cache_mode); + $self->{"rrd"}->flush($rrd_flush_time); + + # We have to manage if you don't need infos + $self->{'dbcentreon'}->force(0); + $self->{'dbcentstorage'}->force(0); + + $self->{'pipe_write'} = $pipe_write; + $self->{'read_select'} = new IO::Select(); + $self->{'read_select'}->add($pipe_read); + while (1) { + my @rh_set = $self->{'read_select'}->can_read(10); + if (scalar(@rh_set) == 0) { + $self->flush_mysql(); + $self->{"rrd"}->flush_all(); + $self->flush_failed(); + } + foreach my $rh (@rh_set) { + my $read_done = 0; + while ((my ($status_line, $readline) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + class_handle_TERM() if ($status_line == -1); + last if ($status_line == 0); + my ($method, @fields) = split(/\t/, $readline); + + # Check Type + if (defined($method) && $method eq "UPDATE") { + $self->update(0, @fields); + } elsif (defined($method) && $method eq "REBUILDBEGIN") { + $self->rebuild(@fields); + } elsif (defined($method) && $method eq "REBUILDFINISH") { + $self->{"rebuild_progress"} = 0; + } elsif (defined($method) && $method eq "RENAMEFINISH") { + $self->rename_finish(@fields); + } elsif (defined($method) && $method eq "RENAMECLEAN") { + $self->rename_clean(@fields); + } elsif (defined($method) && $method eq "DELETECLEAN") { + $self->delete_clean(@fields); + } + + $self->flush_mysql(); + $self->{"rrd"}->flush_all(); + } + } + $self->flush_failed(); + } +} + +1; diff --git a/centreon/lib/perl/centstorage/CentstorageRRD.pm b/centreon/lib/perl/centstorage/CentstorageRRD.pm new file mode 100644 index 00000000000..970ffc3a3ff --- /dev/null +++ b/centreon/lib/perl/centstorage/CentstorageRRD.pm @@ -0,0 +1,365 @@ + +use RRDs; +use strict; +use warnings; + +package centstorage::CentstorageRRD; + +my @rrd_dst = ("GAUGE","COUNTER","DERIVE","ABSOLUTE"); + +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"metric_path"} = undef; + $self->{"status_path"} = undef; + $self->{"len_rrd"} = undef; + $self->{"status_info"} = {}; + $self->{"metric_info"} = {}; + # By metric_id + $self->{"rrdcache_metric_data"} = {}; + $self->{"rrdcache_status_data"} = {}; + # Flush every n seconds: -1 = disable + $self->{"last_flush"} = time(); + $self->{"flush"} = -1; + $self->{"cache_mode"} = 0; + bless $self, $class; + return $self; +} + +sub get_ds_name { + my $self = shift; + + $_[0] =~ s/\//slash\_/g; + $_[0] =~ s/\\/bslash\_/g; + $_[0] =~ s/\%/pct\_/g; + $_[0] =~ s/\#S\#/slash\_/g; + $_[0] =~ s/\#BS\#/bslash\_/g; + $_[0] =~ s/\#P\#/pct\_/g; + $_[0] =~ s/[^0-9_\-a-zA-Z]/-/g; + return $_[0]; +} + +sub create_rrd_database { + my $self = shift; + my ($RRDdatabase_path, $metric_id, $begin, $interval, $metric_name, $my_len_storage_rrd, $data_source_type) = @_; + + my $lsource_type; + if (defined($data_source_type) && defined()) { + $lsource_type = $rrd_dst[$data_source_type]; + } else { + $lsource_type = $rrd_dst[0]; + } + RRDs::create($RRDdatabase_path . "/" . $metric_id . ".rrd", "-b ".$begin, "-s ".$interval, "DS:" . substr($metric_name, 0, 19) . ":" . $lsource_type . ":".$interval.":U:U", "RRA:AVERAGE:0.5:1:".$my_len_storage_rrd, "RRA:AVERAGE:0.5:12:".($my_len_storage_rrd / 12)); + my $ERR = RRDs::error; + if ($ERR) { + $self->{'logger'}->writeLogError("ERROR while creating " . $RRDdatabase_path.$metric_id . ".rrd : $ERR"); + } else { + chmod 0664, "${RRDdatabase_path}/${metric_id}.rrd"; + } +} + +sub tune_rrd_database { + my $self = shift; + my ($RRDdatabase_path, $metric_id ,$metric_name, $interval_hb) = @_; + + RRDs::tune($RRDdatabase_path . "/" . $metric_id . ".rrd", "-h", substr($metric_name, 0, 19).":".$interval_hb); + my $ERR = RRDs::error; + if ($ERR) { + $self->{'logger'}->writeLogError("ERROR while tunning operation on " . $RRDdatabase_path.$metric_id . ".rrd : $ERR"); + } +} + +sub get_last_update { + my $self = shift; + my ($rrd_path_database, $id_db) = @_; + my $last_time = -1; + + if (-e $rrd_path_database . '/' . $id_db . '.rrd') { + $last_time = RRDs::last($rrd_path_database . '/' . $id_db . '.rrd'); + my $ERR = RRDs::error; + if ($ERR) { + $self->{'logger'}->writeLogError("ERROR while checking last time '" . $rrd_path_database . "/" . $id_db . ".rrd' $ERR"); + return -2; + } + } + return $last_time; +} + +sub metric_path { + my $self = shift; + + if (@_) { + $self->{'metric_path'} = shift; + } + return $self->{'metric_path'}; +} + +sub status_path { + my $self = shift; + + if (@_) { + $self->{'status_path'} = shift; + } + return $self->{'status_path'}; +} + +sub len_rrd { + my $self = shift; + + if (@_) { + $self->{'len_rrd'} = shift() * 60 * 60 * 24; + } + return $self->{'len_rrd'}; +} + +sub flush { + my $self = shift; + + if (@_) { + $self->{'flush'} = shift; + } + return $self->{'flush'}; +} + +sub cache_mode { + my $self = shift; + + if (@_) { + $self->{'cache_mode'} = shift; + } + return $self->{'cache_mode'}; +} + +sub delete_rrd_metric { + my $self = shift; + my ($id) = @_; + + if (-e $self->{"metric_path"} . "/" . $id . ".rrd") { + if (!unlink($self->{"metric_path"} . "/" . $id . ".rrd")) { + $self->{'logger'}->writeLogError("Cannot delete rrd file " . $self->{"metric_path"} . "/" . $id . ".rrd"); + return -1; + } + } + return 0; +} + +sub delete_cache_metric { + my $self = shift; + my ($metric_id) = @_; + + if (defined($self->{"metric_info"}->{$metric_id})) { + delete $self->{"metric_info"}->{$metric_id}; + } + if (defined($self->{"rrdcache_metric_data"}->{$metric_id})) { + delete $self->{"rrdcache_metric_data"}->{$metric_id}; + } +} + +sub delete_cache_status { + my $self = shift; + my ($id) = @_; + + if (defined($self->{"status_info"}->{$id})) { + delete $self->{"status_info"}->{$id}; + } + if (defined($self->{"rrdcache_status_data"}->{$id})) { + delete $self->{"rrdcache_status_data"}->{$id}; + } +} + +sub add_metric { + my $self = shift; + my ($metric_id, $metric_name, $interval, $data_source_type, $timestamp, $value, $local_rrd_retention) = @_; + + if (!defined($self->{"metric_info"}->{$metric_id})) { + my $my_len_storage_rrd; + if ($local_rrd_retention == -1) { + $my_len_storage_rrd = $self->{"len_rrd"} / $interval; + } else { + $my_len_storage_rrd = $local_rrd_retention / $interval; + } + my $ltimestamp = $self->get_last_update($self->{"metric_path"}, $metric_id); + return if ($ltimestamp == -2); + $self->{"metric_info"}->{$metric_id} = {'metric_name' => $metric_name, + 'interval' => $interval, + 'data_source_type' => $data_source_type, + 'last_timestamp' => $ltimestamp, + 'len_rrd' => $my_len_storage_rrd}; + if ($self->{"metric_info"}->{$metric_id}->{'last_timestamp'} == -1) { + my $interval_hb = $interval * 10; + + $self->create_rrd_database($self->{"metric_path"}, $metric_id, $timestamp - 200, $interval, + $self->get_ds_name($metric_name), $my_len_storage_rrd, $data_source_type); + $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($metric_name), $interval_hb); + $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} = $timestamp - 200; + } + } + + return -1 if ($timestamp <= $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} || $timestamp > (time() + 7200)); + $self->{"rrdcache_metric_data"}->{$metric_id} = [] if (!defined($self->{"rrdcache_metric_data"}->{$metric_id})); + push @{$self->{"rrdcache_metric_data"}->{$metric_id}}, $timestamp . ":" . $value; + $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} = $timestamp; +} + +sub add_status { + my $self = shift; + my ($index_id, $interval, $timestamp, $service_state, $local_rrd_retention) = @_; + my $value; + + if ($service_state eq 'OK') { + $value = 100; + } elsif ($service_state eq 'WARNING') { + $value = 75; + } elsif ($service_state eq 'CRITICAL') { + $value = 0; + } else { + # Don't do for 'UNKNOWN' + return ; + } + if (!defined($self->{'status_info'}->{$index_id})) { + my $my_len_storage_rrd; + if ($local_rrd_retention == -1) { + $my_len_storage_rrd = $self->{"len_rrd"} / $interval; + } else { + $my_len_storage_rrd = $local_rrd_retention / $interval; + } + my $ltimestamp = $self->get_last_update($self->{"status_path"}, $index_id); + return if ($ltimestamp == -2); + $self->{"status_info"}->{$index_id} = {'interval' => $interval, + 'last_timestamp' => $ltimestamp, + 'values' => [], + 'len_rrd' => $my_len_storage_rrd}; + if ($self->{"status_info"}->{$index_id}->{'last_timestamp'} == -1) { + my $interval_hb = $interval * 10; + + $self->create_rrd_database($self->{"status_path"}, $index_id, $timestamp - 200, $interval, + "status", $my_len_storage_rrd, 0); + $self->tune_rrd_database($self->{"status_path"}, $index_id, "status", $interval_hb); + $self->{"status_info"}->{$index_id}->{'last_timestamp'} = $timestamp - 200; + } + } + + return -1 if ($timestamp <= $self->{"status_info"}->{$index_id}->{'last_timestamp'} || $timestamp > (time() + 7200)); + $self->{"rrdcache_status_data"}->{$index_id} = [] if (!defined($self->{"rrdcache_status_data"}->{$index_id})); + push @{$self->{"rrdcache_status_data"}->{$index_id}}, $timestamp . ":" . $value; + $self->{"status_info"}->{$index_id}->{'last_timestamp'} = $timestamp; +} + +sub flush_metric { + my $self = shift; + my ($metric_id) = @_; + + if (defined($self->{"rrdcache_metric_data"}->{$metric_id})) { + RRDs::update($self->{"metric_path"} . "/" . $metric_id . ".rrd", @{$self->{"rrdcache_metric_data"}->{$metric_id}}); + my $ERR = RRDs::error; + if ($ERR) { + # Try to see if the file had been deleted + if (! -e $self->{"metric_path"} . "/" . $metric_id . ".rrd") { + my $my_len_storage_rrd = $self->{"metric_info"}->{$metric_id}->{'len_rrd'}; + my $interval_hb = $self->{"metric_info"}->{$metric_id}->{'interval'} * 10; + + $self->create_rrd_database($self->{"metric_path"}, $metric_id, + $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} - 200, + $self->{"metric_info"}->{$metric_id}->{'interval'}, + $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $my_len_storage_rrd, + $self->{"metric_info"}->{$metric_id}->{'data_source_type'}); + $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $interval_hb); + } else { + $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"metric_path"} . "/" . $metric_id . ".rrd' $ERR"); + } + } + delete $self->{"rrdcache_metric_data"}->{$metric_id}; + } +} + +sub flush_status { + my $self = shift; + my ($index_id) = @_; + + if (defined($self->{"rrdcache_status_data"}->{$index_id})) { + RRDs::update($self->{"status_path"} . "/" . $index_id . ".rrd", @{$self->{"rrdcache_status_data"}->{$index_id}}); + my $ERR = RRDs::error; + if ($ERR) { + # Try to see if the file had been deleted + if (! -e $self->{"status_path"} . "/" . $index_id . ".rrd") { + my $my_len_storage_rrd = $self->{"status_info"}->{$index_id}->{'len_rrd'}; + my $interval_hb = $self->{"status_info"}->{$index_id}->{'interval'} * 10; + + $self->create_rrd_database($self->{"status_path"}, $index_id, + $self->{"status_info"}->{$index_id}->{'last_timestamp'} - 200, + $self->{"status_info"}->{$index_id}->{'interval'}, + "status", $my_len_storage_rrd, + 0); + $self->tune_rrd_database($self->{"status_path"}, $index_id, "status", $interval_hb); + } else { + $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"status_path"} . "/" . $index_id . ".rrd' $ERR"); + } + } + delete $self->{"rrdcache_status_data"}->{$index_id}; + } +} + +sub flush_all { + my $self = shift; + my ($force) = @_; + + if ($self->{'cache_mode'} == 1 && (!defined($force) || $force == 0)) { + return if (time() < ($self->{'last_flush'} + $self->{'flush'})); + $self->{'last_flush'} = time(); + $self->{'logger'}->writeLogInfo("Flush Beginning"); + } + ### + # Metrics + ### + foreach my $metric_id (keys %{$self->{"rrdcache_metric_data"}}) { + RRDs::update($self->{"metric_path"} . "/" . $metric_id . ".rrd", @{$self->{"rrdcache_metric_data"}->{$metric_id}}); + my $ERR = RRDs::error; + if ($ERR) { + # Try to see if the file had been deleted + if (! -e $self->{"metric_path"} . "/" . $metric_id . ".rrd") { + my $my_len_storage_rrd = $self->{"metric_info"}->{$metric_id}->{'len_rrd'}; + my $interval_hb = $self->{"metric_info"}->{$metric_id}->{'interval'} * 10; + + $self->create_rrd_database($self->{"metric_path"}, $metric_id, + $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} - 200, + $self->{"metric_info"}->{$metric_id}->{'interval'}, + $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $my_len_storage_rrd, + $self->{"metric_info"}->{$metric_id}->{'data_source_type'}); + $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $interval_hb); + } else { + $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"metric_path"} . "/" . $metric_id . ".rrd' $ERR"); + } + } + } + $self->{"rrdcache_metric_data"} = {}; + + ### + # Status + ### + foreach my $service_id (keys %{$self->{"rrdcache_status_data"}}) { + RRDs::update($self->{"status_path"} . "/" . $service_id . ".rrd", @{$self->{"rrdcache_status_data"}->{$service_id}}); + my $ERR = RRDs::error; + if ($ERR) { + # Try to see if the file had been deleted + if (! -e $self->{"status_path"} . "/" . $service_id . ".rrd") { + my $my_len_storage_rrd = $self->{"status_info"}->{$service_id}->{'len_rrd'}; + my $interval_hb = $self->{"status_info"}->{$service_id}->{'interval'} * 10; + + $self->create_rrd_database($self->{"status_path"}, $service_id, + $self->{"status_info"}->{$service_id}->{'last_timestamp'} - 200, + $self->{"status_info"}->{$service_id}->{'interval'}, + "status", $my_len_storage_rrd, + 0); + $self->tune_rrd_database($self->{"status_path"}, $service_id, "status", $interval_hb); + } else { + $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"status_path"} . "/" . $service_id . ".rrd' $ERR"); + } + } + } + $self->{"rrdcache_status_data"} = {}; + + $self->{'logger'}->writeLogInfo("Flush Ending") if ($self->{'cache_mode'} == 1); +} + +1; diff --git a/centreon/lib/perl/centstorage/CentstorageRebuild.pm b/centreon/lib/perl/centstorage/CentstorageRebuild.pm new file mode 100644 index 00000000000..693be0fb9ac --- /dev/null +++ b/centreon/lib/perl/centstorage/CentstorageRebuild.pm @@ -0,0 +1,99 @@ + +use strict; +use warnings; + +package centstorage::CentstorageRebuild; +my %handlers = ('TERM' => {}); + +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"dbcentstorage"} = undef; + + bless $self, $class; + $self->set_signal_handlers; + return $self; +} + +sub set_signal_handlers { + my $self = shift; + + $SIG{TERM} = \&class_handle_TERM; + $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; +} + +sub handle_TERM { + my $self = shift; + $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); + + eval { + local $SIG{ALRM} = sub { die "alarm\n" }; + alarm 10; + $self->{'dbcentstorage'}->kill(); + alarm 0; + }; + if ($@) { + $self->{'logger'}->writeLogError("Can't kill rebuild request"); + } + $self->{"dbcentstorage"}->disconnect() if (defined($self->{"dbcentstorage"})); +} + +sub class_handle_TERM { + foreach (keys %{$handlers{'TERM'}}) { + &{$handlers{'TERM'}->{$_}}(); + } + exit(0); +} + +sub main { + my $self = shift; + my ($dbcentstorage, $index_id, $interval, $rrd, $local_rrd) = @_; + my $status; + my $stmt; + + $self->{'dbcentstorage'} = $dbcentstorage; + ### Update for UI + ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE index_data SET `must_be_rebuild` = '2' WHERE id = " . $index_id); + if ($status == -1) { + $self->{'logger'}->writeLogError("rebuild cannot update index_id $index_id"); + return 1; + } + + ### + # Get By Metric_id + ### + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id, metric_name, data_source_type FROM metrics WHERE index_id = " . $index_id); + if ($status == -1) { + $self->{'logger'}->writeLogError("rebuild cannot get metrics list"); + return 1; + } + while ((my $data = $stmt->fetchrow_hashref())) { + ($status, my $stmt2) = $self->{'dbcentstorage'}->query("SELECT ctime, value FROM data_bin WHERE id_metric = " . $data->{'metric_id'} . " ORDER BY ctime ASC"); + if ($status == -1) { + $self->{'logger'}->writeLogError("rebuild cannot get metric_id datas " . $data->{'metric_id'}); + return 1; + } + + ### Delete RRD + $status = $rrd->delete_rrd_metric($data->{'metric_id'}); + + my $rows = []; + while (my $data2 = (shift(@$rows) || + shift(@{$rows = $stmt2->fetchall_arrayref(undef,10_000)||[]}) ) ) { + $rrd->add_metric($data->{'metric_id'}, $data->{'metric_name'}, $interval, $data->{'data_source_type'}, $$data2[0], $$data2[1], $local_rrd); + } + $rrd->flush_metric($data->{'metric_id'}); + } + + ### Update for UI + ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE index_data SET `must_be_rebuild` = '0' WHERE id = " . $index_id); + if ($status == -1) { + $self->{'logger'}->writeLogError("rebuild cannot update index_id $index_id"); + return 1; + } + + return 0; +} + +1; From a00708585c6af4310598cee6b591c6812527f0f0 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 20 Mar 2013 14:02:05 +0100 Subject: [PATCH 004/458] Fix indentation --- .../lib/perl/centstorage/CentstorageAction.pm | 464 ++--- .../lib/perl/centstorage/CentstorageLib.pm | 310 ++-- .../centstorage/CentstoragePerfdataFile.pm | 198 +-- .../lib/perl/centstorage/CentstoragePool.pm | 1584 ++++++++--------- .../lib/perl/centstorage/CentstorageRRD.pm | 590 +++--- .../perl/centstorage/CentstorageRebuild.pm | 144 +- 6 files changed, 1645 insertions(+), 1645 deletions(-) diff --git a/centreon/lib/perl/centstorage/CentstorageAction.pm b/centreon/lib/perl/centstorage/CentstorageAction.pm index ec237f4cb93..f75e8e33ac9 100644 --- a/centreon/lib/perl/centstorage/CentstorageAction.pm +++ b/centreon/lib/perl/centstorage/CentstorageAction.pm @@ -8,280 +8,280 @@ use centstorage::CentstorageLib; my %handlers = ('TERM' => {}); sub new { - my $class = shift; - my $self = {}; - $self->{"logger"} = shift; - $self->{"rebuild_progress"} = shift; - $self->{"centreon_23_compatibility"} = shift; - $self->{"dbcentreon"} = undef; - $self->{"dbcentstorage"} = undef; - $self->{"purge_delay"} = 3600; - $self->{"last_purge_time"} = time() - $self->{"purge_delay"} - 5; + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"rebuild_progress"} = shift; + $self->{"centreon_23_compatibility"} = shift; + $self->{"dbcentreon"} = undef; + $self->{"dbcentstorage"} = undef; + $self->{"purge_delay"} = 3600; + $self->{"last_purge_time"} = time() - $self->{"purge_delay"} - 5; - $self->{"deleted_delay"} = 120; - $self->{"last_deleted_time"} = time() - $self->{"deleted_delay"} - 5; + $self->{"deleted_delay"} = 120; + $self->{"last_deleted_time"} = time() - $self->{"deleted_delay"} - 5; - $self->{"rrd_metrics_path"} = undef; - $self->{"rrd_status_path"} = undef; + $self->{"rrd_metrics_path"} = undef; + $self->{"rrd_status_path"} = undef; - $self->{"save_read"} = []; + $self->{"save_read"} = []; - bless $self, $class; - $self->set_signal_handlers; - return $self; + bless $self, $class; + $self->set_signal_handlers; + return $self; } sub set_signal_handlers { - my $self = shift; + my $self = shift; - $SIG{TERM} = \&class_handle_TERM; - $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; + $SIG{TERM} = \&class_handle_TERM; + $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; } sub handle_TERM { - my $self = shift; - $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); + my $self = shift; + $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); - $self->{'dbcentreon'}->disconnect() if (defined($self->{'dbcentreon'})); - $self->{'dbcentstorage'}->disconnect() if (defined($self->{'dbcentstorage'})); + $self->{'dbcentreon'}->disconnect() if (defined($self->{'dbcentreon'})); + $self->{'dbcentstorage'}->disconnect() if (defined($self->{'dbcentstorage'})); } sub class_handle_TERM { - foreach (keys %{$handlers{'TERM'}}) { - &{$handlers{'TERM'}->{$_}}(); - } - exit(0); + foreach (keys %{$handlers{'TERM'}}) { + &{$handlers{'TERM'}->{$_}}(); + } + exit(0); } sub check_deleted { - my $self = shift; - my $pipe_write = $_[0]; - - if (defined($self->{'centreon_23_compatibility'}) && $self->{'centreon_23_compatibility'} == 1) { - return ; - } - - if (time() < ($self->{"last_deleted_time"} + $self->{"deleted_delay"})) { - return ; - } - - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `host_name`, `service_description`, `metrics`.metric_id FROM `index_data` LEFT JOIN `metrics` ON (index_data.id = metrics.index_id) WHERE index_data.to_delete = '1' ORDER BY id"); - return -1 if ($status == -1); - my $current_index_id = -1; - while ((my $data = $stmt->fetchrow_hashref())) { - if ($current_index_id != $data->{'id'}) { - if ($self->delete_rrd_file($self->{"rrd_status_path"}, $data->{'id'}) == 0) { - $self->{'dbcentstorage'}->query("DELETE FROM index_data WHERE id = " . $data->{'id'}); - } - $current_index_id = $data->{'id'}; - print $pipe_write "DELETECLEAN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\n"; - } - if (defined($data->{'metric_id'})) { - if ($self->delete_rrd_file($self->{"rrd_metrics_path"}, $data->{'metric_id'}) == 0) { - $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data->{'metric_id'}); - } - } - } - - ### - # Check metrics alone - ### - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `host_name`, `service_description`, `metrics`.metric_id, `metrics`.metric_name FROM `metrics` LEFT JOIN `index_data` ON (index_data.id = metrics.index_id) WHERE metrics.to_delete = '1'"); - return -1 if ($status == -1); - while ((my $data = $stmt->fetchrow_hashref())) { - if (defined($data->{'host_name'})) { - print $pipe_write "DELETECLEAN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\t" . $data->{'metric_name'} . "\n"; - } - if ($self->delete_rrd_file($self->{"rrd_metrics_path"}, $data->{'metric_id'}) == 0) { - $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data->{'metric_id'}); - } - } - - $self->{"last_deleted_time"} = time(); + my $self = shift; + my $pipe_write = $_[0]; + + if (defined($self->{'centreon_23_compatibility'}) && $self->{'centreon_23_compatibility'} == 1) { + return ; + } + + if (time() < ($self->{"last_deleted_time"} + $self->{"deleted_delay"})) { + return ; + } + + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `host_name`, `service_description`, `metrics`.metric_id FROM `index_data` LEFT JOIN `metrics` ON (index_data.id = metrics.index_id) WHERE index_data.to_delete = '1' ORDER BY id"); + return -1 if ($status == -1); + my $current_index_id = -1; + while ((my $data = $stmt->fetchrow_hashref())) { + if ($current_index_id != $data->{'id'}) { + if ($self->delete_rrd_file($self->{"rrd_status_path"}, $data->{'id'}) == 0) { + $self->{'dbcentstorage'}->query("DELETE FROM index_data WHERE id = " . $data->{'id'}); + } + $current_index_id = $data->{'id'}; + print $pipe_write "DELETECLEAN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\n"; + } + if (defined($data->{'metric_id'})) { + if ($self->delete_rrd_file($self->{"rrd_metrics_path"}, $data->{'metric_id'}) == 0) { + $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data->{'metric_id'}); + } + } + } + + ### + # Check metrics alone + ### + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `host_name`, `service_description`, `metrics`.metric_id, `metrics`.metric_name FROM `metrics` LEFT JOIN `index_data` ON (index_data.id = metrics.index_id) WHERE metrics.to_delete = '1'"); + return -1 if ($status == -1); + while ((my $data = $stmt->fetchrow_hashref())) { + if (defined($data->{'host_name'})) { + print $pipe_write "DELETECLEAN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\t" . $data->{'metric_name'} . "\n"; + } + if ($self->delete_rrd_file($self->{"rrd_metrics_path"}, $data->{'metric_id'}) == 0) { + $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data->{'metric_id'}); + } + } + + $self->{"last_deleted_time"} = time(); } sub check_rebuild { - my $self = shift; - my $pipe_write = $_[0]; + my $self = shift; + my $pipe_write = $_[0]; - return if ($self->{"rebuild_progress"} == 1); - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `host_name`, `service_description` FROM `index_data` WHERE `must_be_rebuild` IN ('1', '2') LIMIT 1"); + return if ($self->{"rebuild_progress"} == 1); + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `host_name`, `service_description` FROM `index_data` WHERE `must_be_rebuild` IN ('1', '2') LIMIT 1"); return -1 if ($status == -1); my $data = $stmt->fetchrow_hashref(); - if (defined($data)) { - $self->{"rebuild_progress"} = 1; - $self->{"logger"}->writeLogInfo("Rebuild detected: " . $data->{'host_name'} . "/" . $data->{'service_description'}); - print $pipe_write "REBUILDBEGIN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\n"; - } + if (defined($data)) { + $self->{"rebuild_progress"} = 1; + $self->{"logger"}->writeLogInfo("Rebuild detected: " . $data->{'host_name'} . "/" . $data->{'service_description'}); + print $pipe_write "REBUILDBEGIN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\n"; + } } sub delete_rrd_file { - my $self = shift; - my ($path, $id) = @_; - - - if (-e $path . "/" . $id . ".rrd") { - if (unlink($path . "/" . $id . ".rrd")) { - $self->{'logger'}->writeLogInfo("Delete RRD file " . $path . "/" . $id . ".rrd"); - } else { - $self->{'logger'}->writeLogError("Cannot delete RRD file " . $path . "/" . $id . ".rrd: " . $!); - return 1; - } - } - return 0; + my $self = shift; + my ($path, $id) = @_; + + + if (-e $path . "/" . $id . ".rrd") { + if (unlink($path . "/" . $id . ".rrd")) { + $self->{'logger'}->writeLogInfo("Delete RRD file " . $path . "/" . $id . ".rrd"); + } else { + $self->{'logger'}->writeLogError("Cannot delete RRD file " . $path . "/" . $id . ".rrd: " . $!); + return 1; + } + } + return 0; } sub purge_mysql_and_rrd { - my $self = shift; - my ($status, $stmt, $rows, $data); - my %cache_index_data = (); - my %cache_services = (); - - # Get By direct - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT host_host_id, service_service_id FROM host_service_relation WHERE hostgroup_hg_id IS NULL"); - return -1 if ($status == -1); - $rows = []; - while ($data = (shift(@$rows) || - shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { - $cache_services{$$data[0] . ";" . $$data[1]} = 1; - } - - # Get By Hostgroup - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT host.host_id, host_service_relation.service_service_id FROM host, host_service_relation, hostgroup_relation WHERE host.host_id = hostgroup_relation.host_host_id AND hostgroup_relation.hostgroup_hg_id = host_service_relation.hostgroup_hg_id"); - return -1 if ($status == -1); - $rows = []; - while ($data = (shift(@$rows) || - shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { - $cache_services{$$data[0] . ";" . $$data[1]} = 1; - } - - #### - # Cache Dir - #### - my @files = (); - if (opendir(DIR, $self->{"rrd_status_path"})) { - @files = grep { $_ ne '.' and $_ ne '..' } readdir DIR; - } else { - $self->{'logger'}->writeLogError("Can't opendir " . $self->{"rrd_status_path"} . ": $!"); - } - - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT host_id, service_id, id FROM index_data"); - return -1 if ($status); - $rows = []; - while ($data = (shift(@$rows) || - shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { - $cache_index_data{$$data[2]} = 1; - if (defined($$data[0]) && defined($$data[1]) && !defined($cache_services{$$data[0] . ";" . $$data[1]})) { - ($status, my $stmt2) = $self->{'dbcentstorage'}->query("SELECT metric_id FROM metrics WHERE index_id = '" . $$data[2] . "'"); - next if ($status == -1); - while ((my $data2 = $stmt2->fetchrow_hashref())) { - $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data2->{'metric_id'}); - $self->delete_rrd_file($self->{"rrd_metrics_path"}, $data2->{'metric_id'}); - } - $self->{'dbcentstorage'}->query("DELETE FROM index_data WHERE id = '" . $$data[2] . "'"); - $self->{'logger'}->writeLogInfo("Delete MySQL metrics " . $$data[0] . "/" . $$data[1]); - $self->delete_rrd_file($self->{"rrd_status_path"}, $$data[2]); - } - } - - ### - # Purge RRD Status - ### - foreach (@files) { - if ($_ =~ /(.*)\.rrd$/ && !defined($cache_index_data{$1})) { - $self->delete_rrd_file($self->{"rrd_status_path"}, $1); - } - } - - ### - # Purge RRD Metrics - ### - @files = (); - if (opendir(DIR, $self->{"rrd_metrics_path"})) { - @files = grep { $_ ne '.' and $_ ne '..' } readdir DIR; - } else { - $self->{'logger'}->writeLogError("Can't opendir " . $self->{"rrd_metrics_path"} . ": $!"); - } - - my %cache_metrics_data = (); - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id FROM metrics"); - return -1 if ($status == -1); - $rows = []; - while ($data = (shift(@$rows) || - shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { - $cache_metrics_data{$$data[0]} = 1; - } - - foreach (@files) { - if ($_ =~ /(.*)\.rrd$/ && !defined($cache_metrics_data{$1})) { - $self->delete_rrd_file($self->{"rrd_metrics_path"}, $1); - } - } + my $self = shift; + my ($status, $stmt, $rows, $data); + my %cache_index_data = (); + my %cache_services = (); + + # Get By direct + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT host_host_id, service_service_id FROM host_service_relation WHERE hostgroup_hg_id IS NULL"); + return -1 if ($status == -1); + $rows = []; + while ($data = (shift(@$rows) || + shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { + $cache_services{$$data[0] . ";" . $$data[1]} = 1; + } + + # Get By Hostgroup + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT host.host_id, host_service_relation.service_service_id FROM host, host_service_relation, hostgroup_relation WHERE host.host_id = hostgroup_relation.host_host_id AND hostgroup_relation.hostgroup_hg_id = host_service_relation.hostgroup_hg_id"); + return -1 if ($status == -1); + $rows = []; + while ($data = (shift(@$rows) || + shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { + $cache_services{$$data[0] . ";" . $$data[1]} = 1; + } + + #### + # Cache Dir + #### + my @files = (); + if (opendir(DIR, $self->{"rrd_status_path"})) { + @files = grep { $_ ne '.' and $_ ne '..' } readdir DIR; + } else { + $self->{'logger'}->writeLogError("Can't opendir " . $self->{"rrd_status_path"} . ": $!"); + } + + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT host_id, service_id, id FROM index_data"); + return -1 if ($status); + $rows = []; + while ($data = (shift(@$rows) || + shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { + $cache_index_data{$$data[2]} = 1; + if (defined($$data[0]) && defined($$data[1]) && !defined($cache_services{$$data[0] . ";" . $$data[1]})) { + ($status, my $stmt2) = $self->{'dbcentstorage'}->query("SELECT metric_id FROM metrics WHERE index_id = '" . $$data[2] . "'"); + next if ($status == -1); + while ((my $data2 = $stmt2->fetchrow_hashref())) { + $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data2->{'metric_id'}); + $self->delete_rrd_file($self->{"rrd_metrics_path"}, $data2->{'metric_id'}); + } + $self->{'dbcentstorage'}->query("DELETE FROM index_data WHERE id = '" . $$data[2] . "'"); + $self->{'logger'}->writeLogInfo("Delete MySQL metrics " . $$data[0] . "/" . $$data[1]); + $self->delete_rrd_file($self->{"rrd_status_path"}, $$data[2]); + } + } + + ### + # Purge RRD Status + ### + foreach (@files) { + if ($_ =~ /(.*)\.rrd$/ && !defined($cache_index_data{$1})) { + $self->delete_rrd_file($self->{"rrd_status_path"}, $1); + } + } + + ### + # Purge RRD Metrics + ### + @files = (); + if (opendir(DIR, $self->{"rrd_metrics_path"})) { + @files = grep { $_ ne '.' and $_ ne '..' } readdir DIR; + } else { + $self->{'logger'}->writeLogError("Can't opendir " . $self->{"rrd_metrics_path"} . ": $!"); + } + + my %cache_metrics_data = (); + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id FROM metrics"); + return -1 if ($status == -1); + $rows = []; + while ($data = (shift(@$rows) || + shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { + $cache_metrics_data{$$data[0]} = 1; + } + + foreach (@files) { + if ($_ =~ /(.*)\.rrd$/ && !defined($cache_metrics_data{$1})) { + $self->delete_rrd_file($self->{"rrd_metrics_path"}, $1); + } + } } sub get_centstorage_information { - my $self = shift; - my ($rrd_metrics_path, $rrd_status_path); - - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT RRDdatabase_path, RRDdatabase_status_path FROM config"); - my $data = $stmt->fetchrow_hashref(); - if (defined($data)) { - $rrd_metrics_path = $data->{'RRDdatabase_path'}; - $rrd_status_path = $data->{'RRDdatabase_status_path'}; - } - return ($status, $rrd_metrics_path, $rrd_status_path); + my $self = shift; + my ($rrd_metrics_path, $rrd_status_path); + + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT RRDdatabase_path, RRDdatabase_status_path FROM config"); + my $data = $stmt->fetchrow_hashref(); + if (defined($data)) { + $rrd_metrics_path = $data->{'RRDdatabase_path'}; + $rrd_status_path = $data->{'RRDdatabase_status_path'}; + } + return ($status, $rrd_metrics_path, $rrd_status_path); } sub check_purge { - my $self = shift; + my $self = shift; - if (time() < ($self->{"last_purge_time"} + $self->{"purge_delay"})) { - return ; - } + if (time() < ($self->{"last_purge_time"} + $self->{"purge_delay"})) { + return ; + } - $self->purge_mysql_and_rrd(); - $self->{"last_purge_time"} = time(); + $self->purge_mysql_and_rrd(); + $self->{"last_purge_time"} = time(); } sub main { - my $self = shift; - my ($dbcentreon, $dbcentstorage, $pipe_read, $pipe_write) = @_; - my $status; - - $self->{'dbcentreon'} = $dbcentreon; - $self->{'dbcentstorage'} = $dbcentstorage; - - ($status, $self->{"rrd_metrics_path"}, $self->{"rrd_status_path"}) = $self->get_centstorage_information(); - - # We have to manage if you don't need infos - $self->{'dbcentreon'}->force(0); - $self->{'dbcentstorage'}->force(0); - - my $read_select = new IO::Select(); - $read_select->add($pipe_read); - while (1) { - my @rh_set = $read_select->can_read(5); - if (scalar(@rh_set) > 0) { - foreach my $rh (@rh_set) { - my $read_done = 0; - while ((my ($status_line, $readline) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { - class_handle_TERM() if ($status_line == -1); - last if ($status_line == 0); - my ($method, @fields) = split(/\t/, $readline); - - # Check Type - if (defined($method) && $method eq "REBUILDFINISH") { - $self->{"rebuild_progress"} = 0; - } - } - } - } else { - $self->check_rebuild($pipe_write); - $self->check_deleted($pipe_write); - $self->check_purge(); - } - } + my $self = shift; + my ($dbcentreon, $dbcentstorage, $pipe_read, $pipe_write) = @_; + my $status; + + $self->{'dbcentreon'} = $dbcentreon; + $self->{'dbcentstorage'} = $dbcentstorage; + + ($status, $self->{"rrd_metrics_path"}, $self->{"rrd_status_path"}) = $self->get_centstorage_information(); + + # We have to manage if you don't need infos + $self->{'dbcentreon'}->force(0); + $self->{'dbcentstorage'}->force(0); + + my $read_select = new IO::Select(); + $read_select->add($pipe_read); + while (1) { + my @rh_set = $read_select->can_read(5); + if (scalar(@rh_set) > 0) { + foreach my $rh (@rh_set) { + my $read_done = 0; + while ((my ($status_line, $readline) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + class_handle_TERM() if ($status_line == -1); + last if ($status_line == 0); + my ($method, @fields) = split(/\t/, $readline); + + # Check Type + if (defined($method) && $method eq "REBUILDFINISH") { + $self->{"rebuild_progress"} = 0; + } + } + } + } else { + $self->check_rebuild($pipe_write); + $self->check_deleted($pipe_write); + $self->check_purge(); + } + } } 1; diff --git a/centreon/lib/perl/centstorage/CentstorageLib.pm b/centreon/lib/perl/centstorage/CentstorageLib.pm index 3c5e012e4b4..207d6574909 100644 --- a/centreon/lib/perl/centstorage/CentstorageLib.pm +++ b/centreon/lib/perl/centstorage/CentstorageLib.pm @@ -5,191 +5,191 @@ use File::Basename; my $read_size = 1*1024*1024*10; # 10Mo sub start_or_not { - my ($centreon_db_centreon) = @_; - my $status = 1; - - my ($status2, $stmt) = $centreon_db_centreon->query("SELECT value FROM options WHERE `key` = 'centstorage' LIMIT 1"); - my $data = $stmt->fetchrow_hashref(); - if (defined($data) && int($data->{'value'}) == 0) { - $status = 0; - } - return $status; + my ($centreon_db_centreon) = @_; + my $status = 1; + + my ($status2, $stmt) = $centreon_db_centreon->query("SELECT value FROM options WHERE `key` = 'centstorage' LIMIT 1"); + my $data = $stmt->fetchrow_hashref(); + if (defined($data) && int($data->{'value'}) == 0) { + $status = 0; + } + return $status; } sub get_main_perfdata_file { - my ($centreon_db_centreon) = @_; - my $filename; - - my ($status, $stmt) = $centreon_db_centreon->query("SELECT `nagios_perfdata` FROM `nagios_server` WHERE `localhost` = '1'"); - my $data = $stmt->fetchrow_hashref(); - if (defined($data)) { - $filename = $data->{'nagios_perfdata'}; - } - return ($status, $filename); + my ($centreon_db_centreon) = @_; + my $filename; + + my ($status, $stmt) = $centreon_db_centreon->query("SELECT `nagios_perfdata` FROM `nagios_server` WHERE `localhost` = '1'"); + my $data = $stmt->fetchrow_hashref(); + if (defined($data)) { + $filename = $data->{'nagios_perfdata'}; + } + return ($status, $filename); } sub check_pool_old_perfdata_file { - my ($main_filename, $num_pool) = @_; - - my @files = (); - for (my $i = 0; $i < $num_pool; $i++) { - if (-e $main_filename . "_" . $i . ".bckp_read") { - push @files, $main_filename . "_" . $i . ".bckp_read"; - } - if (-e $main_filename . "_" . $i . ".bckp") { - push @files, $main_filename . "_" . $i . ".bckp"; - } - } - - if (-e $main_filename . "_read") { - push @files, $main_filename . "_read"; - } - return \@files; + my ($main_filename, $num_pool) = @_; + + my @files = (); + for (my $i = 0; $i < $num_pool; $i++) { + if (-e $main_filename . "_" . $i . ".bckp_read") { + push @files, $main_filename . "_" . $i . ".bckp_read"; + } + if (-e $main_filename . "_" . $i . ".bckp") { + push @files, $main_filename . "_" . $i . ".bckp"; + } + } + + if (-e $main_filename . "_read") { + push @files, $main_filename . "_read"; + } + return \@files; } sub call_pool_rebuild { - my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs, $rebuild_progress, $rebuild_pool_choosen) = @_; - - # Send Info - my ($method, $host_name, $service_description) = split(/\t/, $line); - my $pool_choosen; - if (!defined($routing_services->{$host_name . ";" . $service_description})) { - my $pool_num = $$roundrobin_pool_current % $pool_childs; - $$roundrobin_pool_current++; - $routing_services->{$host_name . ";" . $service_description} = $pool_num; - } - $pool_choosen = $routing_services->{$host_name . ";" . $service_description}; - for ($i = 0; $i < $pool_childs; $i++) { - if ($i == $pool_choosen) { - my $fh = $pool_pipes->{$i}->{'writer_two'}; - # It's when you loose a pool. You have to know - $$rebuild_progress = 1; - $$rebuild_pool_choosen = $pool_choosen; - print $fh "REBUILDBEGIN\t$host_name\t$service_description\n"; - } else { - my $fh = $pool_pipes->{$i}->{'writer_two'}; - print $fh "REBUILDBEGIN\n"; - } - } + my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs, $rebuild_progress, $rebuild_pool_choosen) = @_; + + # Send Info + my ($method, $host_name, $service_description) = split(/\t/, $line); + my $pool_choosen; + if (!defined($routing_services->{$host_name . ";" . $service_description})) { + my $pool_num = $$roundrobin_pool_current % $pool_childs; + $$roundrobin_pool_current++; + $routing_services->{$host_name . ";" . $service_description} = $pool_num; + } + $pool_choosen = $routing_services->{$host_name . ";" . $service_description}; + for ($i = 0; $i < $pool_childs; $i++) { + if ($i == $pool_choosen) { + my $fh = $pool_pipes->{$i}->{'writer_two'}; + # It's when you loose a pool. You have to know + $$rebuild_progress = 1; + $$rebuild_pool_choosen = $pool_choosen; + print $fh "REBUILDBEGIN\t$host_name\t$service_description\n"; + } else { + my $fh = $pool_pipes->{$i}->{'writer_two'}; + print $fh "REBUILDBEGIN\n"; + } + } } sub call_pool_rebuild_finish { - my ($pool_pipes, $pool_childs, $delete_pipes, $rebuild_progress, $rebuild_pool_choosen) = @_; - my $fh; - - $$rebuild_progress = 0; - $$rebuild_pool_choosen = -1; - for ($i = 0; $i < $pool_childs; $i++) { - if ($rebuild_pool_choosen != $i) { - $fh = $pool_pipes->{$i}->{'writer_two'}; - print $fh "REBUILDFINISH\n"; - } - } - $fh = $delete_pipes->{'writer_two'}; - print $fh "REBUILDFINISH\n"; + my ($pool_pipes, $pool_childs, $delete_pipes, $rebuild_progress, $rebuild_pool_choosen) = @_; + my $fh; + + $$rebuild_progress = 0; + $$rebuild_pool_choosen = -1; + for ($i = 0; $i < $pool_childs; $i++) { + if ($rebuild_pool_choosen != $i) { + $fh = $pool_pipes->{$i}->{'writer_two'}; + print $fh "REBUILDFINISH\n"; + } + } + $fh = $delete_pipes->{'writer_two'}; + print $fh "REBUILDFINISH\n"; } sub call_pool_rename_clean { - my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs) = @_; - - my ($method, $old_host_name, $old_service_description, $new_host_name, $new_service_description) = split(/\t/, $line); - my $pool_choosen; - if (!defined($routing_services->{$old_host_name . ";" . $old_service_description})) { - # There is no for the old name. Can go back - my $fh = $pool_pipes->{$routing_services->{$new_host_name . ";" . $new_service_description}}->{'writer_two'}; - print $fh "RENAMEFINISH\t" . $new_host_name . "\t" . $new_service_description . "\n"; - return ; - } - # Send to clean - my $fh = $pool_pipes->{$routing_services->{$old_host_name . ";" . $old_service_description}}->{'writer_two'}; - print $fh "RENAMECLEAN\t" . $old_host_name . "\t" . $old_service_description . "\t" . $new_host_name . "\t" . $new_service_description . "\n"; + my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs) = @_; + + my ($method, $old_host_name, $old_service_description, $new_host_name, $new_service_description) = split(/\t/, $line); + my $pool_choosen; + if (!defined($routing_services->{$old_host_name . ";" . $old_service_description})) { + # There is no for the old name. Can go back + my $fh = $pool_pipes->{$routing_services->{$new_host_name . ";" . $new_service_description}}->{'writer_two'}; + print $fh "RENAMEFINISH\t" . $new_host_name . "\t" . $new_service_description . "\n"; + return ; + } + # Send to clean + my $fh = $pool_pipes->{$routing_services->{$old_host_name . ";" . $old_service_description}}->{'writer_two'}; + print $fh "RENAMECLEAN\t" . $old_host_name . "\t" . $old_service_description . "\t" . $new_host_name . "\t" . $new_service_description . "\n"; } sub call_pool_rename_finish { - my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs) = @_; - - my ($method, $new_host_name, $new_service_description) = split(/\t/, $line); - if (defined($routing_services->{$new_host_name . ";" . $new_service_description})) { - my $fh = $pool_pipes->{$routing_services->{$new_host_name . ";" . $new_service_description}}->{'writer_two'}; - print $fh "RENAMEFINISH\t" . $new_host_name . "\t" . $new_service_description . "\n"; - return ; - } + my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs) = @_; + + my ($method, $new_host_name, $new_service_description) = split(/\t/, $line); + if (defined($routing_services->{$new_host_name . ";" . $new_service_description})) { + my $fh = $pool_pipes->{$routing_services->{$new_host_name . ";" . $new_service_description}}->{'writer_two'}; + print $fh "RENAMEFINISH\t" . $new_host_name . "\t" . $new_service_description . "\n"; + return ; + } } sub call_pool_delete_clean { - my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs) = @_; - - my ($method, $host_name, $service_description) = split(/\t/, $line); - if (!defined($routing_services->{$host_name . ";" . $service_description})) { - # No cache. so we return - return ; - } - my $fh = $pool_pipes->{$routing_services->{$host_name . ";" . $service_description}}->{'writer_two'}; - print $fh "$line\n"; + my ($line, $pool_pipes, $routing_services, $roundrobin_pool_current, $pool_childs) = @_; + + my ($method, $host_name, $service_description) = split(/\t/, $line); + if (!defined($routing_services->{$host_name . ";" . $service_description})) { + # No cache. so we return + return ; + } + my $fh = $pool_pipes->{$routing_services->{$host_name . ";" . $service_description}}->{'writer_two'}; + print $fh "$line\n"; } sub can_write { - my $file = $_[0]; - my $dir = dirname($file); - - return 0 if (-d $dir && ! -w $dir); - return 0 if (-e $file && ! -w $file); - return 1; + my $file = $_[0]; + my $dir = dirname($file); + + return 0 if (-d $dir && ! -w $dir); + return 0 if (-e $file && ! -w $file); + return 1; } sub get_line_file { - my ($fh, $datas, $readed) = @_; - my $line; - my $size = scalar(@$datas); - - return (1, shift(@$datas)) if ($size > 1); - while ((my $eof = sysread($fh, $line, $read_size))) { - my @result = split("\n", $line); - if ($line =~ /\n$/) { - push @result, ""; - } - if ($size == 1) { - $$datas[0] .= shift(@result); - } - push @$datas, @result; - $$readed += $eof; - $size = scalar(@$datas); - if ($size > 1) { - return (1, shift(@$datas)); - } - } - return (1, shift(@$datas)) if ($size > 1); - return -1; + my ($fh, $datas, $readed) = @_; + my $line; + my $size = scalar(@$datas); + + return (1, shift(@$datas)) if ($size > 1); + while ((my $eof = sysread($fh, $line, $read_size))) { + my @result = split("\n", $line); + if ($line =~ /\n$/) { + push @result, ""; + } + if ($size == 1) { + $$datas[0] .= shift(@result); + } + push @$datas, @result; + $$readed += $eof; + $size = scalar(@$datas); + if ($size > 1) { + return (1, shift(@$datas)); + } + } + return (1, shift(@$datas)) if ($size > 1); + return -1; } sub get_line_pipe { - my ($fh, $datas, $read_done) = @_; - my $line; - my $size = scalar(@$datas); - - if ($size > 1) { - return (1, shift(@$datas)); - } elsif ($size == 1 && $$read_done == 1) { - return 0; - } - while ((my $eof = sysread($fh, $line, 10000))) { - $$read_done = 1; - my @result = split("\n", $line); - if ($line =~ /\n$/) { - push @result, ""; - } - if ($size == 1) { - $$datas[0] .= shift(@result); - } - push @$datas, @result; - $size = scalar(@$datas); - if ($size > 1) { - return (1, shift(@$datas)); - } else { - return 0; - } - } - return -1; + my ($fh, $datas, $read_done) = @_; + my $line; + my $size = scalar(@$datas); + + if ($size > 1) { + return (1, shift(@$datas)); + } elsif ($size == 1 && $$read_done == 1) { + return 0; + } + while ((my $eof = sysread($fh, $line, 10000))) { + $$read_done = 1; + my @result = split("\n", $line); + if ($line =~ /\n$/) { + push @result, ""; + } + if ($size == 1) { + $$datas[0] .= shift(@result); + } + push @$datas, @result; + $size = scalar(@$datas); + if ($size > 1) { + return (1, shift(@$datas)); + } else { + return 0; + } + } + return -1; } 1; diff --git a/centreon/lib/perl/centstorage/CentstoragePerfdataFile.pm b/centreon/lib/perl/centstorage/CentstoragePerfdataFile.pm index 9b5cf8bf73b..e44ec2f4877 100644 --- a/centreon/lib/perl/centstorage/CentstoragePerfdataFile.pm +++ b/centreon/lib/perl/centstorage/CentstoragePerfdataFile.pm @@ -8,117 +8,117 @@ use centstorage::CentstorageLib; my $end_size_buffer = 1*1024*1024*10; # 10Mo sub new { - my $class = shift; - my $self = {}; - $self->{"logger"} = shift; - $self->{"filehandler"} = undef; - $self->{"filename"} = undef; - $self->{"eof_file"} = 0; - $self->{"readed"} = 0; - $self->{"buffer"} = []; - bless $self, $class; - return $self; + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"filehandler"} = undef; + $self->{"filename"} = undef; + $self->{"eof_file"} = 0; + $self->{"readed"} = 0; + $self->{"buffer"} = []; + bless $self, $class; + return $self; } sub compute { - my $self = shift; - $self->{'filename'} = $_[0]; - my ($pool_pipes, $routing_services, $roundrobin_pool_current, $total_pool) = ($_[1], $_[2], $_[3], $_[4]); + my $self = shift; + $self->{'filename'} = $_[0]; + my ($pool_pipes, $routing_services, $roundrobin_pool_current, $total_pool) = ($_[1], $_[2], $_[3], $_[4]); - if ($self->{'filename'} !~ /_read$/) { - if (!(File::Copy::move($self->{'filename'}, $self->{'filename'} . "_read"))) { - $self->{"logger"}->writeLogError("Cannot move " . $self->{'filename'} . " file : $!"); - return -1; - } - if (!open($self->{"filehandler"}, '+< ' . $self->{"filename"} . "_read")) { - $self->{"logger"}->writeLogError("Cannot open " . $self->{'filename'} . "_read file : $!"); - return -1; - } - } else { - $self->{'filename'} =~ s/_read$//; - if (!open($self->{"filehandler"}, '+< ' . $self->{"filename"} . "_read")) { - $self->{"logger"}->writeLogError("Cannot open " . $self->{'filename'} . "_read file : $!"); - return -1; - } - } + if ($self->{'filename'} !~ /_read$/) { + if (!(File::Copy::move($self->{'filename'}, $self->{'filename'} . "_read"))) { + $self->{"logger"}->writeLogError("Cannot move " . $self->{'filename'} . " file : $!"); + return -1; + } + if (!open($self->{"filehandler"}, '+< ' . $self->{"filename"} . "_read")) { + $self->{"logger"}->writeLogError("Cannot open " . $self->{'filename'} . "_read file : $!"); + return -1; + } + } else { + $self->{'filename'} =~ s/_read$//; + if (!open($self->{"filehandler"}, '+< ' . $self->{"filename"} . "_read")) { + $self->{"logger"}->writeLogError("Cannot open " . $self->{'filename'} . "_read file : $!"); + return -1; + } + } - # Get offset if exist - if (-e $self->{'filename'} . "_read.offset") { - if (!open(FILE, "<", $self->{'filename'} . "_read.offset")) { - $self->{"logger"}->writeLogError("Can't read " . $self->{'filename'} . "_read.offset file: $!"); - return -1; - } - my $offset = ; - close FILE; - chomp $offset; - $offset = int($offset); - if ($offset =~ /^[0-9]+$/) { - seek($self->{"filehandler"}, $offset, 1); - $self->{"readed"} = $offset; - } - unlink($self->{'filename'} . "_read.offset"); - } + # Get offset if exist + if (-e $self->{'filename'} . "_read.offset") { + if (!open(FILE, "<", $self->{'filename'} . "_read.offset")) { + $self->{"logger"}->writeLogError("Can't read " . $self->{'filename'} . "_read.offset file: $!"); + return -1; + } + my $offset = ; + close FILE; + chomp $offset; + $offset = int($offset); + if ($offset =~ /^[0-9]+$/) { + seek($self->{"filehandler"}, $offset, 1); + $self->{"readed"} = $offset; + } + unlink($self->{'filename'} . "_read.offset"); + } - my $fh = $self->{"filehandler"}; - while ((my ($status, $readline) = centstorage::CentstorageLib::get_line_file($fh, \@{$self->{"buffer"}}, \$self->{"readed"}))) { - last if ($status == -1); - $readline =~ /([0-9]+?)\t+?([^\t]+?)\t+?([^\t]+?)\t/; - if (defined($1) && defined($2) && defined($3)) { - if (defined($routing_services->{$2 . ";" . $3})) { - my $tmp_fh = $pool_pipes->{$routing_services->{$2 . ";" . $3}}->{'writer_two'}; - print $tmp_fh "UPDATE\t$readline\n"; - } else { - # Choose a pool - my $pool_num = $$roundrobin_pool_current % $total_pool; - $$roundrobin_pool_current++; - my $tmp_fh = $pool_pipes->{$pool_num}->{'writer_two'}; - print $tmp_fh "UPDATE\t$readline\n"; - $routing_services->{$2 . ";" . $3} = $pool_num; - } - } - } + my $fh = $self->{"filehandler"}; + while ((my ($status, $readline) = centstorage::CentstorageLib::get_line_file($fh, \@{$self->{"buffer"}}, \$self->{"readed"}))) { + last if ($status == -1); + $readline =~ /([0-9]+?)\t+?([^\t]+?)\t+?([^\t]+?)\t/; + if (defined($1) && defined($2) && defined($3)) { + if (defined($routing_services->{$2 . ";" . $3})) { + my $tmp_fh = $pool_pipes->{$routing_services->{$2 . ";" . $3}}->{'writer_two'}; + print $tmp_fh "UPDATE\t$readline\n"; + } else { + # Choose a pool + my $pool_num = $$roundrobin_pool_current % $total_pool; + $$roundrobin_pool_current++; + my $tmp_fh = $pool_pipes->{$pool_num}->{'writer_two'}; + print $tmp_fh "UPDATE\t$readline\n"; + $routing_services->{$2 . ";" . $3} = $pool_num; + } + } + } - $self->{"eof_file"} = 1; - $self->finish(); - return 0; + $self->{"eof_file"} = 1; + $self->finish(); + return 0; } sub finish { - my $self = shift; + my $self = shift; - if (defined($self->{"filehandler"})) { - my $fh = $self->{"filehandler"}; - if ($self->{"eof_file"} == 1) { - if (!unlink($self->{"filename"} . "_read")) { - $self->{"logger"}->writeLogError("Cannot unlink " . $self->{'filename'} . "_read file : $!\n"); - } - close($fh); - } else { - $self->{"logger"}->writeLogInfo("Write Offset File " . $self->{'filename'} . "_read.offset file\n"); - if (open(FILE, ">", $self->{'filename'} . "_read.offset")) { - require bytes; + if (defined($self->{"filehandler"})) { + my $fh = $self->{"filehandler"}; + if ($self->{"eof_file"} == 1) { + if (!unlink($self->{"filename"} . "_read")) { + $self->{"logger"}->writeLogError("Cannot unlink " . $self->{'filename'} . "_read file : $!\n"); + } + close($fh); + } else { + $self->{"logger"}->writeLogInfo("Write Offset File " . $self->{'filename'} . "_read.offset file\n"); + if (open(FILE, ">", $self->{'filename'} . "_read.offset")) { + require bytes; - my $offset = $self->{"readed"}; - for (my $i = scalar(@{$self->{"buffer"}}) - 1; $i >= 0; $i--) { - $offset = $offset - bytes::length(${$self->{"buffer"}}[$i]) - 1; # -1 = \n - } - # Last: Don't have \n - $offset += 1; - print FILE $offset . "\n"; - close FILE; - } else { - $self->{"logger"}->writeLogError("Can't write offset " . $self->{'filename'} . "_read.offset file: $!\n"); - # Slurp File - my $rs_save = $/; - undef $/; - my $content_file = <$fh>; - seek($fh, 0, 0); - truncate($fh, 0); - print $fh $content_file; - $/ = $rs_save; - } - } - } + my $offset = $self->{"readed"}; + for (my $i = scalar(@{$self->{"buffer"}}) - 1; $i >= 0; $i--) { + $offset = $offset - bytes::length(${$self->{"buffer"}}[$i]) - 1; # -1 = \n + } + # Last: Don't have \n + $offset += 1; + print FILE $offset . "\n"; + close FILE; + } else { + $self->{"logger"}->writeLogError("Can't write offset " . $self->{'filename'} . "_read.offset file: $!\n"); + # Slurp File + my $rs_save = $/; + undef $/; + my $content_file = <$fh>; + seek($fh, 0, 0); + truncate($fh, 0); + print $fh $content_file; + $/ = $rs_save; + } + } + } } 1; diff --git a/centreon/lib/perl/centstorage/CentstoragePool.pm b/centreon/lib/perl/centstorage/CentstoragePool.pm index 975af4beb75..38d62a34462 100644 --- a/centreon/lib/perl/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centstorage/CentstoragePool.pm @@ -11,36 +11,36 @@ my %handlers = ('TERM' => {}, 'CHLD' => {}); my %rrd_trans = ("g" => 0, "c" => 1, "d" => 2, "a" => 3); sub new { - my $class = shift; - my $self = {}; - $self->{"logger"} = shift; - $self->{"rrd"} = shift; - $self->{"rebuild_progress"} = shift; - $self->{"dbcentreon"} = undef; - $self->{"dbcentstorage"} = undef; - - $self->{"len_storage_rrd"} = undef; - $self->{"rrd_metrics_path"} = undef; - $self->{"rrd_status_path"} = undef; - $self->{"main_perfdata_file"} = undef; - $self->{"interval_time"} = undef; - $self->{"do_rrd_status"} = 1; - $self->{"TIMEOUT"} = 30; - $self->{"num_pool"} = undef; - # If rebuild in progress, we don't try to insert in DATA_BIN - - $self->{"storage_type"} = undef; - # { - # 'metrics' => {'name1' => {}, 'name2' => {} } - # 'service_id' => - # 'host_id' => - # 'storage_type' => - # 'check_interval' => - # 'index_id' => - # 'rebuild' => - # 'rrd_retention' => - # } - $self->{"cache_service"} = {}; + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"rrd"} = shift; + $self->{"rebuild_progress"} = shift; + $self->{"dbcentreon"} = undef; + $self->{"dbcentstorage"} = undef; + + $self->{"len_storage_rrd"} = undef; + $self->{"rrd_metrics_path"} = undef; + $self->{"rrd_status_path"} = undef; + $self->{"main_perfdata_file"} = undef; + $self->{"interval_time"} = undef; + $self->{"do_rrd_status"} = 1; + $self->{"TIMEOUT"} = 30; + $self->{"num_pool"} = undef; + # If rebuild in progress, we don't try to insert in DATA_BIN + + $self->{"storage_type"} = undef; + # { + # 'metrics' => {'name1' => {}, 'name2' => {} } + # 'service_id' => + # 'host_id' => + # 'storage_type' => + # 'check_interval' => + # 'index_id' => + # 'rebuild' => + # 'rrd_retention' => + # } + $self->{"cache_service"} = {}; # Perfdata parsing vars $self->{"perfdata_pos"} = undef; @@ -49,151 +49,151 @@ sub new { $self->{"perfdata_parser_stop"} = 0; - $self->{"service_perfdata"} = undef; - $self->{"metric_name"} = undef; - $self->{"metric_value"} = undef; - $self->{"metric_unit"} = undef; - $self->{"metric_warn"} = undef; - $self->{"metric_crit"} = undef; - $self->{"metric_min"} = undef; - $self->{"metric_max"} = undef; - - # By service - $self->{"cache_services_failed"} = {}; - $self->{"last_check_failed"} = time(); - $self->{"check_failed_every"} = 60 * 10; # 20 minutes - - # Rename - $self->{"cache_services_rename"} = {}; - $self->{"rename_rebuild_wait"} = 0; - $self->{"rename_old_new"} = {}; - - $self->{"group_databin_stmt"} = ""; - $self->{"group_databin_total"} = 0; - $self->{"group_databin_append"} = ""; - $self->{"group_databin_max"} = 500; - - $self->{"rebuild_index_id"} = undef; - $self->{"rebuild_key"} = undef; - $self->{"current_pid"} = undef; - - $self->{"save_read"} = []; - $self->{"read_select"} = undef; - $self->{"pipe_write"} = undef; - bless $self, $class; - $self->set_signal_handlers; - return $self; + $self->{"service_perfdata"} = undef; + $self->{"metric_name"} = undef; + $self->{"metric_value"} = undef; + $self->{"metric_unit"} = undef; + $self->{"metric_warn"} = undef; + $self->{"metric_crit"} = undef; + $self->{"metric_min"} = undef; + $self->{"metric_max"} = undef; + + # By service + $self->{"cache_services_failed"} = {}; + $self->{"last_check_failed"} = time(); + $self->{"check_failed_every"} = 60 * 10; # 20 minutes + + # Rename + $self->{"cache_services_rename"} = {}; + $self->{"rename_rebuild_wait"} = 0; + $self->{"rename_old_new"} = {}; + + $self->{"group_databin_stmt"} = ""; + $self->{"group_databin_total"} = 0; + $self->{"group_databin_append"} = ""; + $self->{"group_databin_max"} = 500; + + $self->{"rebuild_index_id"} = undef; + $self->{"rebuild_key"} = undef; + $self->{"current_pid"} = undef; + + $self->{"save_read"} = []; + $self->{"read_select"} = undef; + $self->{"pipe_write"} = undef; + bless $self, $class; + $self->set_signal_handlers; + return $self; } sub set_signal_handlers { - my $self = shift; + my $self = shift; - $SIG{TERM} = \&class_handle_TERM; - $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; - $SIG{CHLD} = \&class_handle_CHLD; - $handlers{'CHLD'}->{$self} = sub { $self->handle_CHLD() }; + $SIG{TERM} = \&class_handle_TERM; + $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; + $SIG{CHLD} = \&class_handle_CHLD; + $handlers{'CHLD'}->{$self} = sub { $self->handle_CHLD() }; } sub handle_TERM { - my $self = shift; - $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); - - if (defined($self->{"current_pid"})) { - $self->{'logger'}->writeLogInfo("Send -TERM signal to rebuild process.."); - kill('TERM', $self->{"current_pid"}); - } - - ### - # Flush Data_bin - ### - eval { - local $SIG{ALRM} = sub { die "alarm\n" }; - alarm 5; - $self->flush_mysql(1); - alarm 0; - }; - if ($@) { - $self->{'dbcentstorage'}->kill(); - } - $self->{'dbcentreon'}->disconnect() if (defined($self->{'dbcentreon'})); - $self->{'dbcentstorage'}->disconnect() if (defined($self->{'dbcentstorage'})); - - ### - # Flush RRD - ### - $self->{'rrd'}->flush_all(1); - - ### - # Write In File - ### - if (open(FILE, '>> ' . $self->{"main_perfdata_file"} . "_" . $self->{'num_pool'} . ".bckp")) { - foreach my $id (keys %{$self->{"cache_services_failed"}}) { - foreach (@{$self->{"cache_services_failed"}->{$id}}) { - print FILE join("\t", @$_) . "\n"; - } - } - - # Rename - foreach my $id (keys %{$self->{"cache_services_rename"}}) { - foreach (@{$self->{"cache_services_rename"}->{$id}}) { - print FILE join("\t", @$_) . "\n"; - } - } - - - ### Try to read pipe - my @rh_set = $self->{'read_select'}->can_read(1); - if (scalar(@rh_set) > 0) { - foreach my $rh (@rh_set) { - my $read_done = 0; - while ((my ($status_line, $readline) = CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { - last if ($status_line <= 0); - if ($readline =~ /^UPDATE/) { - $readline =~ s/^UPDATE\t//; - print FILE $readline . "\n"; - } - } - } - } - close FILE; - } else { - $self->{"logger"}->writeLogError("Cannot open " . $self->{"main_perfdata_file"} . "_" . $self->{'num_pool'} . ".bckp file : $!"); - } - - ### - # Check Child - ### - my $kill_or_not = 1; - for (my $i = 0; $i < $self->{"TIMEOUT"}; $i++) { - if (!defined($self->{"current_pid"})) { - $kill_or_not = 0; - last; - } - sleep(1); - } - - if ($kill_or_not == 1) { - $self->{'logger'}->writeLogInfo("Send -KILL signal to rebuild process.."); - kill('KILL', $self->{"current_pid"}); - } + my $self = shift; + $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); + + if (defined($self->{"current_pid"})) { + $self->{'logger'}->writeLogInfo("Send -TERM signal to rebuild process.."); + kill('TERM', $self->{"current_pid"}); + } + + ### + # Flush Data_bin + ### + eval { + local $SIG{ALRM} = sub { die "alarm\n" }; + alarm 5; + $self->flush_mysql(1); + alarm 0; + }; + if ($@) { + $self->{'dbcentstorage'}->kill(); + } + $self->{'dbcentreon'}->disconnect() if (defined($self->{'dbcentreon'})); + $self->{'dbcentstorage'}->disconnect() if (defined($self->{'dbcentstorage'})); + + ### + # Flush RRD + ### + $self->{'rrd'}->flush_all(1); + + ### + # Write In File + ### + if (open(FILE, '>> ' . $self->{"main_perfdata_file"} . "_" . $self->{'num_pool'} . ".bckp")) { + foreach my $id (keys %{$self->{"cache_services_failed"}}) { + foreach (@{$self->{"cache_services_failed"}->{$id}}) { + print FILE join("\t", @$_) . "\n"; + } + } + + # Rename + foreach my $id (keys %{$self->{"cache_services_rename"}}) { + foreach (@{$self->{"cache_services_rename"}->{$id}}) { + print FILE join("\t", @$_) . "\n"; + } + } + + + ### Try to read pipe + my @rh_set = $self->{'read_select'}->can_read(1); + if (scalar(@rh_set) > 0) { + foreach my $rh (@rh_set) { + my $read_done = 0; + while ((my ($status_line, $readline) = CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + last if ($status_line <= 0); + if ($readline =~ /^UPDATE/) { + $readline =~ s/^UPDATE\t//; + print FILE $readline . "\n"; + } + } + } + } + close FILE; + } else { + $self->{"logger"}->writeLogError("Cannot open " . $self->{"main_perfdata_file"} . "_" . $self->{'num_pool'} . ".bckp file : $!"); + } + + ### + # Check Child + ### + my $kill_or_not = 1; + for (my $i = 0; $i < $self->{"TIMEOUT"}; $i++) { + if (!defined($self->{"current_pid"})) { + $kill_or_not = 0; + last; + } + sleep(1); + } + + if ($kill_or_not == 1) { + $self->{'logger'}->writeLogInfo("Send -KILL signal to rebuild process.."); + kill('KILL', $self->{"current_pid"}); + } } sub handle_CHLD { - my $self = shift; - my $child_pid; - my $exit_code; - - $self->{'logger'}->writeLogInfo("Received SIGCHLD..."); - $self->{"current_pid"} = undef; - if ($self->{"rename_rebuild_wait"} == 1) { - my ($new_host_name, $new_service_description) = split(';', $self->{"rename_old_new"}->{$self->{"rebuild_key"}}); - $self->force_flush_rrd($self->{"rebuild_key"}); - delete $self->{"cache_service"}->{$self->{"rebuild_key"}}; - delete $self->{"cache_services_failed"}->{$self->{"rebuild_key"}}; - delete $self->{"rename_old_new"}->{$self->{"rebuild_key"}}; - $self->send_rename_finish($new_host_name, $new_service_description); - } - $self->rebuild_finish(); + my $self = shift; + my $child_pid; + my $exit_code; + + $self->{'logger'}->writeLogInfo("Received SIGCHLD..."); + $self->{"current_pid"} = undef; + if ($self->{"rename_rebuild_wait"} == 1) { + my ($new_host_name, $new_service_description) = split(';', $self->{"rename_old_new"}->{$self->{"rebuild_key"}}); + $self->force_flush_rrd($self->{"rebuild_key"}); + delete $self->{"cache_service"}->{$self->{"rebuild_key"}}; + delete $self->{"cache_services_failed"}->{$self->{"rebuild_key"}}; + delete $self->{"rename_old_new"}->{$self->{"rebuild_key"}}; + $self->send_rename_finish($new_host_name, $new_service_description); + } + $self->rebuild_finish(); while (($child_pid = waitpid(-1, &POSIX::WNOHANG)) > 0) { $exit_code = $? >> 8; } @@ -201,241 +201,241 @@ sub handle_CHLD { } sub class_handle_TERM { - foreach (keys %{$handlers{'TERM'}}) { - &{$handlers{'TERM'}->{$_}}(); - } - exit(0); + foreach (keys %{$handlers{'TERM'}}) { + &{$handlers{'TERM'}->{$_}}(); + } + exit(0); } sub class_handle_CHLD { - foreach (keys %{$handlers{'CHLD'}}) { - &{$handlers{'CHLD'}->{$_}}(); - } + foreach (keys %{$handlers{'CHLD'}}) { + &{$handlers{'CHLD'}->{$_}}(); + } } sub add_data_mysql { - my $self = shift; - my ($metric_id, $ctime, $value) = @_; - - $self->{"group_databin_stmt"} .= $self->{"group_databin_append"} . "('$metric_id', '$ctime', '$value')"; - $self->{"group_databin_append"} = ", "; - $self->{"group_databin_total"}++; + my $self = shift; + my ($metric_id, $ctime, $value) = @_; + + $self->{"group_databin_stmt"} .= $self->{"group_databin_append"} . "('$metric_id', '$ctime', '$value')"; + $self->{"group_databin_append"} = ", "; + $self->{"group_databin_total"}++; } sub force_flush_rrd { - my $self = shift; - my ($key) = @_; + my $self = shift; + my ($key) = @_; - if (defined($self->{"cache_service"}->{$key})) { - foreach (keys %{$self->{"cache_service"}->{$key}->{'metrics'}}) { - $self->{'rrd'}->flush_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$_}->{'metric_id'}); - } + if (defined($self->{"cache_service"}->{$key})) { + foreach (keys %{$self->{"cache_service"}->{$key}->{'metrics'}}) { + $self->{'rrd'}->flush_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$_}->{'metric_id'}); + } - $self->{'rrd'}->flush_status($self->{"cache_service"}->{$key}->{'index_id'}); - } + $self->{'rrd'}->flush_status($self->{"cache_service"}->{$key}->{'index_id'}); + } } sub flush_mysql { - my $self = shift; - my ($force) = @_; - - return 0 if ($self->{"rebuild_progress"} == 1 && (!defined($force) || $force == 0)); - if ((defined($force) && $force == 1 && $self->{"group_databin_total"} > 0) || $self->{"group_databin_total"} > $self->{"group_databin_max"}) { - my $rq = "INSERT INTO `data_bin` (`id_metric`, `ctime`, `value`) VALUES " . $self->{"group_databin_stmt"}; - my ($status, $stmt) = $self->{'dbcentstorage'}->query($rq); - $self->{"group_databin_total"} = 0; - $self->{"group_databin_append"} = ""; - $self->{"group_databin_stmt"} = ""; - } + my $self = shift; + my ($force) = @_; + + return 0 if ($self->{"rebuild_progress"} == 1 && (!defined($force) || $force == 0)); + if ((defined($force) && $force == 1 && $self->{"group_databin_total"} > 0) || $self->{"group_databin_total"} > $self->{"group_databin_max"}) { + my $rq = "INSERT INTO `data_bin` (`id_metric`, `ctime`, `value`) VALUES " . $self->{"group_databin_stmt"}; + my ($status, $stmt) = $self->{'dbcentstorage'}->query($rq); + $self->{"group_databin_total"} = 0; + $self->{"group_databin_append"} = ""; + $self->{"group_databin_stmt"} = ""; + } } sub flush_failed { - my $self = shift; - - if (time() > ($self->{"last_check_failed"} + $self->{"check_failed_every"})) { - # Need to reconnect (maybe a gone away. So we try) - $self->{'dbcentreon'}->disconnect(); - $self->{'dbcentreon'}->connect(); - - $self->{'logger'}->writeLogInfo("Begin Cache Services Failed"); - foreach my $id (keys %{$self->{"cache_services_failed"}}) { - next if ($self->{"rebuild_progress"} == 1 && $id == $self->{"rebuild_key"}); - my @tmp_ar = (); - my $lerror = 0; - foreach (@{$self->{"cache_services_failed"}->{$id}}) { - if ($lerror == 0 && $self->update(1, @$_) != 0) { - push @tmp_ar, \@$_; - $lerror = 1; - } else { - push @tmp_ar, \@$_; - } - } - if (scalar(@tmp_ar) != 0) { - @{$self->{"cache_services_failed"}->{$id}} = @tmp_ar; - } else { - delete $self->{"cache_services_failed"}->{$id}; - } - } - $self->{"last_check_failed"} = time(); - } + my $self = shift; + + if (time() > ($self->{"last_check_failed"} + $self->{"check_failed_every"})) { + # Need to reconnect (maybe a gone away. So we try) + $self->{'dbcentreon'}->disconnect(); + $self->{'dbcentreon'}->connect(); + + $self->{'logger'}->writeLogInfo("Begin Cache Services Failed"); + foreach my $id (keys %{$self->{"cache_services_failed"}}) { + next if ($self->{"rebuild_progress"} == 1 && $id == $self->{"rebuild_key"}); + my @tmp_ar = (); + my $lerror = 0; + foreach (@{$self->{"cache_services_failed"}->{$id}}) { + if ($lerror == 0 && $self->update(1, @$_) != 0) { + push @tmp_ar, \@$_; + $lerror = 1; + } else { + push @tmp_ar, \@$_; + } + } + if (scalar(@tmp_ar) != 0) { + @{$self->{"cache_services_failed"}->{$id}} = @tmp_ar; + } else { + delete $self->{"cache_services_failed"}->{$id}; + } + } + $self->{"last_check_failed"} = time(); + } } sub remove_special_char_metric { - my $self = shift; - my $remove_special_char = $_[0]; - - $remove_special_char =~ s/\./\-/g; - $remove_special_char =~ s/\,/\-/g; - $remove_special_char =~ s/\:/\-/g; - $remove_special_char =~ s/\ /\-/g; - return $remove_special_char; + my $self = shift; + my $remove_special_char = $_[0]; + + $remove_special_char =~ s/\./\-/g; + $remove_special_char =~ s/\,/\-/g; + $remove_special_char =~ s/\:/\-/g; + $remove_special_char =~ s/\ /\-/g; + return $remove_special_char; } sub create_metric { - my $self = shift; - my ($index_id, $cache_metrics, $metric_name) = @_; - - # Check if exists already - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT * FROM `metrics` WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($metric_name) . " LIMIT 1"); - return -1 if ($status == -1); - my $data = $stmt->fetchrow_hashref(); - # move part for compat with old centstorage name - if (!defined($data)) { - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT * FROM `metrics` WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($self->remove_special_char_metric($metric_name)) . " LIMIT 1"); - return -1 if ($status == -1); - $data = $stmt->fetchrow_hashref(); - if (defined($data)) { - ($status) = $self->{'dbcentstorage'}->query("UPDATE `metrics` SET `metric_name` = " . $self->{'dbcentstorage'}->quote($metric_name) . " WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($self->remove_special_char_metric($metric_name)) . " LIMIT 1"); - return -1 if ($status == -1); - } else { - # Insert - ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `metrics` (`index_id`, `metric_name`, `unit_name`, `warn`, `crit`, `min`, `max`, `data_source_type`) VALUES ('" . $index_id . "', " . $self->{'dbcentstorage'}->quote($metric_name) . ", '" . $self->{"metric_unit"} . "', '" . $self->{"metric_warn"} . "', '" . $self->{"metric_crit"} . "', '" . $self->{"metric_min"} . "', '" . $self->{"metric_max"} . "', '" . $self->{"metric_type"} . "')"); - return -1 if ($status); - my $last_insert_id = $self->{'dbcentstorage'}->last_insert_id(); - $$cache_metrics->{$metric_name} = {'metric_id' => $last_insert_id, 'metric_unit' => $self->{"metric_unit"}, 'metric_warn' => $self->{"metric_warn"}, 'metric_crit' => $self->{"metric_crit"}, 'metric_min' => $self->{"metric_min"}, 'metric_max' => $self->{"metric_max"}, 'data_source_type' => $self->{"metric_type"}}; - - return 0; - } - } - # We get - $$cache_metrics->{$metric_name} = {'metric_id' => $data->{'metric_id'}, 'metric_unit' => defined($data->{"unit_name"}) ? $data->{"unit_name"} : "", 'metric_warn' => defined($data->{"warn"}) ? $data->{"warn"} : "", 'metric_crit' => defined($data->{"crit"}) ? $data->{"crit"} : "", 'metric_min' => defined($data->{"min"}) ? $data->{"min"} : "", 'metric_max' => defined($data->{"max"}) ? $data->{"max"} : "", 'data_source_type' => $data->{"data_source_type"}}; - return 0; + my $self = shift; + my ($index_id, $cache_metrics, $metric_name) = @_; + + # Check if exists already + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT * FROM `metrics` WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($metric_name) . " LIMIT 1"); + return -1 if ($status == -1); + my $data = $stmt->fetchrow_hashref(); + # move part for compat with old centstorage name + if (!defined($data)) { + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT * FROM `metrics` WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($self->remove_special_char_metric($metric_name)) . " LIMIT 1"); + return -1 if ($status == -1); + $data = $stmt->fetchrow_hashref(); + if (defined($data)) { + ($status) = $self->{'dbcentstorage'}->query("UPDATE `metrics` SET `metric_name` = " . $self->{'dbcentstorage'}->quote($metric_name) . " WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($self->remove_special_char_metric($metric_name)) . " LIMIT 1"); + return -1 if ($status == -1); + } else { + # Insert + ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `metrics` (`index_id`, `metric_name`, `unit_name`, `warn`, `crit`, `min`, `max`, `data_source_type`) VALUES ('" . $index_id . "', " . $self->{'dbcentstorage'}->quote($metric_name) . ", '" . $self->{"metric_unit"} . "', '" . $self->{"metric_warn"} . "', '" . $self->{"metric_crit"} . "', '" . $self->{"metric_min"} . "', '" . $self->{"metric_max"} . "', '" . $self->{"metric_type"} . "')"); + return -1 if ($status); + my $last_insert_id = $self->{'dbcentstorage'}->last_insert_id(); + $$cache_metrics->{$metric_name} = {'metric_id' => $last_insert_id, 'metric_unit' => $self->{"metric_unit"}, 'metric_warn' => $self->{"metric_warn"}, 'metric_crit' => $self->{"metric_crit"}, 'metric_min' => $self->{"metric_min"}, 'metric_max' => $self->{"metric_max"}, 'data_source_type' => $self->{"metric_type"}}; + + return 0; + } + } + # We get + $$cache_metrics->{$metric_name} = {'metric_id' => $data->{'metric_id'}, 'metric_unit' => defined($data->{"unit_name"}) ? $data->{"unit_name"} : "", 'metric_warn' => defined($data->{"warn"}) ? $data->{"warn"} : "", 'metric_crit' => defined($data->{"crit"}) ? $data->{"crit"} : "", 'metric_min' => defined($data->{"min"}) ? $data->{"min"} : "", 'metric_max' => defined($data->{"max"}) ? $data->{"max"} : "", 'data_source_type' => $data->{"data_source_type"}}; + return 0; } sub check_update_extra_metric { - my $self = shift; - my $cache_metric = $_[0]; - - if ($$cache_metric->{'metric_unit'} ne $self->{"metric_unit"} || - $$cache_metric->{'metric_warn'} ne $self->{"metric_warn"} || - $$cache_metric->{'metric_crit'} ne $self->{"metric_crit"} || - $$cache_metric->{'metric_min'} ne $self->{"metric_min"} || - $$cache_metric->{'metric_max'} ne $self->{"metric_max"}) { - $self->{'dbcentstorage'}->query("UPDATE `metrics` SET `unit_name` = " . $self->{'dbcentstorage'}->quote($self->{"metric_unit"}) . ", `warn` = '" . $self->{"metric_warn"} . "', `crit` = '" . $self->{"metric_crit"} . "', `min` = '" . $self->{"metric_min"} . "', `max` = '" . $self->{"metric_max"} . "' WHERE `metric_id` = " . $$cache_metric->{'metric_id'}); - $$cache_metric->{'metric_unit'} = $self->{"metric_unit"}; - $$cache_metric->{'metric_warn'} = $self->{"metric_warn"}; - $$cache_metric->{'metric_crit'} = $self->{"metric_crit"}; - $$cache_metric->{'metric_min'} = $self->{"metric_min"}; - $$cache_metric->{'metric_max'} = $self->{"metric_max"}; - } + my $self = shift; + my $cache_metric = $_[0]; + + if ($$cache_metric->{'metric_unit'} ne $self->{"metric_unit"} || + $$cache_metric->{'metric_warn'} ne $self->{"metric_warn"} || + $$cache_metric->{'metric_crit'} ne $self->{"metric_crit"} || + $$cache_metric->{'metric_min'} ne $self->{"metric_min"} || + $$cache_metric->{'metric_max'} ne $self->{"metric_max"}) { + $self->{'dbcentstorage'}->query("UPDATE `metrics` SET `unit_name` = " . $self->{'dbcentstorage'}->quote($self->{"metric_unit"}) . ", `warn` = '" . $self->{"metric_warn"} . "', `crit` = '" . $self->{"metric_crit"} . "', `min` = '" . $self->{"metric_min"} . "', `max` = '" . $self->{"metric_max"} . "' WHERE `metric_id` = " . $$cache_metric->{'metric_id'}); + $$cache_metric->{'metric_unit'} = $self->{"metric_unit"}; + $$cache_metric->{'metric_warn'} = $self->{"metric_warn"}; + $$cache_metric->{'metric_crit'} = $self->{"metric_crit"}; + $$cache_metric->{'metric_min'} = $self->{"metric_min"}; + $$cache_metric->{'metric_max'} = $self->{"metric_max"}; + } } sub send_rename_command { - my $self = shift; - my ($old_host_name, $old_service_description, $new_host_name, $new_service_description) = @_; - - $self->{'logger'}->writeLogInfo("Hostname/Servicename changed had been detected " . $old_host_name . "/" . $old_service_description); - my $fh = $self->{'pipe_write'}; + my $self = shift; + my ($old_host_name, $old_service_description, $new_host_name, $new_service_description) = @_; + + $self->{'logger'}->writeLogInfo("Hostname/Servicename changed had been detected " . $old_host_name . "/" . $old_service_description); + my $fh = $self->{'pipe_write'}; print $fh "RENAMECLEAN\t" . $old_host_name . "\t" . $old_service_description . "\t" . $new_host_name . "\t" . $new_service_description . "\n"; } sub create_service { - my $self = shift; - my ($host_id, $service_id, $interval, $host_name, $service_description) = @_; - my ($status, $stmt); - - if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `storage_type`, `host_name`, `service_description`, `rrd_retention` FROM `index_data` WHERE `host_name` = " . $self->{'dbcentstorage'}->quote($host_name) . " AND `service_description` = " . $self->{'dbcentstorage'}->quote($service_description) . " LIMIT 1"); - } else { - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `storage_type`, `host_name`, `service_description`, `rrd_retention` FROM `index_data` WHERE `host_id` = " . $host_id . " AND `service_id` = " . $service_id . " LIMIT 1"); - } - return -1 if ($status == -1); - my $data = $stmt->fetchrow_hashref(); - if (defined($data) && ($data->{'host_name'} ne $host_name || $data->{'service_description'} ne $service_description)) { - ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE `index_data` SET `host_name` = " . $self->{'dbcentstorage'}->quote($host_name) . ", `service_description` = " . $self->{'dbcentreon'}->quote($service_description) . " WHERE id = " . $data->{'id'}); - if ($status != -1) { - $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = int($data->{'storage_type'}); - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $data->{'id'}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; - # Send command to clean cache - $self->send_rename_command($data->{'host_name'}, $data->{'service_description'}, $host_name, $service_description); - return -2; - } - } elsif (defined($data) && ($data->{'host_name'} eq $host_name || $data->{'service_description'} eq $service_description)) { - # same name but exist already - $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = int($data->{'storage_type'}); - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $data->{'id'}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; - } else { - # create - if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { - ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `index_data` (`host_name`, `service_description`, `host_id`, `service_id`, `special`, `storage_type`) VALUES (" . $self->{'dbcentstorage'}->quote($host_name) . ", " . $self->{'dbcentstorage'}->quote($service_description) . ", " . $host_id . ", " . $service_id . ", '1', '" . $self->{'storage_type'} . "')"); - } else { - ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `index_data` (`host_name`, `service_description`, `host_id`, `service_id`, `storage_type`) VALUES (" . $self->{'dbcentstorage'}->quote($host_name) . ", " . $self->{'dbcentstorage'}->quote($service_description) . ", " . $host_id . ", " . $service_id . ", '" . $self->{'storage_type'} . "')"); - } - if ($status != -1) { - $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = $self->{'storage_type'}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $self->{'dbcentstorage'}->last_insert_id(); - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = -1; - } - } - - return $status; + my $self = shift; + my ($host_id, $service_id, $interval, $host_name, $service_description) = @_; + my ($status, $stmt); + + if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `storage_type`, `host_name`, `service_description`, `rrd_retention` FROM `index_data` WHERE `host_name` = " . $self->{'dbcentstorage'}->quote($host_name) . " AND `service_description` = " . $self->{'dbcentstorage'}->quote($service_description) . " LIMIT 1"); + } else { + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `storage_type`, `host_name`, `service_description`, `rrd_retention` FROM `index_data` WHERE `host_id` = " . $host_id . " AND `service_id` = " . $service_id . " LIMIT 1"); + } + return -1 if ($status == -1); + my $data = $stmt->fetchrow_hashref(); + if (defined($data) && ($data->{'host_name'} ne $host_name || $data->{'service_description'} ne $service_description)) { + ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE `index_data` SET `host_name` = " . $self->{'dbcentstorage'}->quote($host_name) . ", `service_description` = " . $self->{'dbcentreon'}->quote($service_description) . " WHERE id = " . $data->{'id'}); + if ($status != -1) { + $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = int($data->{'storage_type'}); + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $data->{'id'}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; + # Send command to clean cache + $self->send_rename_command($data->{'host_name'}, $data->{'service_description'}, $host_name, $service_description); + return -2; + } + } elsif (defined($data) && ($data->{'host_name'} eq $host_name || $data->{'service_description'} eq $service_description)) { + # same name but exist already + $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = int($data->{'storage_type'}); + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $data->{'id'}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; + } else { + # create + if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { + ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `index_data` (`host_name`, `service_description`, `host_id`, `service_id`, `special`, `storage_type`) VALUES (" . $self->{'dbcentstorage'}->quote($host_name) . ", " . $self->{'dbcentstorage'}->quote($service_description) . ", " . $host_id . ", " . $service_id . ", '1', '" . $self->{'storage_type'} . "')"); + } else { + ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `index_data` (`host_name`, `service_description`, `host_id`, `service_id`, `storage_type`) VALUES (" . $self->{'dbcentstorage'}->quote($host_name) . ", " . $self->{'dbcentstorage'}->quote($service_description) . ", " . $host_id . ", " . $service_id . ", '" . $self->{'storage_type'} . "')"); + } + if ($status != -1) { + $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = $self->{'storage_type'}; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $self->{'dbcentstorage'}->last_insert_id(); + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; + $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = -1; + } + } + + return $status; } sub get_centstorage_information { - my $self = shift; - my ($len_storage_rrd, $rrd_metrics_path, $rrd_status_path, $storage_type); - - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT len_storage_rrd, RRDdatabase_path, RRDdatabase_status_path, storage_type FROM config"); - my $data = $stmt->fetchrow_hashref(); - if (defined($data)) { - $len_storage_rrd = int($data->{'len_storage_rrd'}); - $rrd_metrics_path = $data->{'RRDdatabase_path'}; - $rrd_status_path = $data->{'RRDdatabase_status_path'}; - $storage_type = int($data->{'storage_type'}); - } - return ($status, $len_storage_rrd, $rrd_metrics_path, $rrd_status_path, $storage_type); + my $self = shift; + my ($len_storage_rrd, $rrd_metrics_path, $rrd_status_path, $storage_type); + + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT len_storage_rrd, RRDdatabase_path, RRDdatabase_status_path, storage_type FROM config"); + my $data = $stmt->fetchrow_hashref(); + if (defined($data)) { + $len_storage_rrd = int($data->{'len_storage_rrd'}); + $rrd_metrics_path = $data->{'RRDdatabase_path'}; + $rrd_status_path = $data->{'RRDdatabase_status_path'}; + $storage_type = int($data->{'storage_type'}); + } + return ($status, $len_storage_rrd, $rrd_metrics_path, $rrd_status_path, $storage_type); } sub get_centreon_intervaltime { - my $self = shift; - my $interval = 60; - - my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT `value` AS interval_length FROM options WHERE `key` = 'interval_length'"); - my $data = $stmt->fetchrow_hashref(); - if (defined($data)) { - $interval = $data->{'interval_length'}; - } - return (0, $interval); + my $self = shift; + my $interval = 60; + + my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT `value` AS interval_length FROM options WHERE `key` = 'interval_length'"); + my $data = $stmt->fetchrow_hashref(); + if (defined($data)) { + $interval = $data->{'interval_length'}; + } + return (0, $interval); } ############################# @@ -537,9 +537,9 @@ sub get_perfdata { my $self = shift; my ($counter_type, $perf_label, $perf_value, $perf_unit, $perf_warn, $perf_crit, $perf_min, $perf_max); - if (!defined($self->{'service_perfdata'}) || $self->{"perfdata_pos"} >= $self->{"perfdata_size"}) { - return 0; - } + if (!defined($self->{'service_perfdata'}) || $self->{"perfdata_pos"} >= $self->{"perfdata_size"}) { + return 0; + } $self->skip_chars("[ \t]"); $perf_label = $self->parse_label(); @@ -609,490 +609,490 @@ sub init_perfdata { ###################################################### sub cache_update_service_index_data { - my $self = shift; - my ($key) = @_; + my $self = shift; + my ($key) = @_; - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT rrd_retention FROM index_data WHERE id = " . $self->{"cache_service"}->{$key}->{'index_id'}); + my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT rrd_retention FROM index_data WHERE id = " . $self->{"cache_service"}->{$key}->{'index_id'}); if ($status == -1) { $self->{'logger'}->writeLogError("Cannot get index_data"); return -1; } - my $data = $stmt->fetchrow_hashref(); - if (!defined($data)) { - $self->{'logger'}->writeLogError("Can't find index_data"); - return -1; - } - $self->{"cache_service"}->{$key}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; - return 0; + my $data = $stmt->fetchrow_hashref(); + if (!defined($data)) { + $self->{'logger'}->writeLogError("Can't find index_data"); + return -1; + } + $self->{"cache_service"}->{$key}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; + return 0; } # Module meta/bam or normal are specified in tables sub get_host_service_ids { - my $self = shift; - my ($host_name, $service_description) = @_; - my ($host_id, $service_id); - my ($status, $stmt, $data); - my $host_register = 1; - - # For Modules - if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { - $host_register = 2; - } - # Get Host_Id - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT `host_id` FROM `host` WHERE `host_name` = " . $self->{'dbcentreon'}->quote($host_name) . " AND `host_register` = '$host_register' LIMIT 1"); - return -1 if ($status); - $data = $stmt->fetchrow_hashref(); - if (!defined($data)) { - $self->{'logger'}->writeLogError("Can't find 'host_id' $host_name"); - return -1; - } - - $host_id = $data->{'host_id'}; - # For 'BAM' module: in 'host' and 'service' table but there is no relations - # For 'meta' module: in 'host' and 'meta_service_relation' (we can't purge) - if ($host_register == 2) { - return (0, $host_id, undef); - } - - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM service, host_service_relation hsr WHERE hsr.host_host_id = '" . $host_id . "' AND hsr.service_service_id = service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN ('1', '3') LIMIT 1"); - return -1 if ($status == -1); - $data = $stmt->fetchrow_hashref(); - if (!defined($data)) { - # Search in service By hostgroup - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM hostgroup_relation hgr, service, host_service_relation hsr WHERE hgr.host_host_id = '" . $host_id . "' AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id AND service_id = hsr.service_service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN ('1', '3') LIMIT 1"); - return -1 if ($status == -1); - $data = $stmt->fetchrow_hashref(); - } - - if (!defined($data)) { - $self->{'logger'}->writeLogError("Can't find 'service_id' for $host_name/$service_description"); - return -1; - } - - $service_id = $data->{'service_id'}; - return (0, $host_id, $service_id); + my $self = shift; + my ($host_name, $service_description) = @_; + my ($host_id, $service_id); + my ($status, $stmt, $data); + my $host_register = 1; + + # For Modules + if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { + $host_register = 2; + } + # Get Host_Id + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT `host_id` FROM `host` WHERE `host_name` = " . $self->{'dbcentreon'}->quote($host_name) . " AND `host_register` = '$host_register' LIMIT 1"); + return -1 if ($status); + $data = $stmt->fetchrow_hashref(); + if (!defined($data)) { + $self->{'logger'}->writeLogError("Can't find 'host_id' $host_name"); + return -1; + } + + $host_id = $data->{'host_id'}; + # For 'BAM' module: in 'host' and 'service' table but there is no relations + # For 'meta' module: in 'host' and 'meta_service_relation' (we can't purge) + if ($host_register == 2) { + return (0, $host_id, undef); + } + + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM service, host_service_relation hsr WHERE hsr.host_host_id = '" . $host_id . "' AND hsr.service_service_id = service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN ('1', '3') LIMIT 1"); + return -1 if ($status == -1); + $data = $stmt->fetchrow_hashref(); + if (!defined($data)) { + # Search in service By hostgroup + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM hostgroup_relation hgr, service, host_service_relation hsr WHERE hgr.host_host_id = '" . $host_id . "' AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id AND service_id = hsr.service_service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN ('1', '3') LIMIT 1"); + return -1 if ($status == -1); + $data = $stmt->fetchrow_hashref(); + } + + if (!defined($data)) { + $self->{'logger'}->writeLogError("Can't find 'service_id' for $host_name/$service_description"); + return -1; + } + + $service_id = $data->{'service_id'}; + return (0, $host_id, $service_id); } sub get_check_interval_normal { - my $self = shift; - my $service_id = shift; - my $rotation_check = shift; - - if (!defined($service_id)) { - return (0, 5); - } - $rotation_check = {} if (!defined($rotation_check)); - return (0, 5) if (defined($rotation_check->{$service_id})); - - my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_normal_check_interval, service_template_model_stm_id FROM service WHERE service_id = " . $service_id); - return -1 if ($status == -1); - my $data = $stmt->fetchrow_hashref(); - return (0, 5) if (!defined($data)); - - if (!defined($data->{'service_normal_check_interval'}) || $data->{'service_normal_check_interval'} eq '') { - $rotation_check->{$service_id} = 1; - $self->get_check_interval_normal($data->{'service_template_model_stm_id'}, $rotation_check); - } else { - return (0, $data->{'service_normal_check_interval'}); - } + my $self = shift; + my $service_id = shift; + my $rotation_check = shift; + + if (!defined($service_id)) { + return (0, 5); + } + $rotation_check = {} if (!defined($rotation_check)); + return (0, 5) if (defined($rotation_check->{$service_id})); + + my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_normal_check_interval, service_template_model_stm_id FROM service WHERE service_id = " . $service_id); + return -1 if ($status == -1); + my $data = $stmt->fetchrow_hashref(); + return (0, 5) if (!defined($data)); + + if (!defined($data->{'service_normal_check_interval'}) || $data->{'service_normal_check_interval'} eq '') { + $rotation_check->{$service_id} = 1; + $self->get_check_interval_normal($data->{'service_template_model_stm_id'}, $rotation_check); + } else { + return (0, $data->{'service_normal_check_interval'}); + } } sub get_check_interval_module { - my $self = shift; - my ($host_name, $service_description) = @_; - - my $interval = 1; - $service_description =~ /([a-zA-Z0-9]*)_([0-9]*)/; - if ($1 eq "meta"){ - my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT normal_check_interval FROM meta_service WHERE meta_id = '" . $2 . "' LIMIT 1"); - return -1 if ($status == -1); - my $data = $stmt->fetchrow_hashref(); - if (defined($data->{'normal_check_interval'})){ - $interval = $data->{'normal_check_interval'}; - } - } elsif ($1 eq "ba") { - my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT normal_check_interval FROM mod_bam WHERE ba_id = '" . $2 . "' LIMIT 1"); - return -1 if ($status == -1); - my $data = $stmt->fetchrow_hashref(); - if (defined($data->{'normal_check_interval'})) { - $interval = $data->{'normal_check_interval'}; - } - } - return (0, $interval); + my $self = shift; + my ($host_name, $service_description) = @_; + + my $interval = 1; + $service_description =~ /([a-zA-Z0-9]*)_([0-9]*)/; + if ($1 eq "meta"){ + my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT normal_check_interval FROM meta_service WHERE meta_id = '" . $2 . "' LIMIT 1"); + return -1 if ($status == -1); + my $data = $stmt->fetchrow_hashref(); + if (defined($data->{'normal_check_interval'})){ + $interval = $data->{'normal_check_interval'}; + } + } elsif ($1 eq "ba") { + my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT normal_check_interval FROM mod_bam WHERE ba_id = '" . $2 . "' LIMIT 1"); + return -1 if ($status == -1); + my $data = $stmt->fetchrow_hashref(); + if (defined($data->{'normal_check_interval'})) { + $interval = $data->{'normal_check_interval'}; + } + } + return (0, $interval); } sub get_check_interval { - my $self = shift; - my ($host_name, $service_description, $service_id) = @_; - - if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { - return $self->get_check_interval_module($host_name, $service_description); - } else { - return $self->get_check_interval_normal($service_id); - } + my $self = shift; + my ($host_name, $service_description, $service_id) = @_; + + if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { + return $self->get_check_interval_module($host_name, $service_description); + } else { + return $self->get_check_interval_normal($service_id); + } } ########################### sub get_information_service { - my $self = shift; - my ($key_service, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $no_cache) = @_; - - # Need to identify it - my ($status, $host_id, $service_id) = $self->get_host_service_ids($host_name, $service_description); - if ($status != 0) { - if (!defined($no_cache) || $no_cache == 0) { - push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; - } - return 1; - } - - # Get Interval - ($status, my $interval) = $self->get_check_interval($host_name, $service_description, $service_id); - if ($status != 0) { - if (!defined($no_cache) || $no_cache == 0) { - push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; - } - return 1; - } - - # Create It - $status = $self->create_service($host_id, $service_id, $interval * $self->{"interval_time"}, $host_name, $service_description); - if ($status != 0) { - if ($status == -1 && (!defined($no_cache) || $no_cache == 0)) { - push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; - } - if ($status == -2 && (!defined($no_cache) || $no_cache == 0)) { - push @{$self->{"cache_services_rename"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; - } - return 1; - } - - return 0; + my $self = shift; + my ($key_service, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $no_cache) = @_; + + # Need to identify it + my ($status, $host_id, $service_id) = $self->get_host_service_ids($host_name, $service_description); + if ($status != 0) { + if (!defined($no_cache) || $no_cache == 0) { + push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + } + return 1; + } + + # Get Interval + ($status, my $interval) = $self->get_check_interval($host_name, $service_description, $service_id); + if ($status != 0) { + if (!defined($no_cache) || $no_cache == 0) { + push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + } + return 1; + } + + # Create It + $status = $self->create_service($host_id, $service_id, $interval * $self->{"interval_time"}, $host_name, $service_description); + if ($status != 0) { + if ($status == -1 && (!defined($no_cache) || $no_cache == 0)) { + push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + } + if ($status == -2 && (!defined($no_cache) || $no_cache == 0)) { + push @{$self->{"cache_services_rename"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + } + return 1; + } + + return 0; } sub update { - my $self = shift; - my ($play_failed, $timestamp, $host_name, $service_description, $last_service_state, $service_state); - ($play_failed, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}) = @_; - - if ($timestamp !~ /^[0-9]+$/ || $timestamp > (time() + 86400)) { - $self->{'logger'}->writeLogError("Unknown timestamp format or in future: $timestamp"); - return 0; - } - # Not good number field - if (!defined($service_state)) { - $self->{'logger'}->writeLogError("Line not well formed"); - return 0; - } - - my $key_service = $host_name . ";" . $service_description; - # We quit because we have failed to retest before || rebuild - if ((defined($self->{"cache_services_failed"}->{$key_service}) && $play_failed == 0) || - defined($self->{"cache_service"}->{$key_service}) && $self->{"cache_service"}->{$key_service}->{'rebuild'} == 1) { - push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; - return 1; - } - # We quit because we wait rename finish - if (defined($self->{"cache_services_rename"}->{$key_service}) && $play_failed == 0) { - push @{$self->{"cache_services_rename"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; - return 1; - } - - - if (!defined($self->{"cache_service"}->{$key_service})) { - my $status = $self->get_information_service($key_service, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $play_failed); - return 1 if ($status == 1); - } + my $self = shift; + my ($play_failed, $timestamp, $host_name, $service_description, $last_service_state, $service_state); + ($play_failed, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}) = @_; + + if ($timestamp !~ /^[0-9]+$/ || $timestamp > (time() + 86400)) { + $self->{'logger'}->writeLogError("Unknown timestamp format or in future: $timestamp"); + return 0; + } + # Not good number field + if (!defined($service_state)) { + $self->{'logger'}->writeLogError("Line not well formed"); + return 0; + } + + my $key_service = $host_name . ";" . $service_description; + # We quit because we have failed to retest before || rebuild + if ((defined($self->{"cache_services_failed"}->{$key_service}) && $play_failed == 0) || + defined($self->{"cache_service"}->{$key_service}) && $self->{"cache_service"}->{$key_service}->{'rebuild'} == 1) { + push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + return 1; + } + # We quit because we wait rename finish + if (defined($self->{"cache_services_rename"}->{$key_service}) && $play_failed == 0) { + push @{$self->{"cache_services_rename"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + return 1; + } + + + if (!defined($self->{"cache_service"}->{$key_service})) { + my $status = $self->get_information_service($key_service, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $play_failed); + return 1 if ($status == 1); + } $self->init_perfdata(); - while (($self->get_perfdata())) { - if (!defined($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}})) { - # Need to identify metrics - # if failed, we go 'next' - my $status = $self->create_metric($self->{"cache_service"}->{$key_service}->{'index_id'}, \$self->{"cache_service"}->{$key_service}->{'metrics'}, $self->{"metric_name"}); - next if ($status == -1); - } - - $self->check_update_extra_metric(\$self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}); - - ### - # Check data source type: DB - ### - if ($self->{"cache_service"}->{$key_service}->{'storage_type'} == 2) { - # Do DataBin Add - $self->add_data_mysql($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'metric_id'}, - $timestamp, - $self->{"metric_value"}); - } - - ### - # Do RRDs: metric - ### - $self->{"rrd"}->add_metric($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'metric_id'}, - $self->{"metric_name"}, - $self->{"cache_service"}->{$key_service}->{'check_interval'}, - $self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'data_source_type'}, - $timestamp, - $self->{"metric_value"}, - $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); - } - - ### - # Do RRD Status - ### - if ($self->{"do_rrd_status"} == 1) { - $self->{"rrd"}->add_status($self->{"cache_service"}->{$key_service}->{'index_id'}, - $self->{"cache_service"}->{$key_service}->{'check_interval'}, - $timestamp, - $service_state, - $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); - } - - return 0; + while (($self->get_perfdata())) { + if (!defined($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}})) { + # Need to identify metrics + # if failed, we go 'next' + my $status = $self->create_metric($self->{"cache_service"}->{$key_service}->{'index_id'}, \$self->{"cache_service"}->{$key_service}->{'metrics'}, $self->{"metric_name"}); + next if ($status == -1); + } + + $self->check_update_extra_metric(\$self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}); + + ### + # Check data source type: DB + ### + if ($self->{"cache_service"}->{$key_service}->{'storage_type'} == 2) { + # Do DataBin Add + $self->add_data_mysql($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'metric_id'}, + $timestamp, + $self->{"metric_value"}); + } + + ### + # Do RRDs: metric + ### + $self->{"rrd"}->add_metric($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'metric_id'}, + $self->{"metric_name"}, + $self->{"cache_service"}->{$key_service}->{'check_interval'}, + $self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'data_source_type'}, + $timestamp, + $self->{"metric_value"}, + $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); + } + + ### + # Do RRD Status + ### + if ($self->{"do_rrd_status"} == 1) { + $self->{"rrd"}->add_status($self->{"cache_service"}->{$key_service}->{'index_id'}, + $self->{"cache_service"}->{$key_service}->{'check_interval'}, + $timestamp, + $service_state, + $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); + } + + return 0; } sub rebuild_finish { - my $self = shift; - - $self->{"rebuild_progress"} = 0; - if (defined($self->{"cache_service"}->{$self->{"rebuild_key"}})) { - $self->{"cache_service"}->{$self->{"rebuild_key"}}->{'rebuild'} = 0; - } - my $fh = $self->{'pipe_write'}; - print $fh "REBUILDFINISH\n"; + my $self = shift; + + $self->{"rebuild_progress"} = 0; + if (defined($self->{"cache_service"}->{$self->{"rebuild_key"}})) { + $self->{"cache_service"}->{$self->{"rebuild_key"}}->{'rebuild'} = 0; + } + my $fh = $self->{'pipe_write'}; + print $fh "REBUILDFINISH\n"; } sub rebuild { - my $self = shift; - my ($host_name, $service_description) = @_; - my $status; - my $current_interval; - - $self->{"rebuild_progress"} = 1; - if (!defined($host_name)) { - # A rebuild is in progress - return 0; - } - - my $key_service = $host_name . ";" . $service_description; - $self->{"rebuild_key"} = $key_service; - - ###### - # To do the rebuild - # Force flush data_bin - $self->flush_mysql(1); - - ###### - # Maybe we have to create cache service and metrics - # We'll get information for rebuild fork - # - if (!defined($self->{"cache_service"}->{$key_service})) { - $status = $self->get_information_service($key_service, undef, $host_name, $service_description, undef, undef, 1); - if ($status == 1) { - $self->{'logger'}->writeLogError("rebuild cannot get information service"); - $self->rebuild_finish(); - return ; - } - } else { - ###### - # Update Interval - # - ($status, $current_interval) = $self->get_check_interval($host_name, $service_description, $self->{"cache_service"}->{$key_service}->{'service_id'}); - if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot get interval service"); - $self->rebuild_finish(); - return ; - } - $self->{"cache_service"}->{$key_service}->{'check_interval'} = $current_interval * $self->{"interval_time"}; - - ##### - # Update cache to get 'rrd_retention' - ($status) = $self->cache_update_service_index_data($key_service); - if ($status == -1) { - $self->rebuild_finish(); - return ; - } - } - $self->{"cache_service"}->{$key_service}->{'rebuild'} = 1; - - ###### - # Get List Metrics and Flush if needed - # - ($status, my $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id, data_source_type FROM metrics WHERE index_id = " . $self->{"cache_service"}->{$key_service}->{'index_id'}); - if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot get metrics list"); - $self->rebuild_finish(); - return ; - } - while ((my $data = $stmt->fetchrow_hashref())) { - $self->{"rrd"}->delete_cache_metric($data->{'metric_id'}); - # Update cache - $self->{"cache_service"}->{$key_service}->{'metrics'}->{'data_source_type'} = $data->{'data_source_type'}; - } - - ###### - # Fork and launch rebuild (we'll rebuild each metric) - # - $self->{"rebuild_index_id"} = $self->{"cache_service"}->{$key_service}->{'index_id'}; - my $rebuild_index_id = $self->{"rebuild_index_id"}; - - $self->{"current_pid"} = fork(); + my $self = shift; + my ($host_name, $service_description) = @_; + my $status; + my $current_interval; + + $self->{"rebuild_progress"} = 1; + if (!defined($host_name)) { + # A rebuild is in progress + return 0; + } + + my $key_service = $host_name . ";" . $service_description; + $self->{"rebuild_key"} = $key_service; + + ###### + # To do the rebuild + # Force flush data_bin + $self->flush_mysql(1); + + ###### + # Maybe we have to create cache service and metrics + # We'll get information for rebuild fork + # + if (!defined($self->{"cache_service"}->{$key_service})) { + $status = $self->get_information_service($key_service, undef, $host_name, $service_description, undef, undef, 1); + if ($status == 1) { + $self->{'logger'}->writeLogError("rebuild cannot get information service"); + $self->rebuild_finish(); + return ; + } + } else { + ###### + # Update Interval + # + ($status, $current_interval) = $self->get_check_interval($host_name, $service_description, $self->{"cache_service"}->{$key_service}->{'service_id'}); + if ($status == -1) { + $self->{'logger'}->writeLogError("rebuild cannot get interval service"); + $self->rebuild_finish(); + return ; + } + $self->{"cache_service"}->{$key_service}->{'check_interval'} = $current_interval * $self->{"interval_time"}; + + ##### + # Update cache to get 'rrd_retention' + ($status) = $self->cache_update_service_index_data($key_service); + if ($status == -1) { + $self->rebuild_finish(); + return ; + } + } + $self->{"cache_service"}->{$key_service}->{'rebuild'} = 1; + + ###### + # Get List Metrics and Flush if needed + # + ($status, my $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id, data_source_type FROM metrics WHERE index_id = " . $self->{"cache_service"}->{$key_service}->{'index_id'}); + if ($status == -1) { + $self->{'logger'}->writeLogError("rebuild cannot get metrics list"); + $self->rebuild_finish(); + return ; + } + while ((my $data = $stmt->fetchrow_hashref())) { + $self->{"rrd"}->delete_cache_metric($data->{'metric_id'}); + # Update cache + $self->{"cache_service"}->{$key_service}->{'metrics'}->{'data_source_type'} = $data->{'data_source_type'}; + } + + ###### + # Fork and launch rebuild (we'll rebuild each metric) + # + $self->{"rebuild_index_id"} = $self->{"cache_service"}->{$key_service}->{'index_id'}; + my $rebuild_index_id = $self->{"rebuild_index_id"}; + + $self->{"current_pid"} = fork(); if (!defined($self->{"current_pid"})) { - $self->{'logger'}->writeLogError("rebuild cannot fork: $!"); - $self->rebuild_finish(); - } elsif (!$self->{"current_pid"}) { - $self->{'dbcentstorage'}->set_inactive_destroy(); - $self->{'dbcentreon'}->set_inactive_destroy(); + $self->{'logger'}->writeLogError("rebuild cannot fork: $!"); + $self->rebuild_finish(); + } elsif (!$self->{"current_pid"}) { + $self->{'dbcentstorage'}->set_inactive_destroy(); + $self->{'dbcentreon'}->set_inactive_destroy(); - my $centreon_db_centstorage = centreon::db(logger => $self->{'logger'}, db => $self->{'dbcentstorage'}->db(), host => $self->{'dbcentstorage'}->host(), + my $centreon_db_centstorage = centreon::db(logger => $self->{'logger'}, db => $self->{'dbcentstorage'}->db(), host => $self->{'dbcentstorage'}->host(), user => $self->{'dbcentstorage'}->user(), password => $self->{'dbcentstorage'}->password(), "port" => $self->{'dbcentstorage'}->port(), force => 0); - $status = $centreon_db_centstorage->connect(); - exit 1 if ($status == -1); - my $centstorage_rebuild = centstorage::CentstorageRebuild->new($self->{'logger'}); - $status = $centstorage_rebuild->main($centreon_db_centstorage, $rebuild_index_id, $self->{"cache_service"}->{$key_service}->{'check_interval'}, $self->{'rrd'}, $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); - $centreon_db_centstorage->disconnect(); - exit $status; - } - if ($self->{"current_pid"} == -1) { - $self->{"current_pid"} = undef; - } + $status = $centreon_db_centstorage->connect(); + exit 1 if ($status == -1); + my $centstorage_rebuild = centstorage::CentstorageRebuild->new($self->{'logger'}); + $status = $centstorage_rebuild->main($centreon_db_centstorage, $rebuild_index_id, $self->{"cache_service"}->{$key_service}->{'check_interval'}, $self->{'rrd'}, $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); + $centreon_db_centstorage->disconnect(); + exit $status; + } + if ($self->{"current_pid"} == -1) { + $self->{"current_pid"} = undef; + } } sub rename_finish { - my $self = shift; - my ($host_name, $service_description) = @_; - - if (defined($self->{"cache_services_rename"}->{$host_name . ";" . $service_description})) { - $self->{'logger'}->writeLogInfo("rename finish received $host_name/$service_description"); - my @tmp_ar = (); - my $lerror = 0; - foreach (@{$self->{"cache_services_rename"}->{$host_name . ";" . $service_description}}) { - if ($lerror == 0 && $self->update(1, @$_) != 0) { - push @tmp_ar, \@$_; - $lerror = 1; - } else { - push @tmp_ar, \@$_; - } - } - if (scalar(@tmp_ar) != 0) { - @{$self->{"cache_services_failed"}->{$host_name . ";" . $service_description}} = @tmp_ar; - } + my $self = shift; + my ($host_name, $service_description) = @_; + + if (defined($self->{"cache_services_rename"}->{$host_name . ";" . $service_description})) { + $self->{'logger'}->writeLogInfo("rename finish received $host_name/$service_description"); + my @tmp_ar = (); + my $lerror = 0; + foreach (@{$self->{"cache_services_rename"}->{$host_name . ";" . $service_description}}) { + if ($lerror == 0 && $self->update(1, @$_) != 0) { + push @tmp_ar, \@$_; + $lerror = 1; + } else { + push @tmp_ar, \@$_; + } + } + if (scalar(@tmp_ar) != 0) { + @{$self->{"cache_services_failed"}->{$host_name . ";" . $service_description}} = @tmp_ar; + } $self->{'logger'}->writeLogInfo("rename finish $host_name/$service_description ok"); - delete $self->{"cache_services_rename"}->{$host_name . ";" . $service_description}; - } + delete $self->{"cache_services_rename"}->{$host_name . ";" . $service_description}; + } } sub send_rename_finish { - my $self = shift; - my ($host_name, $service_description) = @_; - - $self->{"rename_rebuild_wait"} = 0; + my $self = shift; + my ($host_name, $service_description) = @_; + + $self->{"rename_rebuild_wait"} = 0; my $fh = $self->{'pipe_write'}; print $fh "RENAMEFINISH\t$host_name\t$service_description\n"; } sub rename_clean { - my $self = shift; - my ($host_name, $service_description, $new_host_name, $new_service_description) = @_; - my $key = $host_name . ";" . $service_description; - - $self->{'logger'}->writeLogInfo("rename clean received $host_name/$service_description"); - $self->{"rename_old_new"}->{$key} = $new_host_name . ";" . $new_service_description; - if ($self->{"rebuild_progress"} == 1 && $self->{"rebuild_key"} eq $key) { - $self->{"rename_rebuild_wait"} = 1; - $self->{'logger'}->writeLogInfo("Wait rebuild finish..."); - return ; - } - - # Do RRD flush - $self->force_flush_rrd($key); - delete $self->{"cache_service"}->{$key}; - delete $self->{"cache_services_failed"}->{$key}; - delete $self->{"rename_old_new"}->{$key}; - $self->send_rename_finish($new_host_name, $new_service_description); + my $self = shift; + my ($host_name, $service_description, $new_host_name, $new_service_description) = @_; + my $key = $host_name . ";" . $service_description; + + $self->{'logger'}->writeLogInfo("rename clean received $host_name/$service_description"); + $self->{"rename_old_new"}->{$key} = $new_host_name . ";" . $new_service_description; + if ($self->{"rebuild_progress"} == 1 && $self->{"rebuild_key"} eq $key) { + $self->{"rename_rebuild_wait"} = 1; + $self->{'logger'}->writeLogInfo("Wait rebuild finish..."); + return ; + } + + # Do RRD flush + $self->force_flush_rrd($key); + delete $self->{"cache_service"}->{$key}; + delete $self->{"cache_services_failed"}->{$key}; + delete $self->{"rename_old_new"}->{$key}; + $self->send_rename_finish($new_host_name, $new_service_description); } sub delete_clean { - my $self = shift; - my ($host_name, $service_description, $metric_name) = @_; - my $key = $host_name . ";" . $service_description; - - if (defined($metric_name)) { - $self->{'rrd'}->delete_cache_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$metric_name}->{'metric_id'}); - delete $self->{"cache_service"}->{$key}->{'metrics'}->{$metric_name}; - } else { - foreach (keys %{$self->{"cache_service"}->{$key}->{'metrics'}}) { - $self->{'rrd'}->delete_cache_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$_}->{'metric_id'}); - } - $self->{'rrd'}->delete_cache_status($self->{"cache_service"}->{$key}->{'index_id'}); - delete $self->{"cache_service"}->{$key}; - delete $self->{"cache_services_failed"}->{$key}; - } + my $self = shift; + my ($host_name, $service_description, $metric_name) = @_; + my $key = $host_name . ";" . $service_description; + + if (defined($metric_name)) { + $self->{'rrd'}->delete_cache_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$metric_name}->{'metric_id'}); + delete $self->{"cache_service"}->{$key}->{'metrics'}->{$metric_name}; + } else { + foreach (keys %{$self->{"cache_service"}->{$key}->{'metrics'}}) { + $self->{'rrd'}->delete_cache_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$_}->{'metric_id'}); + } + $self->{'rrd'}->delete_cache_status($self->{"cache_service"}->{$key}->{'index_id'}); + delete $self->{"cache_service"}->{$key}; + delete $self->{"cache_services_failed"}->{$key}; + } } sub main { - my $self = shift; - my ($dbcentreon, $dbcentstorage, $pipe_read, $pipe_write, $num_pool, $rrd_cache_mode, $rrd_flush_time, $perfdata_parser_stop) = @_; - my $status; - - $self->{'dbcentreon'} = $dbcentreon; - $self->{'dbcentstorage'} = $dbcentstorage; - $self->{'num_pool'} = $num_pool; - $self->{'perfdata_parser_stop'} = $perfdata_parser_stop if (defined($perfdata_parser_stop)); - - ($status, $self->{"main_perfdata_file"}) = centstorage::CentstorageLib::get_main_perfdata_file($self->{'dbcentreon'}); - ($status, $self->{"len_storage_rrd"}, $self->{"rrd_metrics_path"}, $self->{"rrd_status_path"}, $self->{"storage_type"}) = $self->get_centstorage_information(); - ($status, $self->{"interval_time"}) = $self->get_centreon_intervaltime(); - $self->{"rrd"}->metric_path($self->{"rrd_metrics_path"}); - $self->{"rrd"}->status_path($self->{"rrd_status_path"}); - $self->{"rrd"}->len_rrd($self->{"len_storage_rrd"}); - $self->{"rrd"}->cache_mode($rrd_cache_mode); - $self->{"rrd"}->flush($rrd_flush_time); - - # We have to manage if you don't need infos - $self->{'dbcentreon'}->force(0); - $self->{'dbcentstorage'}->force(0); - - $self->{'pipe_write'} = $pipe_write; - $self->{'read_select'} = new IO::Select(); - $self->{'read_select'}->add($pipe_read); - while (1) { - my @rh_set = $self->{'read_select'}->can_read(10); - if (scalar(@rh_set) == 0) { - $self->flush_mysql(); - $self->{"rrd"}->flush_all(); - $self->flush_failed(); - } - foreach my $rh (@rh_set) { - my $read_done = 0; - while ((my ($status_line, $readline) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { - class_handle_TERM() if ($status_line == -1); - last if ($status_line == 0); - my ($method, @fields) = split(/\t/, $readline); - - # Check Type - if (defined($method) && $method eq "UPDATE") { - $self->update(0, @fields); - } elsif (defined($method) && $method eq "REBUILDBEGIN") { - $self->rebuild(@fields); - } elsif (defined($method) && $method eq "REBUILDFINISH") { - $self->{"rebuild_progress"} = 0; - } elsif (defined($method) && $method eq "RENAMEFINISH") { - $self->rename_finish(@fields); - } elsif (defined($method) && $method eq "RENAMECLEAN") { - $self->rename_clean(@fields); - } elsif (defined($method) && $method eq "DELETECLEAN") { - $self->delete_clean(@fields); - } - - $self->flush_mysql(); - $self->{"rrd"}->flush_all(); - } - } - $self->flush_failed(); - } + my $self = shift; + my ($dbcentreon, $dbcentstorage, $pipe_read, $pipe_write, $num_pool, $rrd_cache_mode, $rrd_flush_time, $perfdata_parser_stop) = @_; + my $status; + + $self->{'dbcentreon'} = $dbcentreon; + $self->{'dbcentstorage'} = $dbcentstorage; + $self->{'num_pool'} = $num_pool; + $self->{'perfdata_parser_stop'} = $perfdata_parser_stop if (defined($perfdata_parser_stop)); + + ($status, $self->{"main_perfdata_file"}) = centstorage::CentstorageLib::get_main_perfdata_file($self->{'dbcentreon'}); + ($status, $self->{"len_storage_rrd"}, $self->{"rrd_metrics_path"}, $self->{"rrd_status_path"}, $self->{"storage_type"}) = $self->get_centstorage_information(); + ($status, $self->{"interval_time"}) = $self->get_centreon_intervaltime(); + $self->{"rrd"}->metric_path($self->{"rrd_metrics_path"}); + $self->{"rrd"}->status_path($self->{"rrd_status_path"}); + $self->{"rrd"}->len_rrd($self->{"len_storage_rrd"}); + $self->{"rrd"}->cache_mode($rrd_cache_mode); + $self->{"rrd"}->flush($rrd_flush_time); + + # We have to manage if you don't need infos + $self->{'dbcentreon'}->force(0); + $self->{'dbcentstorage'}->force(0); + + $self->{'pipe_write'} = $pipe_write; + $self->{'read_select'} = new IO::Select(); + $self->{'read_select'}->add($pipe_read); + while (1) { + my @rh_set = $self->{'read_select'}->can_read(10); + if (scalar(@rh_set) == 0) { + $self->flush_mysql(); + $self->{"rrd"}->flush_all(); + $self->flush_failed(); + } + foreach my $rh (@rh_set) { + my $read_done = 0; + while ((my ($status_line, $readline) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + class_handle_TERM() if ($status_line == -1); + last if ($status_line == 0); + my ($method, @fields) = split(/\t/, $readline); + + # Check Type + if (defined($method) && $method eq "UPDATE") { + $self->update(0, @fields); + } elsif (defined($method) && $method eq "REBUILDBEGIN") { + $self->rebuild(@fields); + } elsif (defined($method) && $method eq "REBUILDFINISH") { + $self->{"rebuild_progress"} = 0; + } elsif (defined($method) && $method eq "RENAMEFINISH") { + $self->rename_finish(@fields); + } elsif (defined($method) && $method eq "RENAMECLEAN") { + $self->rename_clean(@fields); + } elsif (defined($method) && $method eq "DELETECLEAN") { + $self->delete_clean(@fields); + } + + $self->flush_mysql(); + $self->{"rrd"}->flush_all(); + } + } + $self->flush_failed(); + } } 1; diff --git a/centreon/lib/perl/centstorage/CentstorageRRD.pm b/centreon/lib/perl/centstorage/CentstorageRRD.pm index 970ffc3a3ff..92246197038 100644 --- a/centreon/lib/perl/centstorage/CentstorageRRD.pm +++ b/centreon/lib/perl/centstorage/CentstorageRRD.pm @@ -8,358 +8,358 @@ package centstorage::CentstorageRRD; my @rrd_dst = ("GAUGE","COUNTER","DERIVE","ABSOLUTE"); sub new { - my $class = shift; - my $self = {}; - $self->{"logger"} = shift; - $self->{"metric_path"} = undef; - $self->{"status_path"} = undef; - $self->{"len_rrd"} = undef; - $self->{"status_info"} = {}; - $self->{"metric_info"} = {}; - # By metric_id - $self->{"rrdcache_metric_data"} = {}; - $self->{"rrdcache_status_data"} = {}; - # Flush every n seconds: -1 = disable - $self->{"last_flush"} = time(); - $self->{"flush"} = -1; - $self->{"cache_mode"} = 0; - bless $self, $class; - return $self; + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"metric_path"} = undef; + $self->{"status_path"} = undef; + $self->{"len_rrd"} = undef; + $self->{"status_info"} = {}; + $self->{"metric_info"} = {}; + # By metric_id + $self->{"rrdcache_metric_data"} = {}; + $self->{"rrdcache_status_data"} = {}; + # Flush every n seconds: -1 = disable + $self->{"last_flush"} = time(); + $self->{"flush"} = -1; + $self->{"cache_mode"} = 0; + bless $self, $class; + return $self; } sub get_ds_name { - my $self = shift; - - $_[0] =~ s/\//slash\_/g; - $_[0] =~ s/\\/bslash\_/g; - $_[0] =~ s/\%/pct\_/g; - $_[0] =~ s/\#S\#/slash\_/g; - $_[0] =~ s/\#BS\#/bslash\_/g; - $_[0] =~ s/\#P\#/pct\_/g; - $_[0] =~ s/[^0-9_\-a-zA-Z]/-/g; - return $_[0]; + my $self = shift; + + $_[0] =~ s/\//slash\_/g; + $_[0] =~ s/\\/bslash\_/g; + $_[0] =~ s/\%/pct\_/g; + $_[0] =~ s/\#S\#/slash\_/g; + $_[0] =~ s/\#BS\#/bslash\_/g; + $_[0] =~ s/\#P\#/pct\_/g; + $_[0] =~ s/[^0-9_\-a-zA-Z]/-/g; + return $_[0]; } sub create_rrd_database { - my $self = shift; - my ($RRDdatabase_path, $metric_id, $begin, $interval, $metric_name, $my_len_storage_rrd, $data_source_type) = @_; - - my $lsource_type; - if (defined($data_source_type) && defined()) { - $lsource_type = $rrd_dst[$data_source_type]; - } else { - $lsource_type = $rrd_dst[0]; - } - RRDs::create($RRDdatabase_path . "/" . $metric_id . ".rrd", "-b ".$begin, "-s ".$interval, "DS:" . substr($metric_name, 0, 19) . ":" . $lsource_type . ":".$interval.":U:U", "RRA:AVERAGE:0.5:1:".$my_len_storage_rrd, "RRA:AVERAGE:0.5:12:".($my_len_storage_rrd / 12)); - my $ERR = RRDs::error; - if ($ERR) { - $self->{'logger'}->writeLogError("ERROR while creating " . $RRDdatabase_path.$metric_id . ".rrd : $ERR"); - } else { - chmod 0664, "${RRDdatabase_path}/${metric_id}.rrd"; - } + my $self = shift; + my ($RRDdatabase_path, $metric_id, $begin, $interval, $metric_name, $my_len_storage_rrd, $data_source_type) = @_; + + my $lsource_type; + if (defined($data_source_type) && defined()) { + $lsource_type = $rrd_dst[$data_source_type]; + } else { + $lsource_type = $rrd_dst[0]; + } + RRDs::create($RRDdatabase_path . "/" . $metric_id . ".rrd", "-b ".$begin, "-s ".$interval, "DS:" . substr($metric_name, 0, 19) . ":" . $lsource_type . ":".$interval.":U:U", "RRA:AVERAGE:0.5:1:".$my_len_storage_rrd, "RRA:AVERAGE:0.5:12:".($my_len_storage_rrd / 12)); + my $ERR = RRDs::error; + if ($ERR) { + $self->{'logger'}->writeLogError("ERROR while creating " . $RRDdatabase_path.$metric_id . ".rrd : $ERR"); + } else { + chmod 0664, "${RRDdatabase_path}/${metric_id}.rrd"; + } } sub tune_rrd_database { - my $self = shift; - my ($RRDdatabase_path, $metric_id ,$metric_name, $interval_hb) = @_; - - RRDs::tune($RRDdatabase_path . "/" . $metric_id . ".rrd", "-h", substr($metric_name, 0, 19).":".$interval_hb); - my $ERR = RRDs::error; - if ($ERR) { - $self->{'logger'}->writeLogError("ERROR while tunning operation on " . $RRDdatabase_path.$metric_id . ".rrd : $ERR"); - } + my $self = shift; + my ($RRDdatabase_path, $metric_id ,$metric_name, $interval_hb) = @_; + + RRDs::tune($RRDdatabase_path . "/" . $metric_id . ".rrd", "-h", substr($metric_name, 0, 19).":".$interval_hb); + my $ERR = RRDs::error; + if ($ERR) { + $self->{'logger'}->writeLogError("ERROR while tunning operation on " . $RRDdatabase_path.$metric_id . ".rrd : $ERR"); + } } sub get_last_update { - my $self = shift; - my ($rrd_path_database, $id_db) = @_; - my $last_time = -1; - - if (-e $rrd_path_database . '/' . $id_db . '.rrd') { - $last_time = RRDs::last($rrd_path_database . '/' . $id_db . '.rrd'); - my $ERR = RRDs::error; - if ($ERR) { - $self->{'logger'}->writeLogError("ERROR while checking last time '" . $rrd_path_database . "/" . $id_db . ".rrd' $ERR"); - return -2; - } - } - return $last_time; + my $self = shift; + my ($rrd_path_database, $id_db) = @_; + my $last_time = -1; + + if (-e $rrd_path_database . '/' . $id_db . '.rrd') { + $last_time = RRDs::last($rrd_path_database . '/' . $id_db . '.rrd'); + my $ERR = RRDs::error; + if ($ERR) { + $self->{'logger'}->writeLogError("ERROR while checking last time '" . $rrd_path_database . "/" . $id_db . ".rrd' $ERR"); + return -2; + } + } + return $last_time; } sub metric_path { - my $self = shift; + my $self = shift; - if (@_) { - $self->{'metric_path'} = shift; - } - return $self->{'metric_path'}; + if (@_) { + $self->{'metric_path'} = shift; + } + return $self->{'metric_path'}; } sub status_path { - my $self = shift; + my $self = shift; - if (@_) { - $self->{'status_path'} = shift; - } - return $self->{'status_path'}; + if (@_) { + $self->{'status_path'} = shift; + } + return $self->{'status_path'}; } sub len_rrd { - my $self = shift; + my $self = shift; - if (@_) { - $self->{'len_rrd'} = shift() * 60 * 60 * 24; - } - return $self->{'len_rrd'}; + if (@_) { + $self->{'len_rrd'} = shift() * 60 * 60 * 24; + } + return $self->{'len_rrd'}; } sub flush { - my $self = shift; + my $self = shift; - if (@_) { - $self->{'flush'} = shift; - } - return $self->{'flush'}; + if (@_) { + $self->{'flush'} = shift; + } + return $self->{'flush'}; } sub cache_mode { - my $self = shift; + my $self = shift; - if (@_) { - $self->{'cache_mode'} = shift; - } - return $self->{'cache_mode'}; + if (@_) { + $self->{'cache_mode'} = shift; + } + return $self->{'cache_mode'}; } sub delete_rrd_metric { - my $self = shift; - my ($id) = @_; - - if (-e $self->{"metric_path"} . "/" . $id . ".rrd") { - if (!unlink($self->{"metric_path"} . "/" . $id . ".rrd")) { - $self->{'logger'}->writeLogError("Cannot delete rrd file " . $self->{"metric_path"} . "/" . $id . ".rrd"); - return -1; - } - } - return 0; + my $self = shift; + my ($id) = @_; + + if (-e $self->{"metric_path"} . "/" . $id . ".rrd") { + if (!unlink($self->{"metric_path"} . "/" . $id . ".rrd")) { + $self->{'logger'}->writeLogError("Cannot delete rrd file " . $self->{"metric_path"} . "/" . $id . ".rrd"); + return -1; + } + } + return 0; } sub delete_cache_metric { - my $self = shift; - my ($metric_id) = @_; - - if (defined($self->{"metric_info"}->{$metric_id})) { - delete $self->{"metric_info"}->{$metric_id}; - } - if (defined($self->{"rrdcache_metric_data"}->{$metric_id})) { - delete $self->{"rrdcache_metric_data"}->{$metric_id}; - } + my $self = shift; + my ($metric_id) = @_; + + if (defined($self->{"metric_info"}->{$metric_id})) { + delete $self->{"metric_info"}->{$metric_id}; + } + if (defined($self->{"rrdcache_metric_data"}->{$metric_id})) { + delete $self->{"rrdcache_metric_data"}->{$metric_id}; + } } sub delete_cache_status { - my $self = shift; - my ($id) = @_; - - if (defined($self->{"status_info"}->{$id})) { - delete $self->{"status_info"}->{$id}; - } - if (defined($self->{"rrdcache_status_data"}->{$id})) { - delete $self->{"rrdcache_status_data"}->{$id}; - } + my $self = shift; + my ($id) = @_; + + if (defined($self->{"status_info"}->{$id})) { + delete $self->{"status_info"}->{$id}; + } + if (defined($self->{"rrdcache_status_data"}->{$id})) { + delete $self->{"rrdcache_status_data"}->{$id}; + } } sub add_metric { - my $self = shift; - my ($metric_id, $metric_name, $interval, $data_source_type, $timestamp, $value, $local_rrd_retention) = @_; - - if (!defined($self->{"metric_info"}->{$metric_id})) { - my $my_len_storage_rrd; - if ($local_rrd_retention == -1) { - $my_len_storage_rrd = $self->{"len_rrd"} / $interval; - } else { - $my_len_storage_rrd = $local_rrd_retention / $interval; - } - my $ltimestamp = $self->get_last_update($self->{"metric_path"}, $metric_id); - return if ($ltimestamp == -2); - $self->{"metric_info"}->{$metric_id} = {'metric_name' => $metric_name, - 'interval' => $interval, - 'data_source_type' => $data_source_type, - 'last_timestamp' => $ltimestamp, - 'len_rrd' => $my_len_storage_rrd}; - if ($self->{"metric_info"}->{$metric_id}->{'last_timestamp'} == -1) { - my $interval_hb = $interval * 10; - - $self->create_rrd_database($self->{"metric_path"}, $metric_id, $timestamp - 200, $interval, - $self->get_ds_name($metric_name), $my_len_storage_rrd, $data_source_type); - $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($metric_name), $interval_hb); - $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} = $timestamp - 200; - } - } - - return -1 if ($timestamp <= $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} || $timestamp > (time() + 7200)); - $self->{"rrdcache_metric_data"}->{$metric_id} = [] if (!defined($self->{"rrdcache_metric_data"}->{$metric_id})); - push @{$self->{"rrdcache_metric_data"}->{$metric_id}}, $timestamp . ":" . $value; - $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} = $timestamp; + my $self = shift; + my ($metric_id, $metric_name, $interval, $data_source_type, $timestamp, $value, $local_rrd_retention) = @_; + + if (!defined($self->{"metric_info"}->{$metric_id})) { + my $my_len_storage_rrd; + if ($local_rrd_retention == -1) { + $my_len_storage_rrd = $self->{"len_rrd"} / $interval; + } else { + $my_len_storage_rrd = $local_rrd_retention / $interval; + } + my $ltimestamp = $self->get_last_update($self->{"metric_path"}, $metric_id); + return if ($ltimestamp == -2); + $self->{"metric_info"}->{$metric_id} = {'metric_name' => $metric_name, + 'interval' => $interval, + 'data_source_type' => $data_source_type, + 'last_timestamp' => $ltimestamp, + 'len_rrd' => $my_len_storage_rrd}; + if ($self->{"metric_info"}->{$metric_id}->{'last_timestamp'} == -1) { + my $interval_hb = $interval * 10; + + $self->create_rrd_database($self->{"metric_path"}, $metric_id, $timestamp - 200, $interval, + $self->get_ds_name($metric_name), $my_len_storage_rrd, $data_source_type); + $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($metric_name), $interval_hb); + $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} = $timestamp - 200; + } + } + + return -1 if ($timestamp <= $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} || $timestamp > (time() + 7200)); + $self->{"rrdcache_metric_data"}->{$metric_id} = [] if (!defined($self->{"rrdcache_metric_data"}->{$metric_id})); + push @{$self->{"rrdcache_metric_data"}->{$metric_id}}, $timestamp . ":" . $value; + $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} = $timestamp; } sub add_status { - my $self = shift; - my ($index_id, $interval, $timestamp, $service_state, $local_rrd_retention) = @_; - my $value; - - if ($service_state eq 'OK') { - $value = 100; - } elsif ($service_state eq 'WARNING') { - $value = 75; - } elsif ($service_state eq 'CRITICAL') { - $value = 0; - } else { - # Don't do for 'UNKNOWN' - return ; - } - if (!defined($self->{'status_info'}->{$index_id})) { - my $my_len_storage_rrd; - if ($local_rrd_retention == -1) { - $my_len_storage_rrd = $self->{"len_rrd"} / $interval; - } else { - $my_len_storage_rrd = $local_rrd_retention / $interval; - } - my $ltimestamp = $self->get_last_update($self->{"status_path"}, $index_id); - return if ($ltimestamp == -2); - $self->{"status_info"}->{$index_id} = {'interval' => $interval, - 'last_timestamp' => $ltimestamp, - 'values' => [], - 'len_rrd' => $my_len_storage_rrd}; - if ($self->{"status_info"}->{$index_id}->{'last_timestamp'} == -1) { - my $interval_hb = $interval * 10; - - $self->create_rrd_database($self->{"status_path"}, $index_id, $timestamp - 200, $interval, - "status", $my_len_storage_rrd, 0); - $self->tune_rrd_database($self->{"status_path"}, $index_id, "status", $interval_hb); - $self->{"status_info"}->{$index_id}->{'last_timestamp'} = $timestamp - 200; - } - } - - return -1 if ($timestamp <= $self->{"status_info"}->{$index_id}->{'last_timestamp'} || $timestamp > (time() + 7200)); - $self->{"rrdcache_status_data"}->{$index_id} = [] if (!defined($self->{"rrdcache_status_data"}->{$index_id})); - push @{$self->{"rrdcache_status_data"}->{$index_id}}, $timestamp . ":" . $value; - $self->{"status_info"}->{$index_id}->{'last_timestamp'} = $timestamp; + my $self = shift; + my ($index_id, $interval, $timestamp, $service_state, $local_rrd_retention) = @_; + my $value; + + if ($service_state eq 'OK') { + $value = 100; + } elsif ($service_state eq 'WARNING') { + $value = 75; + } elsif ($service_state eq 'CRITICAL') { + $value = 0; + } else { + # Don't do for 'UNKNOWN' + return ; + } + if (!defined($self->{'status_info'}->{$index_id})) { + my $my_len_storage_rrd; + if ($local_rrd_retention == -1) { + $my_len_storage_rrd = $self->{"len_rrd"} / $interval; + } else { + $my_len_storage_rrd = $local_rrd_retention / $interval; + } + my $ltimestamp = $self->get_last_update($self->{"status_path"}, $index_id); + return if ($ltimestamp == -2); + $self->{"status_info"}->{$index_id} = {'interval' => $interval, + 'last_timestamp' => $ltimestamp, + 'values' => [], + 'len_rrd' => $my_len_storage_rrd}; + if ($self->{"status_info"}->{$index_id}->{'last_timestamp'} == -1) { + my $interval_hb = $interval * 10; + + $self->create_rrd_database($self->{"status_path"}, $index_id, $timestamp - 200, $interval, + "status", $my_len_storage_rrd, 0); + $self->tune_rrd_database($self->{"status_path"}, $index_id, "status", $interval_hb); + $self->{"status_info"}->{$index_id}->{'last_timestamp'} = $timestamp - 200; + } + } + + return -1 if ($timestamp <= $self->{"status_info"}->{$index_id}->{'last_timestamp'} || $timestamp > (time() + 7200)); + $self->{"rrdcache_status_data"}->{$index_id} = [] if (!defined($self->{"rrdcache_status_data"}->{$index_id})); + push @{$self->{"rrdcache_status_data"}->{$index_id}}, $timestamp . ":" . $value; + $self->{"status_info"}->{$index_id}->{'last_timestamp'} = $timestamp; } sub flush_metric { - my $self = shift; - my ($metric_id) = @_; - - if (defined($self->{"rrdcache_metric_data"}->{$metric_id})) { - RRDs::update($self->{"metric_path"} . "/" . $metric_id . ".rrd", @{$self->{"rrdcache_metric_data"}->{$metric_id}}); - my $ERR = RRDs::error; - if ($ERR) { - # Try to see if the file had been deleted - if (! -e $self->{"metric_path"} . "/" . $metric_id . ".rrd") { - my $my_len_storage_rrd = $self->{"metric_info"}->{$metric_id}->{'len_rrd'}; - my $interval_hb = $self->{"metric_info"}->{$metric_id}->{'interval'} * 10; - - $self->create_rrd_database($self->{"metric_path"}, $metric_id, - $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} - 200, - $self->{"metric_info"}->{$metric_id}->{'interval'}, - $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $my_len_storage_rrd, - $self->{"metric_info"}->{$metric_id}->{'data_source_type'}); - $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $interval_hb); - } else { - $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"metric_path"} . "/" . $metric_id . ".rrd' $ERR"); - } - } - delete $self->{"rrdcache_metric_data"}->{$metric_id}; - } + my $self = shift; + my ($metric_id) = @_; + + if (defined($self->{"rrdcache_metric_data"}->{$metric_id})) { + RRDs::update($self->{"metric_path"} . "/" . $metric_id . ".rrd", @{$self->{"rrdcache_metric_data"}->{$metric_id}}); + my $ERR = RRDs::error; + if ($ERR) { + # Try to see if the file had been deleted + if (! -e $self->{"metric_path"} . "/" . $metric_id . ".rrd") { + my $my_len_storage_rrd = $self->{"metric_info"}->{$metric_id}->{'len_rrd'}; + my $interval_hb = $self->{"metric_info"}->{$metric_id}->{'interval'} * 10; + + $self->create_rrd_database($self->{"metric_path"}, $metric_id, + $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} - 200, + $self->{"metric_info"}->{$metric_id}->{'interval'}, + $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $my_len_storage_rrd, + $self->{"metric_info"}->{$metric_id}->{'data_source_type'}); + $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $interval_hb); + } else { + $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"metric_path"} . "/" . $metric_id . ".rrd' $ERR"); + } + } + delete $self->{"rrdcache_metric_data"}->{$metric_id}; + } } sub flush_status { - my $self = shift; - my ($index_id) = @_; - - if (defined($self->{"rrdcache_status_data"}->{$index_id})) { - RRDs::update($self->{"status_path"} . "/" . $index_id . ".rrd", @{$self->{"rrdcache_status_data"}->{$index_id}}); - my $ERR = RRDs::error; - if ($ERR) { - # Try to see if the file had been deleted - if (! -e $self->{"status_path"} . "/" . $index_id . ".rrd") { - my $my_len_storage_rrd = $self->{"status_info"}->{$index_id}->{'len_rrd'}; - my $interval_hb = $self->{"status_info"}->{$index_id}->{'interval'} * 10; - - $self->create_rrd_database($self->{"status_path"}, $index_id, - $self->{"status_info"}->{$index_id}->{'last_timestamp'} - 200, - $self->{"status_info"}->{$index_id}->{'interval'}, - "status", $my_len_storage_rrd, - 0); - $self->tune_rrd_database($self->{"status_path"}, $index_id, "status", $interval_hb); - } else { - $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"status_path"} . "/" . $index_id . ".rrd' $ERR"); - } - } - delete $self->{"rrdcache_status_data"}->{$index_id}; - } + my $self = shift; + my ($index_id) = @_; + + if (defined($self->{"rrdcache_status_data"}->{$index_id})) { + RRDs::update($self->{"status_path"} . "/" . $index_id . ".rrd", @{$self->{"rrdcache_status_data"}->{$index_id}}); + my $ERR = RRDs::error; + if ($ERR) { + # Try to see if the file had been deleted + if (! -e $self->{"status_path"} . "/" . $index_id . ".rrd") { + my $my_len_storage_rrd = $self->{"status_info"}->{$index_id}->{'len_rrd'}; + my $interval_hb = $self->{"status_info"}->{$index_id}->{'interval'} * 10; + + $self->create_rrd_database($self->{"status_path"}, $index_id, + $self->{"status_info"}->{$index_id}->{'last_timestamp'} - 200, + $self->{"status_info"}->{$index_id}->{'interval'}, + "status", $my_len_storage_rrd, + 0); + $self->tune_rrd_database($self->{"status_path"}, $index_id, "status", $interval_hb); + } else { + $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"status_path"} . "/" . $index_id . ".rrd' $ERR"); + } + } + delete $self->{"rrdcache_status_data"}->{$index_id}; + } } sub flush_all { - my $self = shift; - my ($force) = @_; - - if ($self->{'cache_mode'} == 1 && (!defined($force) || $force == 0)) { - return if (time() < ($self->{'last_flush'} + $self->{'flush'})); - $self->{'last_flush'} = time(); - $self->{'logger'}->writeLogInfo("Flush Beginning"); - } - ### - # Metrics - ### - foreach my $metric_id (keys %{$self->{"rrdcache_metric_data"}}) { - RRDs::update($self->{"metric_path"} . "/" . $metric_id . ".rrd", @{$self->{"rrdcache_metric_data"}->{$metric_id}}); - my $ERR = RRDs::error; - if ($ERR) { - # Try to see if the file had been deleted - if (! -e $self->{"metric_path"} . "/" . $metric_id . ".rrd") { - my $my_len_storage_rrd = $self->{"metric_info"}->{$metric_id}->{'len_rrd'}; - my $interval_hb = $self->{"metric_info"}->{$metric_id}->{'interval'} * 10; - - $self->create_rrd_database($self->{"metric_path"}, $metric_id, - $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} - 200, - $self->{"metric_info"}->{$metric_id}->{'interval'}, - $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $my_len_storage_rrd, - $self->{"metric_info"}->{$metric_id}->{'data_source_type'}); - $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $interval_hb); - } else { - $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"metric_path"} . "/" . $metric_id . ".rrd' $ERR"); - } - } - } - $self->{"rrdcache_metric_data"} = {}; - - ### - # Status - ### - foreach my $service_id (keys %{$self->{"rrdcache_status_data"}}) { - RRDs::update($self->{"status_path"} . "/" . $service_id . ".rrd", @{$self->{"rrdcache_status_data"}->{$service_id}}); - my $ERR = RRDs::error; - if ($ERR) { - # Try to see if the file had been deleted - if (! -e $self->{"status_path"} . "/" . $service_id . ".rrd") { - my $my_len_storage_rrd = $self->{"status_info"}->{$service_id}->{'len_rrd'}; - my $interval_hb = $self->{"status_info"}->{$service_id}->{'interval'} * 10; - - $self->create_rrd_database($self->{"status_path"}, $service_id, - $self->{"status_info"}->{$service_id}->{'last_timestamp'} - 200, - $self->{"status_info"}->{$service_id}->{'interval'}, - "status", $my_len_storage_rrd, - 0); - $self->tune_rrd_database($self->{"status_path"}, $service_id, "status", $interval_hb); - } else { - $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"status_path"} . "/" . $service_id . ".rrd' $ERR"); - } - } - } - $self->{"rrdcache_status_data"} = {}; + my $self = shift; + my ($force) = @_; + + if ($self->{'cache_mode'} == 1 && (!defined($force) || $force == 0)) { + return if (time() < ($self->{'last_flush'} + $self->{'flush'})); + $self->{'last_flush'} = time(); + $self->{'logger'}->writeLogInfo("Flush Beginning"); + } + ### + # Metrics + ### + foreach my $metric_id (keys %{$self->{"rrdcache_metric_data"}}) { + RRDs::update($self->{"metric_path"} . "/" . $metric_id . ".rrd", @{$self->{"rrdcache_metric_data"}->{$metric_id}}); + my $ERR = RRDs::error; + if ($ERR) { + # Try to see if the file had been deleted + if (! -e $self->{"metric_path"} . "/" . $metric_id . ".rrd") { + my $my_len_storage_rrd = $self->{"metric_info"}->{$metric_id}->{'len_rrd'}; + my $interval_hb = $self->{"metric_info"}->{$metric_id}->{'interval'} * 10; + + $self->create_rrd_database($self->{"metric_path"}, $metric_id, + $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} - 200, + $self->{"metric_info"}->{$metric_id}->{'interval'}, + $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $my_len_storage_rrd, + $self->{"metric_info"}->{$metric_id}->{'data_source_type'}); + $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $interval_hb); + } else { + $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"metric_path"} . "/" . $metric_id . ".rrd' $ERR"); + } + } + } + $self->{"rrdcache_metric_data"} = {}; + + ### + # Status + ### + foreach my $service_id (keys %{$self->{"rrdcache_status_data"}}) { + RRDs::update($self->{"status_path"} . "/" . $service_id . ".rrd", @{$self->{"rrdcache_status_data"}->{$service_id}}); + my $ERR = RRDs::error; + if ($ERR) { + # Try to see if the file had been deleted + if (! -e $self->{"status_path"} . "/" . $service_id . ".rrd") { + my $my_len_storage_rrd = $self->{"status_info"}->{$service_id}->{'len_rrd'}; + my $interval_hb = $self->{"status_info"}->{$service_id}->{'interval'} * 10; + + $self->create_rrd_database($self->{"status_path"}, $service_id, + $self->{"status_info"}->{$service_id}->{'last_timestamp'} - 200, + $self->{"status_info"}->{$service_id}->{'interval'}, + "status", $my_len_storage_rrd, + 0); + $self->tune_rrd_database($self->{"status_path"}, $service_id, "status", $interval_hb); + } else { + $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"status_path"} . "/" . $service_id . ".rrd' $ERR"); + } + } + } + $self->{"rrdcache_status_data"} = {}; - $self->{'logger'}->writeLogInfo("Flush Ending") if ($self->{'cache_mode'} == 1); + $self->{'logger'}->writeLogInfo("Flush Ending") if ($self->{'cache_mode'} == 1); } 1; diff --git a/centreon/lib/perl/centstorage/CentstorageRebuild.pm b/centreon/lib/perl/centstorage/CentstorageRebuild.pm index 693be0fb9ac..13de3825976 100644 --- a/centreon/lib/perl/centstorage/CentstorageRebuild.pm +++ b/centreon/lib/perl/centstorage/CentstorageRebuild.pm @@ -6,94 +6,94 @@ package centstorage::CentstorageRebuild; my %handlers = ('TERM' => {}); sub new { - my $class = shift; - my $self = {}; - $self->{"logger"} = shift; - $self->{"dbcentstorage"} = undef; - - bless $self, $class; - $self->set_signal_handlers; - return $self; + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"dbcentstorage"} = undef; + + bless $self, $class; + $self->set_signal_handlers; + return $self; } sub set_signal_handlers { - my $self = shift; + my $self = shift; - $SIG{TERM} = \&class_handle_TERM; - $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; + $SIG{TERM} = \&class_handle_TERM; + $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; } sub handle_TERM { - my $self = shift; - $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); - - eval { - local $SIG{ALRM} = sub { die "alarm\n" }; - alarm 10; - $self->{'dbcentstorage'}->kill(); - alarm 0; - }; - if ($@) { - $self->{'logger'}->writeLogError("Can't kill rebuild request"); - } - $self->{"dbcentstorage"}->disconnect() if (defined($self->{"dbcentstorage"})); + my $self = shift; + $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); + + eval { + local $SIG{ALRM} = sub { die "alarm\n" }; + alarm 10; + $self->{'dbcentstorage'}->kill(); + alarm 0; + }; + if ($@) { + $self->{'logger'}->writeLogError("Can't kill rebuild request"); + } + $self->{"dbcentstorage"}->disconnect() if (defined($self->{"dbcentstorage"})); } sub class_handle_TERM { - foreach (keys %{$handlers{'TERM'}}) { - &{$handlers{'TERM'}->{$_}}(); - } - exit(0); + foreach (keys %{$handlers{'TERM'}}) { + &{$handlers{'TERM'}->{$_}}(); + } + exit(0); } sub main { - my $self = shift; - my ($dbcentstorage, $index_id, $interval, $rrd, $local_rrd) = @_; - my $status; - my $stmt; - - $self->{'dbcentstorage'} = $dbcentstorage; - ### Update for UI - ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE index_data SET `must_be_rebuild` = '2' WHERE id = " . $index_id); + my $self = shift; + my ($dbcentstorage, $index_id, $interval, $rrd, $local_rrd) = @_; + my $status; + my $stmt; + + $self->{'dbcentstorage'} = $dbcentstorage; + ### Update for UI + ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE index_data SET `must_be_rebuild` = '2' WHERE id = " . $index_id); + if ($status == -1) { + $self->{'logger'}->writeLogError("rebuild cannot update index_id $index_id"); + return 1; + } + + ### + # Get By Metric_id + ### + ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id, metric_name, data_source_type FROM metrics WHERE index_id = " . $index_id); + if ($status == -1) { + $self->{'logger'}->writeLogError("rebuild cannot get metrics list"); + return 1; + } + while ((my $data = $stmt->fetchrow_hashref())) { + ($status, my $stmt2) = $self->{'dbcentstorage'}->query("SELECT ctime, value FROM data_bin WHERE id_metric = " . $data->{'metric_id'} . " ORDER BY ctime ASC"); if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot update index_id $index_id"); - return 1; - } - - ### - # Get By Metric_id - ### - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id, metric_name, data_source_type FROM metrics WHERE index_id = " . $index_id); - if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot get metrics list"); - return 1; + $self->{'logger'}->writeLogError("rebuild cannot get metric_id datas " . $data->{'metric_id'}); + return 1; } - while ((my $data = $stmt->fetchrow_hashref())) { - ($status, my $stmt2) = $self->{'dbcentstorage'}->query("SELECT ctime, value FROM data_bin WHERE id_metric = " . $data->{'metric_id'} . " ORDER BY ctime ASC"); - if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot get metric_id datas " . $data->{'metric_id'}); - return 1; - } - - ### Delete RRD - $status = $rrd->delete_rrd_metric($data->{'metric_id'}); - - my $rows = []; - while (my $data2 = (shift(@$rows) || - shift(@{$rows = $stmt2->fetchall_arrayref(undef,10_000)||[]}) ) ) { - $rrd->add_metric($data->{'metric_id'}, $data->{'metric_name'}, $interval, $data->{'data_source_type'}, $$data2[0], $$data2[1], $local_rrd); - } - $rrd->flush_metric($data->{'metric_id'}); - } - - ### Update for UI - ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE index_data SET `must_be_rebuild` = '0' WHERE id = " . $index_id); - if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot update index_id $index_id"); - return 1; - } - return 0; + ### Delete RRD + $status = $rrd->delete_rrd_metric($data->{'metric_id'}); + + my $rows = []; + while (my $data2 = (shift(@$rows) || + shift(@{$rows = $stmt2->fetchall_arrayref(undef,10_000)||[]}) ) ) { + $rrd->add_metric($data->{'metric_id'}, $data->{'metric_name'}, $interval, $data->{'data_source_type'}, $$data2[0], $$data2[1], $local_rrd); + } + $rrd->flush_metric($data->{'metric_id'}); + } + + ### Update for UI + ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE index_data SET `must_be_rebuild` = '0' WHERE id = " . $index_id); + if ($status == -1) { + $self->{'logger'}->writeLogError("rebuild cannot update index_id $index_id"); + return 1; + } + + return 0; } 1; From e16c2b2fe8c6787af7a008d755f8cfa79e629fdd Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 20 Mar 2013 16:22:37 +0100 Subject: [PATCH 005/458] + Add debug logger class + Protect port db class + Correct level in logger class --- centreon/lib/perl/centreon/db.pm | 1 + centreon/lib/perl/centreon/logger.pm | 34 +- .../lib/perl/centreon/script/centstorage.pm | 638 +++++++++--------- .../lib/perl/centstorage/CentstoragePool.pm | 9 +- 4 files changed, 358 insertions(+), 324 deletions(-) diff --git a/centreon/lib/perl/centreon/db.pm b/centreon/lib/perl/centreon/db.pm index ec5fd17d784..f760b6e05f0 100644 --- a/centreon/lib/perl/centreon/db.pm +++ b/centreon/lib/perl/centreon/db.pm @@ -55,6 +55,7 @@ sub new { ); my $self = {%defaults, %options}; + $self->{port} = 3306 if (!defined($self->{port})); $self->{"instance"} = undef; $self->{"type"} = "mysql"; $self->{"args"} = []; diff --git a/centreon/lib/perl/centreon/logger.pm b/centreon/lib/perl/centreon/logger.pm index 1e53f19a4e7..1b051eec8c2 100644 --- a/centreon/lib/perl/centreon/logger.pm +++ b/centreon/lib/perl/centreon/logger.pm @@ -33,7 +33,8 @@ use Sys::Syslog qw(:standard :macros); use IO::Handle; my %severities = (1 => LOG_INFO, - 2 => LOG_ERR); + 2 => LOG_ERR, + 4 => LOG_DEBUG); sub new { my $class = shift; @@ -42,7 +43,7 @@ sub new { { file => 0, filehandler => undef, - # 0 = nothing, 1 = critical, 3 = info + # 0 = nothing, 1 = critical, 3 = info, 7 = debug severity => 3, # 0 = stdout, 1 = file, 2 = syslog log_mode => 0, @@ -59,6 +60,7 @@ sub file_mode($$) { if (open($self->{filehandler}, ">>", $file)){ $self->{log_mode} = 1; $self->{filehandler}->autoflush(1); + $self->{file_name} = $file; return 1; } $self->{filehandler} = undef; @@ -66,6 +68,15 @@ sub file_mode($$) { return 0; } +sub is_file_mode { + my $self = shift; + + if ($self->{log_mode} == 1) { + return 1; + } + return 0; +} + sub syslog_mode($$$) { my ($self, $logopt, $facility) = @_; @@ -74,6 +85,17 @@ sub syslog_mode($$$) { return 1; } +# For daemons +sub redirect_output { + my $self = shift; + + if ($self->is_file_mode()) { + open my $lfh, '>>', $self->{file_name}; + open STDOUT, '>&', $lfh; + open STDERR, '>&', $lfh; + } +} + # Getter/Setter Log severity sub severity { my $self = shift; @@ -110,12 +132,16 @@ sub writeLog($$$%) { } } +sub writeLogDebug { + shift->writeLog(4, @_); +} + sub writeLogInfo { - shift->writeLog(1, @_); + shift->writeLog(2, @_); } sub writeLogError { - shift->writeLog(2, @_); + shift->writeLog(1, @_); } sub DESTROY { diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index aeccd00b69a..87f6a1b35b0 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -16,7 +16,7 @@ use centstorage::CentstorageAction; use centstorage::CentstorageRRD; use base qw(centreon::script); -use vars qw($centstorage_config); +use vars qw(%centstorage_config); my %handlers = ('TERM' => {}, 'CHLD' => {}, 'DIE' => {}); @@ -47,12 +47,24 @@ sub new { $self->{rebuild_progress} = 0; $self->{rebuild_pool_choosen} = 0; + my %centstorage_default_config = + ( + pool_childs => 4, + TIMEOUT => 60, + rrd_cache_mode => 0, + rrd_flush_time => 60 * 10, + centreon_23_compatibility => 0, + perfdata_parser_stop => 1 + ); + if (defined($self->{opt_extra})) { - require $self->{opt_extra}; + require $self->{opt_extra}; } else { - require "/etc/centreon/centstorage.pm"; + if (-f "/etc/centreon/centstorage.pm") { + require "/etc/centreon/centstorage.pm"; + } } - $self->{centstorage_config} = $centstorage_config; + $self->{centstorage_config} = {%centstorage_default_config, %centstorage_config}; $self->set_signal_handlers; @@ -60,118 +72,102 @@ sub new { } sub set_signal_handlers { - my $self = shift; - - $SIG{TERM} = \&class_handle_TERM; - $handlers{TERM}->{$self} = sub { $self->handle_TERM() }; - $SIG{__DIE__} = \&class_handle_DIE; - $handlers{DIE}->{$self} = sub { $self->handle_DIE($_[0]) }; - $SIG{CHLD} = \&class_handle_CHLD; - $handlers{CHLD}->{$self} = sub { $self->handle_CHLD() }; + my $self = shift; + + $SIG{TERM} = \&class_handle_TERM; + $handlers{TERM}->{$self} = sub { $self->handle_TERM() }; + $SIG{__DIE__} = \&class_handle_DIE; + $handlers{DIE}->{$self} = sub { $self->handle_DIE($_[0]) }; + $SIG{CHLD} = \&class_handle_CHLD; + $handlers{CHLD}->{$self} = sub { $self->handle_CHLD() }; } sub class_handle_TERM { - foreach (keys %{$handlers{TERM}}) { - &{$handlers{TERM}->{$_}}(); - } - exit(0); + foreach (keys %{$handlers{TERM}}) { + &{$handlers{TERM}->{$_}}(); + } + exit(0); } sub class_handle_DIE { - my ($msg) = @_; + my ($msg) = @_; - foreach (keys %{$handlers{DIE}}) { - &{$handlers{DIE}->{$_}}($msg); - } + foreach (keys %{$handlers{DIE}}) { + &{$handlers{DIE}->{$_}}($msg); + } } sub class_handle_CHLD { - foreach (keys %{$handlers{CHLD}}) { - &{$handlers{CHLD}->{$_}}(); - } + foreach (keys %{$handlers{CHLD}}) { + &{$handlers{CHLD}->{$_}}(); + } } +sub handle_DIE { + my $self = shift; + my $msg = shift; -# Init Log -#my $logger = CentstorageLogger->new(); -#$logger->severity($log_crit); + # We get SIGCHLD signals + $self->{logger}->writeLogInfo($msg); + + ### + # Send -TERM signal + ### + for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { + if (defined($self->{pool_pipes}{$i}) && $self->{pool_pipes}{$i}->{'running'} == 1) { + kill('TERM', $self->{pool_pipes}{$i}->{'pid'}); + $self->{logger}->writeLogInfo("Send -TERM signal to pool process.."); + } + } + if (defined($self->{delete_pipes}{'running'}) && $self->{delete_pipes}{'running'} == 1) { + $self->{logger}->writeLogInfo("Send -TERM signal to delete process.."); + kill('TERM', $self->{pid_delete_child}); + } -#if ($log_mode == 1) { -# open my $centstorage_fh, '>>', $LOG; -# open STDOUT, '>&', $centstorage_fh; -# open STDERR, '>&', $centstorage_fh; -# $logger->log_mode(1, $LOG); -#} -#if ($log_mode == 2) { -# $logger->log_mode(2, $openlog_option, $log_facility); -#} -######### + ### Write file + if (defined($self->{centstorage_perfdata_file})) { + $self->{centstorage_perfdata_file}->finish(); + } -sub handle_DIE { - my $self = shift; - my $msg = shift; - - # We get SIGCHLD signals - $self->{logger}->writeLogInfo($msg); - - ### - # Send -TERM signal - ### - for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { - if (defined($self->{pool_pipes}{$i}) && $self->{pool_pipes}{$i}->{'running'} == 1) { - kill('TERM', $self->{pool_pipes}{$i}->{'pid'}); - $self->{logger}->writeLogInfo("Send -TERM signal to pool process.."); - } - } - if (defined($self->{delete_pipes}{'running'}) && $self->{delete_pipes}{'running'} == 1) { - $self->{logger}->writeLogInfo("Send -TERM signal to delete process.."); - kill('TERM', $self->{pid_delete_child}); - } - - ### Write file - if (defined($self->{centstorage_perfdata_file})) { - $self->{centstorage_perfdata_file}->finish(); - } - - if (scalar(keys %{$self->{pool_pipes}}) == 0) { - exit(0); - } - - my $kill_or_not = 1; - for (my $i = 0; $i < $self->{centstorage_config}->{TIMEOUT}; $i++) { - $self->verify_pool(0); - my $running = 0; - for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { - $running += $self->{pool_pipes}{$i}->{'running'} == 1; - } - $running += $self->{delete_pipes}{'running'}; - if ($running == 0) { - $kill_or_not = 0; - last; - } - sleep(1); - } - - if ($kill_or_not == 1) { - for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { - if ($self->{pool_pipes}{$i}->{'running'} == 1) { - kill('KILL', $self->{pool_pipes}{$i}->{'pid'}); - $self->{logger}->writeLogInfo("Send -KILL signal to pool process.."); - } - } - if ($self->{delete_pipes}{'running'} == 1) { - kill('KILL', $self->{pid_delete_child}); - $self->{logger}->writeLogInfo("Send -KILL signal to delete process.."); - } - } - - exit(0); + if (scalar(keys %{$self->{pool_pipes}}) == 0) { + exit(0); + } + + my $kill_or_not = 1; + for (my $i = 0; $i < $self->{centstorage_config}->{TIMEOUT}; $i++) { + $self->verify_pool(0); + my $running = 0; + for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { + $running += $self->{pool_pipes}{$i}->{'running'} == 1; + } + $running += $self->{delete_pipes}{'running'}; + if ($running == 0) { + $kill_or_not = 0; + last; + } + sleep(1); + } + + if ($kill_or_not == 1) { + for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { + if ($self->{pool_pipes}{$i}->{'running'} == 1) { + kill('KILL', $self->{pool_pipes}{$i}->{'pid'}); + $self->{logger}->writeLogInfo("Send -KILL signal to pool process.."); + } + } + if ($self->{delete_pipes}{'running'} == 1) { + kill('KILL', $self->{pid_delete_child}); + $self->{logger}->writeLogInfo("Send -KILL signal to delete process.."); + } + } + + exit(0); } sub handle_TERM { - my $self = shift; - $self->{logger}->writeLogInfo("$$ Receiving order to stop..."); - die("Quit"); + my $self = shift; + $self->{logger}->writeLogInfo("$$ Receiving order to stop..."); + die("Quit"); } #### @@ -180,247 +176,253 @@ sub handle_TERM { #### sub verify_pool { - my $self = shift; - my ($create_pool) = @_; - - foreach my $child_pid (keys %{$self->{return_child}}) { - foreach my $pool_num (keys %{$self->{pool_pipes}}) { - if ($self->{pool_pipes}{$pool_num}->{'pid'} == $child_pid) { - $self->{logger}->writeLogInfo("Pool child '$pool_num' is dead"); - $self->{read_select}->remove($self->{pool_pipes}{$pool_num}->{'reader_one'}); - $self->{pool_pipes}{$pool_num}->{'running'} = 0; - if (defined($create_pool) && $create_pool == 1) { - # We have lost one. And if it's the pool rebuild, send progress finish - if ($pool_num == $self->{rebuild_pool_choosen}) { - centstorage::CentstorageLib::call_pool_rebuild_finish(\%{$self->{pool_pipes}}, $self->{centstorage_config}->{pool_childs}, \%{$self->{delete_pipes}}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); - } - $self->create_pool_child($pool_num); - } - delete $self->{return_child}{$child_pid}; - last; - } - } - if ($child_pid == $self->{pid_delete_child}) { - $self->{logger}->writeLogInfo("Delete child is dead"); - $self->{read_select}->remove($self->{delete_pipes}{'reader_one'}); - $self->{delete_pipes}{'running'} = 0; - if (defined($create_pool) && $create_pool == 1) { - $self->create_delete_child(); - } - delete $self->{return_child}{$child_pid}; - } - } + my $self = shift; + my ($create_pool) = @_; + + foreach my $child_pid (keys %{$self->{return_child}}) { + foreach my $pool_num (keys %{$self->{pool_pipes}}) { + if ($self->{pool_pipes}{$pool_num}->{'pid'} == $child_pid) { + $self->{logger}->writeLogInfo("Pool child '$pool_num' is dead"); + $self->{read_select}->remove($self->{pool_pipes}{$pool_num}->{'reader_one'}); + $self->{pool_pipes}{$pool_num}->{'running'} = 0; + if (defined($create_pool) && $create_pool == 1) { + # We have lost one. And if it's the pool rebuild, send progress finish + if ($pool_num == $self->{rebuild_pool_choosen}) { + centstorage::CentstorageLib::call_pool_rebuild_finish(\%{$self->{pool_pipes}}, $self->{centstorage_config}->{pool_childs}, \%{$self->{delete_pipes}}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); + } + $self->create_pool_child($pool_num); + } + delete $self->{return_child}{$child_pid}; + last; + } + } + if ($child_pid == $self->{pid_delete_child}) { + $self->{logger}->writeLogInfo("Delete child is dead"); + $self->{read_select}->remove($self->{delete_pipes}{'reader_one'}); + $self->{delete_pipes}{'running'} = 0; + if (defined($create_pool) && $create_pool == 1) { + $self->create_delete_child(); + } + delete $self->{return_child}{$child_pid}; + } + } } sub create_pool_child { - my $self = shift; - my $pool_num = $_[0]; - - my ($reader_pipe_one, $writer_pipe_one); - my ($reader_pipe_two, $writer_pipe_two); - - pipe($reader_pipe_one, $writer_pipe_one); - pipe($reader_pipe_two, $writer_pipe_two); - $writer_pipe_one->autoflush(1); - $writer_pipe_two->autoflush(1); - - $self->{pool_pipes}{$pool_num} = {}; - $self->{pool_pipes}{$pool_num}->{'reader_one'} = \*$reader_pipe_one; - $self->{pool_pipes}{$pool_num}->{'writer_one'} = \*$writer_pipe_one; - $self->{pool_pipes}{$pool_num}->{'reader_two'} = \*$reader_pipe_two; - $self->{pool_pipes}{$pool_num}->{'writer_two'} = \*$writer_pipe_two; - - $self->{logger}->writeLogInfo("Create Pool child '$pool_num'"); - my $current_pid = fork(); - if (!$current_pid) { - close $self->{pool_pipes}{$pool_num}->{'reader_one'}; - close $self->{pool_pipes}{$pool_num}->{'writer_two'}; - my $centreon_db_centreon = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, - host => $self->{centreon_config}->{db_host}, - user => $self->{centreon_config}->{db_user}, - password => $self->{centreon_config}->{db_passwd}, - force => 1, - logger => $self->{logger}); - $centreon_db_centreon->connect(); - my $centreon_db_centstorage = centreon::db->new(db => $self->{centreon_config}->{centstorage_db}, - host => $self->{centreon_config}->{db_host}, - user => $self->{centreon_config}->{db_user}, - password => $self->{centreon_config}->{db_passwd}, - force => 1, - logger => $self->{logger}); - $centreon_db_centstorage->connect(); - - my $centstorage_rrd = centstorage::CentstorageRRD->new($self->{logger}); - - my $centstorage_pool = centstorage::CentstoragePool->new($self->{logger}, $centstorage_rrd, $self->{rebuild_progress}); - $centstorage_pool->main($centreon_db_centreon, $centreon_db_centstorage, - $self->{pool_pipes}{$pool_num}->{'reader_two'}, $self->{pool_pipes}{$pool_num}->{'writer_one'}, $pool_num, - $self->{centstorage_config}->{rrd_cache_mode}, $self->{centstorage_config}->{rrd_flush_time}, $self->{centstorage_config}->{perfdata_parser_stop}); - exit(0); - } - $self->{pool_pipes}{$pool_num}->{'pid'} = $current_pid; - $self->{pool_pipes}{$pool_num}->{'running'} = 1; - close $self->{pool_pipes}{$pool_num}->{'writer_one'}; - close $self->{pool_pipes}{$pool_num}->{'reader_two'}; - $self->{fileno_save_read}{fileno($self->{pool_pipes}{$pool_num}->{'reader_one'})} = []; - $self->{read_select}->add($self->{pool_pipes}{$pool_num}->{'reader_one'}); + my $self = shift; + my $pool_num = $_[0]; + + my ($reader_pipe_one, $writer_pipe_one); + my ($reader_pipe_two, $writer_pipe_two); + + pipe($reader_pipe_one, $writer_pipe_one); + pipe($reader_pipe_two, $writer_pipe_two); + $writer_pipe_one->autoflush(1); + $writer_pipe_two->autoflush(1); + + $self->{pool_pipes}{$pool_num} = {}; + $self->{pool_pipes}{$pool_num}->{'reader_one'} = \*$reader_pipe_one; + $self->{pool_pipes}{$pool_num}->{'writer_one'} = \*$writer_pipe_one; + $self->{pool_pipes}{$pool_num}->{'reader_two'} = \*$reader_pipe_two; + $self->{pool_pipes}{$pool_num}->{'writer_two'} = \*$writer_pipe_two; + + $self->{logger}->writeLogInfo("Create Pool child '$pool_num'"); + my $current_pid = fork(); + if (!$current_pid) { + close $self->{pool_pipes}{$pool_num}->{'reader_one'}; + close $self->{pool_pipes}{$pool_num}->{'writer_two'}; + my $centreon_db_centreon = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 1, + logger => $self->{logger}); + $centreon_db_centreon->connect(); + my $centreon_db_centstorage = centreon::db->new(db => $self->{centreon_config}->{centstorage_db}, + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 1, + logger => $self->{logger}); + $centreon_db_centstorage->connect(); + + my $centstorage_rrd = centstorage::CentstorageRRD->new($self->{logger}); + + my $centstorage_pool = centstorage::CentstoragePool->new($self->{logger}, $centstorage_rrd, $self->{rebuild_progress}); + $centstorage_pool->main($centreon_db_centreon, $centreon_db_centstorage, + $self->{pool_pipes}{$pool_num}->{'reader_two'}, $self->{pool_pipes}{$pool_num}->{'writer_one'}, $pool_num, + $self->{centstorage_config}->{rrd_cache_mode}, $self->{centstorage_config}->{rrd_flush_time}, $self->{centstorage_config}->{perfdata_parser_stop}); + exit(0); + } + $self->{pool_pipes}{$pool_num}->{'pid'} = $current_pid; + $self->{pool_pipes}{$pool_num}->{'running'} = 1; + close $self->{pool_pipes}{$pool_num}->{'writer_one'}; + close $self->{pool_pipes}{$pool_num}->{'reader_two'}; + $self->{fileno_save_read}{fileno($self->{pool_pipes}{$pool_num}->{'reader_one'})} = []; + $self->{read_select}->add($self->{pool_pipes}{$pool_num}->{'reader_one'}); } sub create_delete_child { - my $self = shift; - my ($reader_pipe_one, $writer_pipe_one); - my ($reader_pipe_two, $writer_pipe_two); - - - pipe($reader_pipe_one, $writer_pipe_one); - pipe($reader_pipe_two, $writer_pipe_two); - $writer_pipe_one->autoflush(1); - $writer_pipe_two->autoflush(1); - - $self->{delete_pipes}{'reader_one'} = \*$reader_pipe_one; - $self->{delete_pipes}{'writer_one'} = \*$writer_pipe_one; - $self->{delete_pipes}{'reader_two'} = \*$reader_pipe_two; - $self->{delete_pipes}{'writer_two'} = \*$writer_pipe_two; - - $self->{logger}->writeLogInfo("Create delete child"); - my $current_pid = fork(); - if (!$current_pid) { - close $self->{delete_pipes}{'reader_one'}; - close $self->{delete_pipes}{'writer_two'}; - my $centreon_db_centreon = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, - host => $self->{centreon_config}->{db_host}, - user => $self->{centreon_config}->{db_user}, - password => $self->{centreon_config}->{db_passwd}, - force => 1, - logger => $self->{logger}); - $centreon_db_centreon->connect(); - my $centreon_db_centstorage = centreon::db->new(db => $self->{centreon_config}->{centstorage_db}, - host => $self->{centreon_config}->{db_host}, - user => $self->{centreon_config}->{db_user}, - password => $self->{centreon_config}->{db_passwd}, - force => 1, - logger => $self->{logger}); - $centreon_db_centstorage->connect(); - - my $centstorage_action = centstorage::CentstorageAction->new($self->{logger}, $self->{rebuild_progress}, $self->{centstorage_config}->{centreon_23_compatibility}); - $centstorage_action->main($centreon_db_centreon, $centreon_db_centstorage, - $self->{delete_pipes}{'reader_two'}, $self->{delete_pipes}{'writer_one'}); - exit(0); - } - $self->{pid_delete_child} = $current_pid; - close $self->{delete_pipes}{'writer_one'}; - close $self->{delete_pipes}{'reader_two'}; - $self->{delete_pipes}{'running'} = 1; - $self->{fileno_save_read}{fileno($self->{delete_pipes}{'reader_one'})} = []; - $self->{read_select}->add($self->{delete_pipes}{'reader_one'}); + my $self = shift; + my ($reader_pipe_one, $writer_pipe_one); + my ($reader_pipe_two, $writer_pipe_two); + + + pipe($reader_pipe_one, $writer_pipe_one); + pipe($reader_pipe_two, $writer_pipe_two); + $writer_pipe_one->autoflush(1); + $writer_pipe_two->autoflush(1); + + $self->{delete_pipes}{'reader_one'} = \*$reader_pipe_one; + $self->{delete_pipes}{'writer_one'} = \*$writer_pipe_one; + $self->{delete_pipes}{'reader_two'} = \*$reader_pipe_two; + $self->{delete_pipes}{'writer_two'} = \*$writer_pipe_two; + + $self->{logger}->writeLogInfo("Create delete child"); + my $current_pid = fork(); + if (!$current_pid) { + close $self->{delete_pipes}{'reader_one'}; + close $self->{delete_pipes}{'writer_two'}; + my $centreon_db_centreon = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 1, + logger => $self->{logger}); + $centreon_db_centreon->connect(); + my $centreon_db_centstorage = centreon::db->new(db => $self->{centreon_config}->{centstorage_db}, + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 1, + logger => $self->{logger}); + $centreon_db_centstorage->connect(); + + my $centstorage_action = centstorage::CentstorageAction->new($self->{logger}, $self->{rebuild_progress}, $self->{centstorage_config}->{centreon_23_compatibility}); + $centstorage_action->main($centreon_db_centreon, $centreon_db_centstorage, + $self->{delete_pipes}{'reader_two'}, $self->{delete_pipes}{'writer_one'}); + exit(0); + } + $self->{pid_delete_child} = $current_pid; + close $self->{delete_pipes}{'writer_one'}; + close $self->{delete_pipes}{'reader_two'}; + $self->{delete_pipes}{'running'} = 1; + $self->{fileno_save_read}{fileno($self->{delete_pipes}{'reader_one'})} = []; + $self->{read_select}->add($self->{delete_pipes}{'reader_one'}); } sub handle_CHLD { - my $self = shift; - my $child_pid; + my $self = shift; + my $child_pid; - while (($child_pid = waitpid(-1, &WNOHANG)) > 0) { - $self->{return_child}{$child_pid} = {'exit_code' => $? >> 8}; - } - $SIG{CHLD} = \&class_handle_CHLD; + while (($child_pid = waitpid(-1, &WNOHANG)) > 0) { + $self->{return_child}{$child_pid} = {'exit_code' => $? >> 8}; + } + $SIG{CHLD} = \&class_handle_CHLD; } sub run { - my $self = shift; + my $self = shift; - $self->SUPER::run(); + $self->SUPER::run(); + $self->{logger}->redirect_output(); - #### - # Get Main perfdata and status - #### - my $main_perfdata; - my $status; - my $pools_perfdata_filename; + #### + # Get Main perfdata and status + #### + my $main_perfdata; + my $status; + my $pools_perfdata_filename; - $self->{centreon_db_centreon} = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, + $self->{centreon_db_centreon} = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, user => $self->{centreon_config}->{db_user}, password => $self->{centreon_config}->{db_passwd}, force => 1, logger => $self->{logger}); - $self->{centreon_db_centreon}->connect(); - $self->handle_DIE("Censtorage option is '0'. Don't have to start") if (centstorage::CentstorageLib::start_or_not($self->{centreon_db_centreon}) == 0); - while (!defined($main_perfdata) || $main_perfdata eq "") { - ($status, $main_perfdata) = centstorage::CentstorageLib::get_main_perfdata_file($self->{centreon_db_centreon}); - if (defined($main_perfdata)) { - $pools_perfdata_filename = centstorage::CentstorageLib::check_pool_old_perfdata_file($main_perfdata, $self->{centstorage_config}->{pool_childs}); - } - } - $self->{centreon_db_centreon}->disconnect(); - - ### - # Check write - ### - if (defined($pools_perfdata_filename)) { - foreach (@$pools_perfdata_filename) { - $self->handle_DIE("Don't have righs on file '$_' (or the directory)") if (centstorage::CentstorageLib::can_write($_) == 0); - } - } - $self->handle_DIE("Don't have righs on file '$main_perfdata' (or the directory)") if (centstorage::CentstorageLib::can_write($main_perfdata) == 0); - - ### - # Create Childs - ### - $self->{read_select} = new IO::Select(); - for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { - $self->create_pool_child($i); - } - $self->create_delete_child(); - - ################## - ################## - - - #### - # Main loop - #### - while (1) { - $self->verify_pool(1); - - ### - # Do pool perfdata if needed - ### - if (defined($pools_perfdata_filename)) { - foreach (@$pools_perfdata_filename) { - $self->{centstorage_perfdata_file} = centstorage::CentstoragePerfdataFile->new($self->{logger}); - $self->{centstorage_perfdata_file}->compute($_, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); - } - $pools_perfdata_filename = undef; - } - - ### - # Do main file - ### - $self->{centstorage_perfdata_file} = centstorage::CentstoragePerfdataFile->new($self->{logger}); - $self->{centstorage_perfdata_file}->compute($main_perfdata, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); - - ### - # Check response from rebuild - ### - my @rh_set = $self->{read_select}->can_read(10); - foreach my $rh (@rh_set) { - my $read_done = 0; - while ((my ($status_line, $data_element) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{fileno_save_read}{fileno($rh)}}, \$read_done))) { - last if ($status_line <= 0); - if ($data_element =~ /^REBUILDBEGIN/) { - centstorage::CentstorageLib::call_pool_rebuild($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); - } elsif ($data_element =~ /^REBUILDFINISH/) { - centstorage::CentstorageLib::call_pool_rebuild_finish(\%{$self->{pool_pipes}}, $self->{centstorage_config}->{pool_childs}, \%{$self->{delete_pipes}}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); - } elsif ($data_element =~ /^RENAMECLEAN/) { - centstorage::CentstorageLib::call_pool_rename_clean($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); - } elsif ($data_element =~ /^RENAMEFINISH/) { - centstorage::CentstorageLib::call_pool_rename_finish($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); - } elsif ($data_element =~ /^DELETECLEAN/) { - centstorage::CentstorageLib::call_pool_delete_clean($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); - } - } - } - } + $self->{centreon_db_centreon}->connect(); + $self->handle_DIE("Censtorage option is '0'. Don't have to start") if (centstorage::CentstorageLib::start_or_not($self->{centreon_db_centreon}) == 0); + while (!defined($main_perfdata) || $main_perfdata eq "") { + ($status, $main_perfdata) = centstorage::CentstorageLib::get_main_perfdata_file($self->{centreon_db_centreon}); + if (defined($main_perfdata)) { + $pools_perfdata_filename = centstorage::CentstorageLib::check_pool_old_perfdata_file($main_perfdata, $self->{centstorage_config}->{pool_childs}); + } + } + $self->{centreon_db_centreon}->disconnect(); + + ### + # Check write + ### + if (defined($pools_perfdata_filename)) { + foreach (@$pools_perfdata_filename) { + $self->handle_DIE("Don't have righs on file '$_' (or the directory)") if (centstorage::CentstorageLib::can_write($_) == 0); + } + } + $self->handle_DIE("Don't have righs on file '$main_perfdata' (or the directory)") if (centstorage::CentstorageLib::can_write($main_perfdata) == 0); + + ### + # Create Childs + ### + $self->{read_select} = new IO::Select(); + for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { + $self->create_pool_child($i); + } + $self->create_delete_child(); + + ################## + ################## + + + #### + # Main loop + #### + while (1) { + $self->verify_pool(1); + + ### + # Do pool perfdata if needed + ### + if (defined($pools_perfdata_filename)) { + foreach (@$pools_perfdata_filename) { + $self->{centstorage_perfdata_file} = centstorage::CentstoragePerfdataFile->new($self->{logger}); + $self->{centstorage_perfdata_file}->compute($_, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + } + $pools_perfdata_filename = undef; + } + + ### + # Do main file + ### + $self->{centstorage_perfdata_file} = centstorage::CentstoragePerfdataFile->new($self->{logger}); + $self->{centstorage_perfdata_file}->compute($main_perfdata, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + + ### + # Check response from rebuild + ### + my @rh_set = $self->{read_select}->can_read(10); + foreach my $rh (@rh_set) { + my $read_done = 0; + while ((my ($status_line, $data_element) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{fileno_save_read}{fileno($rh)}}, \$read_done))) { + last if ($status_line <= 0); + if ($data_element =~ /^REBUILDBEGIN/) { + centstorage::CentstorageLib::call_pool_rebuild($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); + } elsif ($data_element =~ /^REBUILDFINISH/) { + centstorage::CentstorageLib::call_pool_rebuild_finish(\%{$self->{pool_pipes}}, $self->{centstorage_config}->{pool_childs}, \%{$self->{delete_pipes}}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); + } elsif ($data_element =~ /^RENAMECLEAN/) { + centstorage::CentstorageLib::call_pool_rename_clean($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + } elsif ($data_element =~ /^RENAMEFINISH/) { + centstorage::CentstorageLib::call_pool_rename_finish($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + } elsif ($data_element =~ /^DELETECLEAN/) { + centstorage::CentstorageLib::call_pool_delete_clean($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + } + } + } + } } 1; diff --git a/centreon/lib/perl/centstorage/CentstoragePool.pm b/centreon/lib/perl/centstorage/CentstoragePool.pm index 38d62a34462..278e8399621 100644 --- a/centreon/lib/perl/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centstorage/CentstoragePool.pm @@ -946,8 +946,13 @@ sub rebuild { $self->{'dbcentstorage'}->set_inactive_destroy(); $self->{'dbcentreon'}->set_inactive_destroy(); - my $centreon_db_centstorage = centreon::db(logger => $self->{'logger'}, db => $self->{'dbcentstorage'}->db(), host => $self->{'dbcentstorage'}->host(), - user => $self->{'dbcentstorage'}->user(), password => $self->{'dbcentstorage'}->password(), "port" => $self->{'dbcentstorage'}->port(), force => 0); + my $centreon_db_centstorage = centreon::db(logger => $self->{'logger'}, + db => $self->{'dbcentstorage'}->db(), + host => $self->{'dbcentstorage'}->host(), + user => $self->{'dbcentstorage'}->user(), + password => $self->{'dbcentstorage'}->password(), + port => $self->{'dbcentstorage'}->port(), + force => 0); $status = $centreon_db_centstorage->connect(); exit 1 if ($status == -1); my $centstorage_rebuild = centstorage::CentstorageRebuild->new($self->{'logger'}); From 394bd897faee535460b9907f6b609c882c95ca6d Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 20 Mar 2013 16:47:18 +0100 Subject: [PATCH 006/458] + Can specify severity --- centreon/lib/perl/centreon/logger.pm | 14 +++++++++++++- centreon/lib/perl/centreon/script.pm | 5 +++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/centreon/lib/perl/centreon/logger.pm b/centreon/lib/perl/centreon/logger.pm index 1b051eec8c2..3449528b8f9 100644 --- a/centreon/lib/perl/centreon/logger.pm +++ b/centreon/lib/perl/centreon/logger.pm @@ -100,7 +100,19 @@ sub redirect_output { sub severity { my $self = shift; if (@_) { - $self->{"severity"} = $_[0]; + if ($_[0] =~ /^[012347]$/) { + $self->{"severity"} = $_[0]; + } elsif ($_[0] eq "none") { + $self->{"severity"} = 0; + } elsif ($_[0] eq "error") { + $self->{"severity"} = 1; + } elsif ($_[0] eq "info") { + $self->{"severity"} = 3; + } elsif ($_[0] eq "debug") { + $self->{"severity"} = 7; + } else { + $self->writeLogError("Wrong severity value set."); + } } return $self->{"severity"}; } diff --git a/centreon/lib/perl/centreon/script.pm b/centreon/lib/perl/centreon/script.pm index 93144057918..b8c0fce7c0d 100644 --- a/centreon/lib/perl/centreon/script.pm +++ b/centreon/lib/perl/centreon/script.pm @@ -25,7 +25,7 @@ sub new { log_file => undef, centreon_db_conn => 0, centstorage_db_conn => 0, - debug_mode => 0 + severity => "info" ); my $self = {%defaults, %options}; @@ -35,7 +35,7 @@ sub new { $self->{options} = { "config=s" => \$self->{config_file}, "logfile=s" => \$self->{log_file}, - "debug" => \$self->{debug_mode}, + "severity=s" => \$self->{severity}, "help|?" => \$self->{help} }; return $self; @@ -47,6 +47,7 @@ sub init { if (defined $self->{log_file}) { $self->{logger}->file_mode($self->{log_file}); } + $self->{logger}->severity($self->{severity}); if ($self->{centreon_db_conn}) { $self->{cdb} = centreon::db->new From 9755f3d2bf128251105614720c77ca061ab16acf Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 20 Mar 2013 17:13:54 +0100 Subject: [PATCH 007/458] First work on cron reporting Conflicts: cron/perl-modules/CentreonAck.pm cron/perl-modules/CentreonDownTime.pm --- centreon/lib/perl/reporting/CentreonAck.pm | 108 +++++++++ .../lib/perl/reporting/CentreonDashboard.pm | 176 ++++++++++++++ .../lib/perl/reporting/CentreonDownTime.pm | 222 ++++++++++++++++++ centreon/lib/perl/reporting/CentreonHost.pm | 63 +++++ .../perl/reporting/CentreonHostStateEvents.pm | 202 ++++++++++++++++ centreon/lib/perl/reporting/CentreonLog.pm | 117 +++++++++ .../reporting/CentreonProcessStateEvents.pm | 179 ++++++++++++++ .../lib/perl/reporting/CentreonService.pm | 86 +++++++ .../reporting/CentreonServiceStateEvents.pm | 203 ++++++++++++++++ 9 files changed, 1356 insertions(+) create mode 100644 centreon/lib/perl/reporting/CentreonAck.pm create mode 100644 centreon/lib/perl/reporting/CentreonDashboard.pm create mode 100644 centreon/lib/perl/reporting/CentreonDownTime.pm create mode 100644 centreon/lib/perl/reporting/CentreonHost.pm create mode 100644 centreon/lib/perl/reporting/CentreonHostStateEvents.pm create mode 100644 centreon/lib/perl/reporting/CentreonLog.pm create mode 100644 centreon/lib/perl/reporting/CentreonProcessStateEvents.pm create mode 100644 centreon/lib/perl/reporting/CentreonService.pm create mode 100644 centreon/lib/perl/reporting/CentreonServiceStateEvents.pm diff --git a/centreon/lib/perl/reporting/CentreonAck.pm b/centreon/lib/perl/reporting/CentreonAck.pm new file mode 100644 index 00000000000..f5c3c967ea0 --- /dev/null +++ b/centreon/lib/perl/reporting/CentreonAck.pm @@ -0,0 +1,108 @@ + +use strict; +use warnings; + +package reporting::CentreonAck; + +# Constructor +# parameters: +# $logger: instance of class CentreonLogger +# $centreon: Instance of centreonDB class for connection to Centreon database +# $dbLayer : Database Layer : ndo | broker +# $centstorage: (optionnal) Instance of centreonDB class for connection to Centstorage database +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"centstatus"} = shift; + $self->{'dbLayer'} = shift; + if (@_) { + $self->{"centstorage"} = shift; + } + bless $self, $class; + return $self; +} + +# returns first ack time for a service or a host event +sub getServiceAckTime { + my $self = shift; + my $centreon = $self->{"centstatus"}; + my $start = shift; + my $end = shift; + my $hostName = shift; + my $serviceDescription = shift; + my $dbLayer = $self->{'dbLayer'}; + my $query; + + if ($dbLayer eq "ndo") { + $query = "SELECT UNIX_TIMESTAMP(`entry_time`) as ack_time ". + " FROM `nagios_acknowledgements` a, `nagios_objects` o". + " WHERE o.`object_id` = a.`object_id`". + " AND `acknowledgement_type` = '1'". + " AND UNIX_TIMESTAMP(`entry_time`) >= ".$start. + " AND UNIX_TIMESTAMP(`entry_time`) <= ".$end. + " AND o.`name1` = '".$hostName. "'". + " AND o.`name2` = '".$serviceDescription. "'". + " ORDER BY `entry_time` asc"; + } elsif ($dbLayer eq "broker") { + $query = "SELECT `entry_time` as ack_time ". + " FROM `acknowledgements` a, `services` s, `hosts` h ". + " WHERE h.`host_id` = a.`host_id`". + " AND a.`host_id` = s.`host_id`". + " AND `type` = 1". + " AND `entry_time` >= ".$start. + " AND `entry_time` <= ".$end. + " AND h.`name` = '".$hostName. "'". + " AND s.`description` = '".$serviceDescription. "'". + " ORDER BY `entry_time` asc"; + } + + my $sth = $centreon->query($query); + my $ackTime = "NULL"; + if (my $row = $sth->fetchrow_hashref()) { + $ackTime = $row->{'ack_time'}; + } + $sth->finish(); + return ($ackTime); +} + +# returns first ack time for a service or a host event +sub getHostAckTime { + my $self = shift; + my $centreon = $self->{"centstatus"}; + my $start = shift; + my $end = shift; + my $hostName = shift; + my $dbLayer = $self->{'dbLayer'}; + my $query; + + if ($dbLayer eq "ndo") { + $query = "SELECT UNIX_TIMESTAMP(`entry_time`) as ack_time ". + " FROM `nagios_acknowledgements` a, `nagios_objects` o". + " WHERE o.`object_id` = a.`object_id`". + " AND `acknowledgement_type` = '0'". + " AND UNIX_TIMESTAMP(`entry_time`) >= ".$start. + " AND UNIX_TIMESTAMP(`entry_time`) <= ".$end. + " AND o.`name1` = '".$hostName. "'". + " ORDER BY `entry_time` asc"; + } elsif ($dbLayer eq "broker") { + $query = "SELECT entry_time as ack_time ". + " FROM `acknowledgements` a, `hosts` h". + " WHERE h.`host_id` = a.`host_id`". + " AND `type` = 0". + " AND `entry_time` >= ".$start. + " AND `entry_time` <= ".$end. + " AND h.`name` = '".$hostName. "'". + " ORDER BY `entry_time` asc"; + } + + my $sth = $centreon->query($query); + my $ackTime = "NULL"; + if (my $row = $sth->fetchrow_hashref()) { + $ackTime = $row->{'ack_time'}; + } + $sth->finish(); + return ($ackTime); +} + +1; \ No newline at end of file diff --git a/centreon/lib/perl/reporting/CentreonDashboard.pm b/centreon/lib/perl/reporting/CentreonDashboard.pm new file mode 100644 index 00000000000..f22d0a05da8 --- /dev/null +++ b/centreon/lib/perl/reporting/CentreonDashboard.pm @@ -0,0 +1,176 @@ + +use strict; +use warnings; + +package reporting::CentreonDashboard; + +use POSIX; +use Getopt::Long; +use Time::Local; + +# Constructor +# parameters: +# $logger: instance of class CentreonLogger +# $centreon: Instance of centreonDB class for connection to Centreon database +# $centstorage: (optionnal) Instance of centreonDB class for connection to Centstorage database +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"centstorage"} = shift; + bless $self, $class; + return $self; +} + +# returns two references to two hash tables => hosts indexed by id and hosts indexed by name +sub insertHostStats { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + my $names = shift; + my $stateDurations = shift; + my $start = shift; + my $end = shift; + my $dayDuration = $end - $start; + my $query_start = "INSERT INTO `log_archive_host` (`host_id`,". + " `UPTimeScheduled`,". + " `DOWNTimeScheduled`,". + " `UNREACHABLETimeScheduled`,". + " `MaintenanceTime`,". + " `UNDETERMINEDTimeScheduled`,". + " `UPnbEvent`,". + " `DOWNnbEvent`,". + " `UNREACHABLEnbEvent`,". + " `date_start`, `date_end`) VALUES "; + my $query_end = ""; + my $firstHost = 1; + my $count = 0; + my $sth; + while (my ($key, $value) = each %$names) { + if ($firstHost == 1) { + $firstHost = 0; + } else { + $query_end .= ","; + } + $query_end .= "(".$key.","; + if (defined($stateDurations->{$key})) { + my $stats = $stateDurations->{$key}; + my @tab = @$stats; + foreach(@tab) { + $query_end .= $_.","; + } + $query_end .= $start.",".$end.")"; + } else { + $query_end .= "0,0,0,0,".$dayDuration.",0,0,0,".$start.",".$end.")"; + } + $count++; + if ($count == 5000) { + $sth = $centstorage->query($query_start.$query_end); + $firstHost = 1; + $query_end = ""; + $count = 0; + } + } + if ($count) { + $sth = $centstorage->query($query_start.$query_end); + } +} + +# +sub insertServiceStats { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + my $names = shift; + my $stateDurations = shift; + my $start = shift; + my $end = shift; + my $dayDuration = $end - $start; + my $query_start = "INSERT INTO `log_archive_service` (`host_id`, `service_id`,". + " `OKTimeScheduled`,". + " `WARNINGTimeScheduled`,". + " `CRITICALTimeScheduled`,". + " `UNKNOWNTimeScheduled`,". + " `MaintenanceTime`,". + " `UNDETERMINEDTimeScheduled`,". + " `OKnbEvent`,". + " `WARNINGnbEvent`,". + " `CRITICALnbEvent`,". + " `UNKNOWNnbEvent`,". + " `date_start`, `date_end`) VALUES "; + my $query_end = ""; + my $firstService = 1; + my $count = 0; + my $sth; + while (my ($key, $value) = each %$names) { + if ($firstService == 1) { + $firstService = 0; + } else { + $query_end .= ","; + } + my ($host_id, $service_id) = split(";;", $key); + $query_end .= "(".$host_id.",".$service_id.","; + if (defined($stateDurations->{$key})) { + my $stats = $stateDurations->{$key}; + my @tab = @$stats; + foreach(@tab) { + $query_end .= $_.","; + } + $query_end .= $start.",".$end.")"; + } else { + $query_end .= "0,0,0,0,0,".$dayDuration.",0,0,0,0,".$start.",".$end.")"; + } + $count++; + if ($count == 5000) { + $sth = $centstorage->query($query_start.$query_end); + $firstService = 1; + $query_end = ""; + $count = 0; + } + } + if ($count) { + $sth = $centstorage->query($query_start.$query_end); + } +} + +# Truncate service dashboard stats table +sub truncateServiceStats { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + + my $query = "TRUNCATE TABLE `log_archive_service`"; + $centstorage->query($query); +} + +# Truncate host dashboard stats table +sub truncateHostStats { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + + my $query = "TRUNCATE TABLE `log_archive_host`"; + $centstorage->query($query); +} + +# Delete service dashboard stats for a given period +sub deleteServiceStats { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + + my ($start, $end) = (shift, shift); + my ($day, $month, $year) = (localtime($end))[3,4,5]; + $end = mktime(0, 0, 0, $day + 1, $month, $year); + my $query = "DELETE FROM `log_archive_service` WHERE `date_start`>= ".$start." AND `date_end` <= ".$end; + $centstorage->query($query); +} + +# Delete host dashboard stats for a given period +sub deleteHostStats { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + + my ($start, $end) = (shift, shift); + my ($day, $month, $year) = (localtime($end))[3,4,5]; + $end = mktime(0, 0, 0, $day + 1, $month, $year); + my $query = "DELETE FROM `log_archive_host` WHERE `date_start`>= ".$start." AND `date_end` <= ".$end; + $centstorage->query($query); +} + +1; diff --git a/centreon/lib/perl/reporting/CentreonDownTime.pm b/centreon/lib/perl/reporting/CentreonDownTime.pm new file mode 100644 index 00000000000..2415128fe3f --- /dev/null +++ b/centreon/lib/perl/reporting/CentreonDownTime.pm @@ -0,0 +1,222 @@ + +use strict; +use warnings; + +package reporting::CentreonDownTime; + +# Constructor +# parameters: +# $logger: instance of class CentreonLogger +# $centreon: Instance of centreonDB class for connection to Centreon database +# $dbLayer : Database Layer : ndo | broker +# $centstorage: (optionnal) Instance of centreonDB class for connection to Centstorage database +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"centstatus"} = shift; + $self->{'dbLayer'} = shift; + if (@_) { + $self->{"centstorage"} = shift; + } + bless $self, $class; + return $self; +} + +# returns two references to two hash tables => hosts indexed by id and hosts indexed by name +sub getDownTime { + my $self = shift; + my $centreon = $self->{"centstatus"}; + my $allIds = shift; + my $start = shift; + my $end = shift; + my $type = shift; # if 1 => host, if 2 => service + my $dbLayer = $self->{'dbLayer'}; + my $query; + + if ($dbLayer eq "ndo") { + $query = "SELECT `name1`, `name2`,". + " UNIX_TIMESTAMP(`scheduled_start_time`) as start_time,". + " UNIX_TIMESTAMP(`actual_end_time`) as end_time". + " FROM `nagios_downtimehistory` d, `nagios_objects` o". + " WHERE o.`object_id` = d.`object_id` AND o.`objecttype_id` = '".$type."'". + " AND was_started = 1". + " AND UNIX_TIMESTAMP(`scheduled_start_time`) < ".$end. + " AND (UNIX_TIMESTAMP(`actual_end_time`) > ".$start." || UNIX_TIMESTAMP(`actual_end_time`) = 0)". + " ORDER BY `name1` ASC, `scheduled_start_time` ASC, `actual_end_time` ASC"; + } elsif ($dbLayer eq "broker") { + $query = "SELECT DISTINCT h.name as name1, s.description as name2, " . + "d.start_time, d.end_time " . + "FROM `hosts` h, `downtimes` d " . + "LEFT JOIN services s ON s.service_id = d.service_id " . + "WHERE started = 1 " . + "AND d.host_id = h.host_id "; + if ($type == 1) { + $query .= "AND d.type = 2 "; # That can be confusing, but downtime_type 2 is for host + } elsif ($type == 2) { + $query .= "AND d.type = 1 "; # That can be confusing, but downtime_type 1 is for service + } + $query .= "AND start_time < " . $end . " " . + "AND (end_time > " . $start . " || end_time = 0) " . + "ORDER BY name1 ASC, start_time ASC, end_time ASC"; + } + + my $sth = $centreon->query($query); + + my @periods = (); + while (my $row = $sth->fetchrow_hashref()) { + my $id = $row->{"name1"}; + if ($type == 2) { + $id .= ";;".$row->{"name2"} + } + if (defined($allIds->{$id})) { + if ($row->{"start_time"} < $start) { + $row->{"start_time"} = $start; + } + if ($row->{"end_time"} > $end || $row->{"end_time"} == 0) { + $row->{"end_time"} = $end; + } + + my $insert = 1; + for (my $i = 0; $i < scalar(@periods) && $insert; $i++) { + my $checkTab = $periods[$i]; + if ($checkTab->[0] eq $allIds->{$id}){ + if ($row->{"start_time"} <= $checkTab->[2] && $row->{"end_time"} <= $checkTab->[2]) { + $insert = 0; + } elsif ($row->{"start_time"} <= $checkTab->[2] && $row->{"end_time"} > $checkTab->[2]) { + $checkTab->[2] = $row->{"end_time"}; + $periods[$i] = $checkTab; + $insert = 0; + } + } + } + if ($insert) { + my @tab = ($allIds->{$id}, $row->{"start_time"}, $row->{"end_time"}); + $periods[scalar(@periods)] = \@tab; + } + } + } + $sth->finish(); + return (\@periods); +} + +sub splitInsertEventDownTime { + my $self = shift; + + my $objectId = shift; + my $start = shift; + my $end = shift; + my $downTimes = shift; + my $state = shift; + + my @events = (); + my $total = 0; + if ($state ne "" && defined($downTimes) && defined($state) && $state != 0) { + $total = scalar(@$downTimes); + } + for (my $i = 0; $i < $total && $start < $end; $i++) { + my $tab = $downTimes->[$i]; + my $id = $tab->[0]; + my $downTimeStart = $tab->[1]; + my $downTimeEnd = $tab->[2]; + + if ($id eq $objectId) { + if ($downTimeStart < $start) { + $downTimeStart = $start; + } + if ($downTimeEnd > $end) { + $downTimeEnd = $end; + } + if ($downTimeStart < $end && $downTimeEnd > $start) { + if ($downTimeStart > $start) { + my @tab = ($start, $downTimeStart, 0); + $events[scalar(@events)] = \@tab; + } + my @tab = ($downTimeStart, $downTimeEnd, 1); + $events[scalar(@events)] = \@tab; + $start = $downTimeEnd; + } + } + } + if ($start < $end) { + my @tab = ($start, $end, 0); + $events[scalar(@events)] = \@tab; + } + return (\@events); +} + +sub splitUpdateEventDownTime { + my $self = shift; + + my $objectId = shift; + my $start = shift; + my $end = shift; + my $downTimeFlag = shift; + my $downTimes = shift; + my $state = shift; + + my $updated = 0; + my @events = (); + my $updateTime = 0; + my $total = 0; + if (defined($downTimes) && $state != 0) { + $total = scalar(@$downTimes); + } + for (my $i = 0; $i < $total && $start < $end; $i++) { + my $tab = $downTimes->[$i]; + my $id = $tab->[0]; + my $downTimeStart = $tab->[1]; + my $downTimeEnd = $tab->[2]; + + if ($id eq $objectId) { + if ($downTimeStart < $start) { + $downTimeStart = $start; + } + if ($downTimeEnd > $end) { + $downTimeEnd = $end; + } + if ($downTimeStart < $end && $downTimeEnd > $start) { + if ($updated == 0) { + $updated = 1; + if ($downTimeStart > $start) { + if ($downTimeFlag == 1) { + my @tab = ($start, $downTimeStart, 0); + $events[scalar(@events)] = \@tab; + }else { + $updateTime = $downTimeStart; + } + my @tab = ($downTimeStart, $downTimeEnd, 1); + $events[scalar(@events)] = \@tab; + }else { + if ($downTimeFlag == 1) { + $updateTime = $downTimeEnd; + }else { + my @tab = ($downTimeStart, $downTimeEnd, 1); + $events[scalar(@events)] = \@tab; + } + } + }else { + if ($downTimeStart > $start) { + my @tab = ($start, $downTimeStart, 0); + $events[scalar(@events)] = \@tab; + } + my @tab = ($downTimeStart, $downTimeEnd, 1); + $events[scalar(@events)] = \@tab; + } + $start = $downTimeEnd; + } + } + } + if ($start < $end && scalar(@events)) { + my @tab = ($start, $end, 0); + $events[scalar(@events)] = \@tab; + } else { + $updateTime = $end; + if (scalar(@events) && $end > $events[0][0]) { + $updateTime = $events[0][0]; + } + } + return ($updateTime, \@events); +} + +1; \ No newline at end of file diff --git a/centreon/lib/perl/reporting/CentreonHost.pm b/centreon/lib/perl/reporting/CentreonHost.pm new file mode 100644 index 00000000000..a8c8b318918 --- /dev/null +++ b/centreon/lib/perl/reporting/CentreonHost.pm @@ -0,0 +1,63 @@ + +use strict; +use warnings; + +package reporting::CentreonHost; + +# Constructor +# parameters: +# $logger: instance of class CentreonLogger +# $centreon: Instance of centreonDB class for connection to Centreon database +# $centstorage: (optionnal) Instance of centreonDB class for connection to Centstorage database +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"centreon"} = shift; + if (@_) { + $self->{"centstorage"} = shift; + } + bless $self, $class; + return $self; +} + +# returns two references to two hash tables => hosts indexed by id and hosts indexed by name +sub getAllHosts { + my $self = shift; + my $centreon = $self->{"centreon"}; + my $activated = 1; + if (@_) { + $activated = 0; + } + my (%host_ids, %host_names); + + my $query = "SELECT `host_id`, `host_name`". + " FROM `host`". + " WHERE `host_register`='1'"; + if ($activated == 1) { + $query .= " AND `host_activate` ='1'"; + } + my $sth = $centreon->query($query); + while (my $row = $sth->fetchrow_hashref()) { + $host_ids{$row->{"host_name"}} = $row->{"host_id"}; + $host_names{$row->{"host_id"}} = $row->{"host_name"}; + } + $sth->finish(); + return (\%host_ids,\%host_names); +} + +# Get all hosts, keys are IDs +sub getAllHostsByID { + my $self = shift; + my ($host_ids, $host_names) = $self->getAllHosts(); + return ($host_ids); +} + +# Get all hosts, keys are names +sub getAllHostsByName { + my $self = shift; + my ($host_ids, $host_names) = $self->getAllHosts(); + return ($host_names); +} + +1; \ No newline at end of file diff --git a/centreon/lib/perl/reporting/CentreonHostStateEvents.pm b/centreon/lib/perl/reporting/CentreonHostStateEvents.pm new file mode 100644 index 00000000000..af301e74719 --- /dev/null +++ b/centreon/lib/perl/reporting/CentreonHostStateEvents.pm @@ -0,0 +1,202 @@ + +use strict; +use warnings; + +package reporting::CentreonHostStateEvents; + +# Constructor +# parameters: +# $logger: instance of class CentreonLogger +# $centreon: Instance of centreonDB class for connection to Centreon database +# $centstorage: (optionnal) Instance of centreonDB class for connection to Centstorage database +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"centstorage"} = shift; + $self->{"centreonAck"} = shift; + $self->{"centreonDownTime"} = shift; + bless $self, $class; + return $self; +} + +# Get events in given period +# Parameters: +# $start: period start +# $end: period end +sub getStateEventDurations { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + my $start = shift; + my $end = shift; + my %hosts; + my $query = "SELECT `host_id`, `state`, `start_time`, `end_time`, `in_downtime`". + " FROM `hoststateevents`". + " WHERE `start_time` < ".$end. + " AND `end_time` > ".$start. + " AND `state` < 3"; # STATE PENDING AND UNKNOWN NOT HANDLED + my $sth = $centstorage->query($query); + while (my $row = $sth->fetchrow_hashref()) { + if ($row->{"start_time"} < $start) { + $row->{"start_time"} = $start; + } + if ($row->{"end_time"} > $end) { + $row->{"end_time"} = $end; + } + if (!defined($hosts{$row->{"host_id"}})) { + my @tab = (0, 0, 0, 0, 0, 0, 0, 0); + # index 0: UP, index 1: DOWN, index 2: UNREACHABLE, index 3: DOWNTIME, index 4: UNDETERMINED + # index 5: UP alerts, index 6: Down alerts, , index 7: Unreachable alerts + $hosts{$row->{"host_id"}} = \@tab; + } + + my $stats = $hosts{$row->{"host_id"}}; + if ($row->{"in_downtime"} == 0) { + $stats->[$row->{"state"}] += $row->{"end_time"} - $row->{"start_time"}; + $stats->[$row->{"state"} + 5] += 1; + }else { + $stats->[3] += $row->{"end_time"} - $row->{"start_time"}; + } + $hosts{$row->{"host_id"}} = $stats; + } + my %results; + while (my ($key, $value) = each %hosts) { + $value->[4] = ($end - $start) - ($value->[0] + $value->[1] + $value->[2] + $value->[3]); + $results{$key} = $value; + } + return (\%results); +} + +# Get last events for each host +# Parameters: +# $start: max date possible for each event +# $serviceNames: references a hash table containing a list of host +sub getLastStates { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + my $hostNames = shift; + + my %currentStates; + + my $query = "SELECT `host_id`, `state`, `hoststateevent_id`, `end_time`, `in_downtime`". + " FROM `hoststateevents`". + " WHERE `last_update` = 1"; + my $sth = $centstorage->query($query); + while(my $row = $sth->fetchrow_hashref()) { + if (defined($hostNames->{$row->{'host_id'}})) { + my @tab = ($row->{'end_time'}, $row->{'state'}, $row->{'hoststateevent_id'}, $row->{'in_downtime'}); + $currentStates{$hostNames->{$row->{'host_id'}}} = \@tab; + } + } + $sth->finish(); + + return (\%currentStates); +} + +# update a specific host incident end time +# Parameters +# $endTime: incident end time +# $eventId: ID of event to update +sub updateEventEndTime { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + my $centreonDownTime = $self->{"centreonDownTime"}; + my $centreonAck = $self->{"centreonAck"}; + + my ($id, $hostId, $start, $end, $state, $eventId, $downTimeFlag, $lastUpdate, $downTime) = (shift, shift, shift, shift, shift, shift, shift, shift, shift); + + my ($events, $updateTime); + ($updateTime, $events) = $centreonDownTime->splitUpdateEventDownTime($hostId, $start, $end, $downTimeFlag,$downTime, $state); + + my $totalEvents = 0; + if (defined($events)) { + $totalEvents = scalar(@$events); + } + my $ack = $centreonAck->getHostAckTime($start, $updateTime, $id); + if (!$totalEvents && $updateTime) { + my $query = "UPDATE `hoststateevents` SET `end_time` = ".$updateTime.", `ack_time`=".$ack.", `last_update`=".$lastUpdate. + " WHERE `hoststateevent_id` = ".$eventId; + $centstorage->query($query); + }else { + if ($updateTime) { + my $query = "UPDATE `hoststateevents` SET `end_time` = ".$updateTime.", `ack_time`=".$ack.", `last_update`= 0". + " WHERE `hoststateevent_id` = ".$eventId; + $centstorage->query($query); + } + $self->insertEventTable($id, $hostId, $state, $lastUpdate, $events); + } +} + +# insert a new incident for host +# Parameters +# $hostId : host ID +# $serviceId: service ID +# $state: incident state +# $start: incident start time +# $end: incident end time +sub insertEvent { + my $self = shift; + my $centreonDownTime = $self->{"centreonDownTime"}; + + my ($id, $hostId, $state, $start, $end, $lastUpdate, $downTime) = (shift, shift, shift, shift, shift, shift, shift); + + my $events = $centreonDownTime->splitInsertEventDownTime($hostId, $start, $end, $downTime, $state); + if ($state ne "") { + $self->insertEventTable($id, $hostId, $state, $lastUpdate, $events); + } +} + +sub insertEventTable { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + my $centreonAck = $self->{"centreonAck"}; + + my ($id, $hostId, $state, $lastUpdate, $events) = (shift, shift, shift, shift, shift); + + my $query_start = "INSERT INTO `hoststateevents`". + " (`host_id`, `state`, `start_time`, `end_time`, `last_update`, `in_downtime`, `ack_time`)". + " VALUES ("; + my $count = 0; + my $totalEvents = 0; + + for($count = 0; $count < scalar(@$events) - 1; $count++) { + my $tab = $events->[$count]; + my $ack = $centreonAck->getHostAckTime($tab->[0], $tab->[1], $id); + my $query_end = $hostId.", ".$state.", ".$tab->[0].", ".$tab->[1].", 0, ".$tab->[2].", ".$ack.")"; + $centstorage->query($query_start.$query_end); + } + if (scalar(@$events)) { + my $tab = $events->[$count]; + if (defined($hostId) && defined($state)) { + my $ack = $centreonAck->getHostAckTime($tab->[0], $tab->[1], $id); + my $query_end = $hostId.", ".$state.", ".$tab->[0].", ".$tab->[1].", ".$lastUpdate.", ".$tab->[2].", ".$ack.")"; + $centstorage->query($query_start.$query_end); + } + } +} + +# Truncate service incident table +sub truncateStateEvents { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + + my $query = "TRUNCATE TABLE `hoststateevents`"; + $centstorage->query($query); +} + +# Get first and last events date +sub getFirstLastIncidentTimes { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + + my $query = "SELECT min(`start_time`) as minc, max(`end_time`) as maxc FROM `hoststateevents`"; + my $sth = $centstorage->query($query); + my ($start, $end) = (0,0); + if (my $row = $sth->fetchrow_hashref()) { + ($start, $end) = ($row->{"minc"}, $row->{"maxc"}); + } + $sth->finish; + return ($start, $end); +} + +1; \ No newline at end of file diff --git a/centreon/lib/perl/reporting/CentreonLog.pm b/centreon/lib/perl/reporting/CentreonLog.pm new file mode 100644 index 00000000000..b122af34ba1 --- /dev/null +++ b/centreon/lib/perl/reporting/CentreonLog.pm @@ -0,0 +1,117 @@ + +use strict; +use warnings; + +package reporting::CentreonLog; + +# Constructor +# parameters: +# $logger: instance of class CentreonLogger +# $centreon: Instance of centreonDB class for connection to Centreon database +# $centstorage: (optionnal) Instance of centreonDB class for connection to Centstorage database +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"centstorage"} = shift; + $self->{"dbLayer"} = shift; + if (@_) { + $self->{"centreon"} = shift; + } + bless $self, $class; + return $self; +} + +# Get all service logs between two dates +# Parameters: +# $start: period start date in timestamp +# $end: period start date in timestamp +sub getLogOfServices { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + my ($start, $end); + if (@_) { + $start = shift; + $end = shift; + } + my $query; + if ($self->{'dbLayer'} eq "ndo") { + $query = "SELECT `status`, `ctime`, `host_name`, `service_description`". + " FROM `log`". + " WHERE `ctime` >= ".$start. + " AND `ctime` < ".$end. + " AND (`type` = 'HARD' OR (`status` = 'OK' AND `type` = 'SOFT'))". + " AND `service_description` IS NOT null". + " AND `msg_type` IN ('0', '1', '6', '7', '8', '9')". + " ORDER BY `ctime`"; + } elsif($self->{'dbLayer'} eq "broker") { + $query = "SELECT `status`, `ctime`, `host_name`, `service_description`". + " FROM `logs`". + " WHERE `ctime` >= ".$start. + " AND `ctime` < ".$end. + " AND (`type` = 1 OR (`status` = 0 AND `type` = 0))". + " AND `service_description` IS NOT null". + " AND `msg_type` IN ('0', '1', '6', '7', '8', '9')". + " ORDER BY `ctime`"; + } + my $result = $centstorage->query($query); + return $result; +} + +# Get all hosts logs between two dates +# Parameters: +# $start: period start date in timestamp +# $end: period start date in timestamp +sub getLogOfHosts { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + my ($start, $end); + if (@_) { + $start = shift; + $end = shift; + } + my $query; + if ($self->{'dbLayer'} eq "ndo") { + $query = "SELECT `status`, `ctime`, `host_name`". + " FROM `log`". + " WHERE `ctime` >= ".$start. + " AND `ctime` < ".$end. + " AND (`type` = 'HARD' OR (`status` = 'UP' AND `type` = 'SOFT'))". + " AND `msg_type` IN ('0', '1', '6', '7', '8', '9')". + " AND `service_description` IS NULL". + " ORDER BY `ctime`"; + } elsif ($self->{'dbLayer'} eq "broker") { + $query = "SELECT `status`, `ctime`, `host_name`". + " FROM `logs`". + " WHERE `ctime` >= ".$start. + " AND `ctime` < ".$end. + " AND (`type` = 1 OR (`status` = 0 AND `type` = 0))". + " AND `msg_type` IN ('0', '1', '6', '7', '8', '9')". + " AND `service_id` IS NULL". + " ORDER BY `ctime`"; + } + my $result = $centstorage->query($query); + return $result; +} + +# Get First log date and last log date +sub getFirstLastLogTime { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + + my $query; + if ($self->{'dbLayer'} eq "ndo") { + $query = "SELECT min(`ctime`) as minc, max(`ctime`) as maxc FROM `log`"; + } elsif ($self->{'dbLayer'} eq "broker") { + $query = "SELECT min(`ctime`) as minc, max(`ctime`) as maxc FROM `logs`"; + } + my $sth = $centstorage->query($query); + my ($start, $end) = (0,0); + if (my $row = $sth->fetchrow_hashref()) { + ($start, $end) = ($row->{"minc"}, $row->{"maxc"}); + } + $sth->finish; + return ($start, $end); +} + +1; \ No newline at end of file diff --git a/centreon/lib/perl/reporting/CentreonProcessStateEvents.pm b/centreon/lib/perl/reporting/CentreonProcessStateEvents.pm new file mode 100644 index 00000000000..aa14f7526a2 --- /dev/null +++ b/centreon/lib/perl/reporting/CentreonProcessStateEvents.pm @@ -0,0 +1,179 @@ + +use strict; +use warnings; + +package reporting::CentreonProcessStateEvents; + +#use vars qw (%serviceStates %hostStates %servicStateIds %hostStateIds); +#require "/home/msugumaran/merethis/centreon-bi-server/centreon/cron/perl-modules/variables.pm"; + +# Constructor +# parameters: +# $logger: instance of class CentreonLogger +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"host"} = shift; + $self->{"service"} = shift; + $self->{"nagiosLog"} = shift; + $self->{"hostEvents"} = shift; + $self->{"serviceEvents"} = shift; + $self->{"centreonDownTime"} = shift; + $self->{"dbLayer"} = shift; + bless $self, $class; + + return $self; +} + +# Parse services logs for given period +# Parameters: +# $start: period start +# $end: period end +sub parseServiceLog { + my $self = shift; + # parameters: + my ($start ,$end) = (shift,shift); + my %serviceStates = ("OK" => 0, "WARNING" => 1, "CRITICAL" => 2, "UNKNOWN" => 3, "PENDING" => 4); + my $service = $self->{"service"}; + my $nagiosLog = $self->{"nagiosLog"}; + my $events = $self->{"serviceEvents"}; + my $centreonDownTime = $self->{"centreonDownTime"}; + + my ($allIds, $allNames) = $service->getAllServices(); + my $currentEvents = $events->getLastStates($allNames); + my $logs = $nagiosLog->getLogOfServices($start, $end); + my $downTime = $centreonDownTime->getDownTime($allIds, $start, $end, 2); + + while(my $row = $logs->fetchrow_hashref()) { + my $id = $row->{'host_name'}.";;".$row->{'service_description'}; + if (defined($allIds->{$id})) { + my $statusCode = $row->{'status'}; + if ($self->{'dbLayer'} eq "ndo") { + $statusCode = $serviceStates{$row->{'status'}}; + } + if (defined($currentEvents->{$id})) { + my $eventInfos = $currentEvents->{$id}; # $eventInfos is a reference to a table containing : incident start time | status | state_event_id | in_downtime. The last one is optionnal + if ($statusCode ne "" && defined($eventInfos->[1]) && $eventInfos->[1] ne "" && $eventInfos->[1] != $statusCode) { + my ($hostId, $serviceId) = split (";;", $allIds->{$id}); + if ($eventInfos->[2] != 0) { + # If eventId of log is defined, update the last day event + $events->updateEventEndTime($id, $hostId, $serviceId, $eventInfos->[0], $row->{'ctime'}, $eventInfos->[1], $eventInfos->[2], $eventInfos->[3], 0, $downTime); + }else { + if ($row->{'ctime'} > $eventInfos->[0]) { + $events->insertEvent($id, $hostId, $serviceId, $eventInfos->[1], $eventInfos->[0], $row->{'ctime'}, 0, $downTime); + } + } + $eventInfos->[0] = $row->{'ctime'}; + $eventInfos->[1] = $statusCode; + $eventInfos->[2] = 0; + $eventInfos->[3] = 0; + $currentEvents->{$id} = $eventInfos; + } + } else { + my @tab; + @tab = ($row->{'ctime'}, $statusCode, 0, 0); + $currentEvents->{$id} = \@tab; + } + + } + } + + $self->insertLastServiceEvents($end, $currentEvents, $allIds, $downTime); +} + +# Parse host logs for given period +# Parameters: +# $start: period start +# $end: period end +sub parseHostLog { + my $self = shift; + # parameters: + my ($start ,$end) = (shift,shift); + my %hostStates = ("UP" => 0, "DOWN" => 1, "UNREACHABLE" => 2, "UNKNOWN" => 3, "PENDING" => 4); + my $host = $self->{"host"}; + my $nagiosLog = $self->{"nagiosLog"}; + my $events = $self->{"hostEvents"}; + my $centreonDownTime = $self->{"centreonDownTime"}; + + my ($allIds, $allNames) = $host->getAllHosts(); + my $currentEvents = $events->getLastStates($allNames); + my $logs = $nagiosLog->getLogOfHosts($start, $end); + my $downTime = $centreonDownTime->getDownTime($allIds, $start, $end, 1); + + while(my $row = $logs->fetchrow_hashref()) { + my $id = $row->{'host_name'}; + if (defined($allIds->{$id})) { + my $statusCode = $row->{'status'}; + if ($self->{'dbLayer'} eq "ndo") { + $statusCode = $hostStates{$row->{'status'}}; + } + if (defined($currentEvents->{$id})) { + my $eventInfos = $currentEvents->{$id}; # $eventInfos is a reference to a table containing : incident start time | status | state_event_id. The last one is optionnal + if ($statusCode ne "" && defined($eventInfos->[1]) && $eventInfos->[1] ne "" && $eventInfos->[1] != $statusCode) { + if ($eventInfos->[2] != 0) { + # If eventId of log is defined, update the last day event + $events->updateEventEndTime($id, $allIds->{$id}, $eventInfos->[0], $row->{'ctime'}, $eventInfos->[1], $eventInfos->[2],$eventInfos->[3], 0, $downTime); + }else { + if ($row->{'ctime'} > $eventInfos->[0]) { + $events->insertEvent($id, $allIds->{$id}, $eventInfos->[1], $eventInfos->[0], $row->{'ctime'}, 0, $downTime); + } + } + $eventInfos->[0] = $row->{'ctime'}; + $eventInfos->[1] = $statusCode; + $eventInfos->[2] = 0; + $eventInfos->[3] = 0; + $currentEvents->{$id} = $eventInfos; + } + }else { + my @tab = ($row->{'ctime'}, $statusCode, 0, 0); + $currentEvents->{$id} = \@tab; + } + } + } + $self->insertLastHostEvents($end, $currentEvents, $allIds, $downTime); +} + + +# Insert in DB last service incident of day currently processed +# Parameters: +# $end: period end +# $currentEvents: reference to a hash table that contains last incident details +# $allIds: reference to a hash table that returns host/service ids for host/service names +sub insertLastServiceEvents { + my $self = shift; + my $events = $self->{"serviceEvents"}; + # parameters: + my ($end,$currentEvents, $allIds, $downTime) = (shift, shift, shift, shift); + + while(my ($id, $eventInfos) = each (%$currentEvents)) { + my ($hostId, $serviceId) = split (";;", $allIds->{$id}); + if ($eventInfos->[2] != 0) { + $events->updateEventEndTime($id, $hostId, $serviceId, $eventInfos->[0], $end, $eventInfos->[1], $eventInfos->[2], $eventInfos->[3], 1, $downTime); + }else { + $events->insertEvent($id, $hostId, $serviceId, $eventInfos->[1], $eventInfos->[0], $end, 1, $downTime); + } + } +} + +# Insert in DB last host incident of day currently processed +# Parameters: +# $end: period end +# $currentEvents: reference to a hash table that contains last incident details +# $allIds: reference to a hash table that returns host ids for host names +sub insertLastHostEvents { + my $self = shift; + my $events = $self->{"hostEvents"}; + # parameters: + my ($end, $currentEvents, $allIds, $downTime) = (shift, shift, shift, shift, shift); + + while(my ($id, $eventInfos) = each (%$currentEvents)) { + if ($eventInfos->[2] != 0) { + $events->updateEventEndTime($id, $allIds->{$id}, $eventInfos->[0], $end, $eventInfos->[1], $eventInfos->[2], $eventInfos->[3], 1, $downTime); + }else { + $events->insertEvent($id, $allIds->{$id}, $eventInfos->[1], $eventInfos->[0], $end, 1, $downTime); + } + } +} + +1; \ No newline at end of file diff --git a/centreon/lib/perl/reporting/CentreonService.pm b/centreon/lib/perl/reporting/CentreonService.pm new file mode 100644 index 00000000000..8929a2834b7 --- /dev/null +++ b/centreon/lib/perl/reporting/CentreonService.pm @@ -0,0 +1,86 @@ + +use strict; +use warnings; + +package reporting::CentreonService; + +# Constructor +# parameters: +# $logger: instance of class CentreonLogger +# $centreon: Instance of centreonDB class for connection to Centreon database +# $centstorage: (optionnal) Instance of centreonDB class for connection to Centstorage database +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"centreon"} = shift; + if (@_) { + $self->{"centstorage"} = shift; + } + bless $self, $class; + return $self; +} + +# returns two references to two hash tables => services indexed by id and services indexed by name +sub getAllServices { + my $self = shift; + my $centreon = $self->{"centreon"}; + my $activated = 1; + if (@_) { + $activated = 0; + } + + my (%service_ids, %service_names); + # getting services linked to hosts + my $query = "SELECT service_description, service_id, host_id, host_name". + " FROM host, service, host_service_relation". + " WHERE host_id = host_host_id and service_service_id = service_id". + " AND service_register = '1'"; + if ($activated == 1) { + $query .= " AND `service_activate`='1'"; + } + my $sth = $centreon->query($query); + while(my $row = $sth->fetchrow_hashref()) { + $service_ids{$row->{'host_name'}.";;".$row->{'service_description'}} = $row->{'host_id'}.";;".$row->{'service_id'}; + $service_names{$row->{'host_id'}.";;".$row->{'service_id'}} = $row->{'host_name'}.";;".$row->{'service_description'}; + } + #getting services linked to hostgroup + $query = "SELECT service_description, service_id, host_id, host_name". + " FROM host, service, host_service_relation hr, hostgroup_relation hgr, hostgroup hg". + " WHERE hr.hostgroup_hg_id is not null". + " AND hr.service_service_id = service_id". + " AND hr.hostgroup_hg_id = hgr.hostgroup_hg_id". + " AND hgr.host_host_id = host_id". + " AND service_register = '1'"; + if ($activated == 1) { + $query .= " AND service_activate='1'". + " AND host_activate = '1'". + " AND hg.hg_activate = '1'"; + } + $query .= " AND hg.hg_id = hgr.hostgroup_hg_id"; + + $sth = $centreon->query($query); + while(my $row = $sth->fetchrow_hashref()) { + $service_ids{$row->{'host_name'}.";;".$row->{'service_description'}} = $row->{'host_id'}.";;".$row->{'service_id'}; + $service_names{$row->{'host_id'}.";;".$row->{'service_id'}} = $row->{'host_name'}.";;".$row->{'service_description'}; + } + $sth->finish(); + + return (\%service_ids, \%service_names); +} + +# Get all services, keys are IDs +sub getAllServicesByID { + my $self = shift; + my ($service_ids, $service_names) = $self->getAllServices(); + return ($service_ids); +} + +# Get all services, keys are names +sub getAllservicesByName { + my $self = shift; + my ($service_ids, $service_names) = $self->getAllServices(); + return ($service_names); +} + +1; \ No newline at end of file diff --git a/centreon/lib/perl/reporting/CentreonServiceStateEvents.pm b/centreon/lib/perl/reporting/CentreonServiceStateEvents.pm new file mode 100644 index 00000000000..111aae19610 --- /dev/null +++ b/centreon/lib/perl/reporting/CentreonServiceStateEvents.pm @@ -0,0 +1,203 @@ + +use strict; +use warnings; + +package reporting::CentreonServiceStateEvents; + +# Constructor +# parameters: +# $logger: instance of class CentreonLogger +# $centreon: Instance of centreonDB class for connection to Centreon database +# $centstorage: (optionnal) Instance of centreonDB class for connection to Centstorage database +sub new { + my $class = shift; + my $self = {}; + $self->{"logger"} = shift; + $self->{"centstorage"} = shift; + $self->{"centreonAck"} = shift; + $self->{"centreonDownTime"} = shift; + bless $self, $class; + return $self; +} + +# Get events in given period +# Parameters: +# $start: period start +# $end: period end +sub getStateEventDurations { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + my $start = shift; + my $end = shift; + + my %services; + my $query = "SELECT `host_id`, `service_id`, `state`, `start_time`, `end_time`, `in_downtime`". + " FROM `servicestateevents`". + " WHERE `start_time` < ".$end. + " AND `end_time` > ".$start. + " AND `state` < 4"; # NOT HANDLING PENDING STATE + my $sth = $centstorage->query($query); + while (my $row = $sth->fetchrow_hashref()) { + if ($row->{"start_time"} < $start) { + $row->{"start_time"} = $start; + } + if ($row->{"end_time"} > $end) { + $row->{"end_time"} = $end; + } + if (!defined($services{$row->{"host_id"}.";;".$row->{"service_id"}})) { + my @tab = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + # index 0: OK, index 1: WARNING, index 2: CRITICAL, index 3: UNKNOWN, index 4: DOWNTIME, index 5: UNDETERMINED + # index 6: OK alerts, index 7: WARNING alerts, index 8: CRITICAL alerts, index 9: UNKNOWN alerts + $services{$row->{"host_id"}.";;".$row->{"service_id"}} = \@tab; + } + + my $stats = $services{$row->{"host_id"}.";;".$row->{"service_id"}}; + if ($row->{"in_downtime"} == 0) { + $stats->[$row->{"state"}] += $row->{"end_time"} - $row->{"start_time"}; + $stats->[$row->{"state"} + 6] += 1; + }else { + $stats->[4] += $row->{"end_time"} - $row->{"start_time"}; + } + $services{$row->{"host_id"}.";;".$row->{"service_id"}} = $stats; + } + my %results; + while (my ($key, $value) = each %services) { + $value->[5] = ($end - $start) - ($value->[0] + $value->[1] + $value->[2] + $value->[3] + $value->[4]); + $results{$key} = $value; + } + return (\%results); +} + + +# Get last events for each service +# Parameters: +# $start: max date possible for each event +# $serviceNames: references a hash table containing a list of services +sub getLastStates { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + + my $serviceNames = shift; + + my $currentStates = {}; + + my $query = "SELECT `host_id`, `service_id`, `state`, `servicestateevent_id`, `end_time`, `in_downtime`". + " FROM `servicestateevents`". + " WHERE `last_update` = 1"; + my $sth = $centstorage->query($query); + while(my $row = $sth->fetchrow_hashref()) { + my $serviceId = $row->{'host_id'}.";;".$row->{'service_id'}; + if (defined($serviceNames->{$serviceId})) { + my @tab = ($row->{'end_time'}, $row->{'state'}, $row->{'servicestateevent_id'}, $row->{'in_downtime'}); + $currentStates->{$serviceNames->{$serviceId}} = \@tab; + } + } + $sth->finish(); + + return ($currentStates); +} + +# update a specific service incident end time +# Parameters +# $endTime: incident end time +# $eventId: ID of event to update +sub updateEventEndTime { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + my $centstatus = $self->{"centstatus"}; + my $centreonAck = $self->{"centreonAck"}; + my $centreonDownTime = $self->{"centreonDownTime"}; + my ($id, $hostId, $serviceId, $start, $end, $state, $eventId, $downTimeFlag, $lastUpdate, $downTime) = (shift, shift, shift, shift, shift, shift, shift, shift, shift, shift); + + my ($hostName, $serviceDescription) = split (";;", $id); + my ($events, $updateTime); + ($updateTime, $events) = $centreonDownTime->splitUpdateEventDownTime($hostId.";;".$serviceId, $start, $end, $downTimeFlag, $downTime, $state); + my $totalEvents = 0; + if (defined($events)) { + $totalEvents = scalar(@$events); + } + my $ack = $centreonAck->getServiceAckTime($start, $updateTime, $hostName, $serviceDescription); + if (!$totalEvents && $updateTime) { + my $query = "UPDATE `servicestateevents` SET `end_time` = ".$updateTime.", `ack_time`=".$ack.", `last_update`=".$lastUpdate. + " WHERE `servicestateevent_id` = ".$eventId; + $centstorage->query($query); + }else { + if ($updateTime) { + my $query = "UPDATE `servicestateevents` SET `end_time` = ".$updateTime.", `ack_time`=".$ack.", `last_update`= 0". + " WHERE `servicestateevent_id` = ".$eventId; + $centstorage->query($query); + } + $self->insertEventTable($id, $hostId, $serviceId, $state, $lastUpdate, $events); + } +} + +# insert a new incident for service +# Parameters +# $hostId : host ID +# $serviceId: service ID +# $state: incident state +# $start: incident start time +# $end: incident end time +sub insertEvent { + my $self = shift; + my $centreonDownTime = $self->{"centreonDownTime"}; + my ($id, $hostId, $serviceId, $state, $start, $end, $lastUpdate, $downTime) = (shift, shift, shift, shift, shift, shift, shift, shift); + my $events = $centreonDownTime->splitInsertEventDownTime($hostId.";;".$serviceId, $start, $end, $downTime, $state); + if ($state ne "") { + $self->insertEventTable($id, $hostId, $serviceId, $state, $lastUpdate, $events); + } +} + +sub insertEventTable { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + my $centreonAck = $self->{"centreonAck"}; + my ($id, $hostId, $serviceId, $state, $lastUpdate, $events) = (shift, shift, shift, shift, shift, shift); + + my $query_start = "INSERT INTO `servicestateevents`". + " (`host_id`, `service_id`, `state`, `start_time`, `end_time`, `last_update`, `in_downtime`, `ack_time`)". + " VALUES ("; + + my $count = 0; + my ($hostName, $serviceDescription) = split (";;", $id); + for($count = 0; $count < scalar(@$events) - 1; $count++) { + my $tab = $events->[$count]; + my $ack = $centreonAck->getServiceAckTime($tab->[0], $tab->[1], $hostName, $serviceDescription); + my $query_end = $hostId.", ".$serviceId.", ".$state.", ".$tab->[0].", ".$tab->[1].", 0, ".$tab->[2].", ".$ack.")"; + $centstorage->query($query_start.$query_end); + } + if (scalar(@$events)) { + my $tab = $events->[$count]; + if (defined($hostId) && defined($serviceId) && defined($state)) { + my $ack = $centreonAck->getServiceAckTime($tab->[0], $tab->[1], $hostName, $serviceDescription); + my $query_end = $hostId.", ".$serviceId.", ".$state.", ".$tab->[0].", ".$tab->[1].", ".$lastUpdate.", ".$tab->[2].", ".$ack.")"; + $centstorage->query($query_start.$query_end); + } + } +} + +# Truncate service incident table +sub truncateStateEvents { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + + my $query = "TRUNCATE TABLE `servicestateevents`"; + $centstorage->query($query); +} + +# Get first and last events date +sub getFirstLastIncidentTimes { + my $self = shift; + my $centstorage = $self->{"centstorage"}; + + my $query = "SELECT min(`start_time`) as minc, max(`end_time`) as maxc FROM `servicestateevents`"; + my $sth = $centstorage->query($query); + my ($start, $end) = (0,0); + if (my $row = $sth->fetchrow_hashref()) { + ($start, $end) = ($row->{"minc"}, $row->{"maxc"}); + } + $sth->finish; + return ($start, $end); +} + +1; \ No newline at end of file From f6e0632ed7df79af8206dac42142af58c380f6fa Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 20 Mar 2013 17:51:16 +0100 Subject: [PATCH 008/458] Step work on eventreportbuilder --- .../centreon/script/eventReportBuilder.pm | 192 ++++++++++++++++++ 1 file changed, 192 insertions(+) create mode 100644 centreon/lib/perl/centreon/script/eventReportBuilder.pm diff --git a/centreon/lib/perl/centreon/script/eventReportBuilder.pm b/centreon/lib/perl/centreon/script/eventReportBuilder.pm new file mode 100644 index 00000000000..daed573c29b --- /dev/null +++ b/centreon/lib/perl/centreon/script/eventReportBuilder.pm @@ -0,0 +1,192 @@ + +use warnings; +use strict; +use POSIX; +use Time::Local; + +use reporting::CentreonHost; +use reporting::CentreonService; +use reporting::CentreonLog; +use reporting::CentreonServiceStateEvents; +use reporting::CentreonHostStateEvents; +use reporting::CentreonProcessStateEvents; +use reporting::CentreonDownTime; +use reporting::CentreonAck; +use centreon::script; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("eventReportBuilder", + centreon_db_conn => 1, + centstorage_db_conn => 1 + ); + + bless $self, $class; + $self->add_options( + "r" => \$self->{opt_rebuild}, "rebuild" => \$self->{opt_rebuild}, + ); + $self->{centstatusdb} = undef; + $self->{processEvents} = undef; + $self->{serviceEvents} = undef; + $self->{hostEvents} = undef; + $self->{nagiosLog} = undef; + $self->{service} = undef; + $self->{host} = undef; + $self->{dbLayer} = undef; + return $self; +} + +# program exit function +sub exit_pgr() { + my $self = shift; + + $self->{logger}->writeLogInfo("INFO", "Exiting program..."); + exit (0); +} + +# get db layer +sub getDbLayer() { + my $self = shift; + + my $res = $self->{cdb}->query("SELECT `value` FROM `options` WHERE `key` = 'broker'"); + if (my $row = $res->fetchrow_hashref()) { + return $row->{'value'}; + } + return "ndo"; +} + +# function that checks if the log is already built +sub dayAlreadyProcessed($$$$) { + my $self = shift; + my ($day, $month, $year) = (shift, shift, shift); + + my $tmp_file = $varLibCentreon . "/archive-monitoring-incidents.last"; + my $last; + my $now; + my $write_cmd; + + $now = $day.$month.$year; + if (-e "$tmp_file") { + chomp($last = `cat $tmp_file`); + $write_cmd = `echo $now > $tmp_file`; + if ($now == $last) { + print "[".time."] Error : day already processed\n"; + return 1; + } + else { + return 0; + } + } + $write_cmd = `echo $now > $tmp_file`; + return 0; +} + +# Initialize objects for program +sub initVars { + my $self = shift; + + # Getting centstatus database name + $self->{dbLayer} = getDbLayer(); + if ($self->{dbLayer} eq "ndo") { + my $sth = $centreon->query("SELECT db_name, db_host, db_port, db_user, db_pass FROM cfg_ndo2db WHERE activate = '1' LIMIT 1"); + if (my $row = $sth->fetchrow_hashref()) { + #connecting to censtatus + $centstatus = CentreonDB->new($logger, $row->{"db_name"}, $row->{'db_host'}, $row->{'db_user'}, $row->{'db_pass'}, $row->{'db_port'}); + } + } elsif ($self->{dbLayer} eq "broker") { + $centstatus = $centstorage; + } else { + $self->{logger}->writeLogError("Unsupported database layer: " . $dbLayer); + $self->exit_pgr(); + } + + # classes to query database tables + $host = CentreonHost->new($logger, $centreon); + $service = CentreonService->new($logger, $centreon); + $nagiosLog = CentreonLog->new($logger, $centstorage, $dbLayer); + my $centreonDownTime = CentreonDownTime->new($logger, $centstatus, $dbLayer); + my $centreonAck = CentreonAck->new($logger, $centstatus, $dbLayer); + $serviceEvents = CentreonServiceStateEvents->new($logger, $centstorage, $centreonAck, $centreonDownTime); + $hostEvents = CentreonHostStateEvents->new($logger, $centstorage, $centreonAck, $centreonDownTime); + + # Class that builds events + $processEvents = CentreonProcessStateEvents->new($logger, $host, $service, $nagiosLog, $hostEvents, $serviceEvents, $centreonDownTime, $dbLayer); +} + +# For a given period returns in a table each +sub getDaysFromPeriod { + my ($start, $end) = (shift, shift); + + my @days; + # Check if $end is > to current time + my ($day,$month,$year) = (localtime(time))[3,4,5]; + my $today_begin = mktime(0,0,0,$day,$month,$year,0,0,-1); + if ($end > $today_begin) { + $end = $today_begin; + } + # get start day as mm/dd/yyyy 00:00 + ($day,$month,$year) = (localtime($start))[3,4,5]; + $start = mktime(0,0,0,$day,$month,$year,0,0,-1); + my $previousDay = mktime(0,0,0,$day - 1,$month,$year,0,0,-1); + + while ($start < $end) { + # getting day beginning => 00h 00min + # if there is few hour gap (time change : winter/summer), we also readjust it + if ($start == $previousDay) { + $start = mktime(0,0,0, ++$day, $month, $year,0,0,-1); + } + # setting day beginning/end hour and minute with the value set in centreon DB + my $dayEnd =mktime(0, 0, 0, ++$day, $month, $year, 0, 0, -1); + my %period = ("day_start" => $start, "day_end" => $dayEnd); + $days[scalar(@days)] = \%period; + + $previousDay = $start; + $start = $dayEnd; + } + return \@days; +} + +# rebuild all events +sub rebuildIncidents { + my $time_period = shift; + # Empty tables + $serviceEvents->truncateStateEvents(); + $hostEvents->truncateStateEvents(); + # Getting first log and last log times + my ($start, $end) = $nagiosLog->getFirstLastLogTime(); + my $periods = getDaysFromPeriod($start, $end); + # archiving logs for each days + foreach(@$periods) { + $self->{logger}->writeLogInfo("Processing period: ".localtime($_->{"day_start"})." => ".localtime($_->{"day_end"})); + $processEvents->parseHostLog($_->{"day_start"}, $_->{"day_end"}); + $processEvents->parseServiceLog($_->{"day_start"}, $_->{"day_end"}); + } +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + $self->{logger}->redirect_output(); + $self->initVars(); + + $self->{logger}->writeLogInfo("Starting program..."); + + if (defined($options{'rebuild'})) { + $self->rebuildIncidents(); + }else { + my $currentTime = time; + my ($day,$month,$year) = (localtime($currentTime))[3,4,5]; + my $end = mktime(0,0,0,$day,$month,$year,0,0,-1); + my $start = mktime(0,0,0,$day-1,$month,$year,0,0,-1); + $self->{logger}->writeLogInfo("Processing period: ".localtime($start)." => ".localtime($end)); + $processEvents->parseHostLog($start, $end); + $processEvents->parseServiceLog($start, $end); + } + + $self->exit_pgr(); +} + +1; From 125cfed7f68546f690fa06061ef5d1054ab166bd Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 31 May 2013 17:05:03 +0200 Subject: [PATCH 009/458] First work on cron reporting Conflicts: cron/perl-modules/CentreonAck.pm cron/perl-modules/CentreonDownTime.pm --- centreon/lib/perl/reporting/CentreonAck.pm | 5 +++-- centreon/lib/perl/reporting/CentreonDownTime.pm | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/reporting/CentreonAck.pm b/centreon/lib/perl/reporting/CentreonAck.pm index f5c3c967ea0..77ebb3cc729 100644 --- a/centreon/lib/perl/reporting/CentreonAck.pm +++ b/centreon/lib/perl/reporting/CentreonAck.pm @@ -39,8 +39,9 @@ sub getServiceAckTime { " FROM `nagios_acknowledgements` a, `nagios_objects` o". " WHERE o.`object_id` = a.`object_id`". " AND `acknowledgement_type` = '1'". - " AND UNIX_TIMESTAMP(`entry_time`) >= ".$start. - " AND UNIX_TIMESTAMP(`entry_time`) <= ".$end. + " AND `entry_time` >= FROM_UNIXTIME(".$start.")". + " AND `entry_time` <= FROM_UNIXTIME(".$end.")". + " AND objecttype_id = '2'". " AND o.`name1` = '".$hostName. "'". " AND o.`name2` = '".$serviceDescription. "'". " ORDER BY `entry_time` asc"; diff --git a/centreon/lib/perl/reporting/CentreonDownTime.pm b/centreon/lib/perl/reporting/CentreonDownTime.pm index 2415128fe3f..3a7c0c9d5c9 100644 --- a/centreon/lib/perl/reporting/CentreonDownTime.pm +++ b/centreon/lib/perl/reporting/CentreonDownTime.pm @@ -41,8 +41,8 @@ sub getDownTime { " FROM `nagios_downtimehistory` d, `nagios_objects` o". " WHERE o.`object_id` = d.`object_id` AND o.`objecttype_id` = '".$type."'". " AND was_started = 1". - " AND UNIX_TIMESTAMP(`scheduled_start_time`) < ".$end. - " AND (UNIX_TIMESTAMP(`actual_end_time`) > ".$start." || UNIX_TIMESTAMP(`actual_end_time`) = 0)". + " AND `scheduled_start_time` < FROM_UNIXTIME(".$end.")". + " AND (`actual_end_time` > FROM_UNIXTIME(".$start.") || `actual_end_time` = '0000-00-00')". " ORDER BY `name1` ASC, `scheduled_start_time` ASC, `actual_end_time` ASC"; } elsif ($dbLayer eq "broker") { $query = "SELECT DISTINCT h.name as name1, s.description as name2, " . From 7a2507fa0b4376ad1d29de835aa8bfa1a7bc3fab Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 21 Mar 2013 10:12:16 +0100 Subject: [PATCH 010/458] Mod directories --- .../centstorage/CentstorageAction.pm | 6 +- .../centstorage/CentstorageLib.pm | 2 +- .../centstorage/CentstoragePerfdataFile.pm | 4 +- .../centstorage/CentstoragePool.pm | 30 +++++----- .../centstorage/CentstorageRRD.pm | 2 +- .../centstorage/CentstorageRebuild.pm | 2 +- centreon/lib/perl/centreon/{ => common}/db.pm | 40 +------------ .../lib/perl/centreon/{ => common}/lock.pm | 10 ++-- .../lib/perl/centreon/{ => common}/logger.pm | 2 +- .../{ => centreon}/reporting/CentreonAck.pm | 2 +- .../reporting/CentreonDashboard.pm | 2 +- .../reporting/CentreonDownTime.pm | 2 +- .../{ => centreon}/reporting/CentreonHost.pm | 2 +- .../reporting/CentreonHostStateEvents.pm | 2 +- .../{ => centreon}/reporting/CentreonLog.pm | 2 +- .../reporting/CentreonProcessStateEvents.pm | 2 +- .../reporting/CentreonService.pm | 2 +- .../reporting/CentreonServiceStateEvents.pm | 2 +- centreon/lib/perl/centreon/script.pm | 14 ++--- .../lib/perl/centreon/script/centstorage.pm | 58 +++++++++---------- .../perl/centreon/script/centstorage_purge.pm | 4 +- .../centreon/script/eventReportBuilder.pm | 16 ++--- 22 files changed, 86 insertions(+), 122 deletions(-) rename centreon/lib/perl/{ => centreon}/centstorage/CentstorageAction.pm (97%) rename centreon/lib/perl/{ => centreon}/centstorage/CentstorageLib.pm (99%) rename centreon/lib/perl/{ => centreon}/centstorage/CentstoragePerfdataFile.pm (97%) rename centreon/lib/perl/{ => centreon}/centstorage/CentstoragePool.pm (97%) rename centreon/lib/perl/{ => centreon}/centstorage/CentstorageRRD.pm (99%) rename centreon/lib/perl/{ => centreon}/centstorage/CentstorageRebuild.pm (98%) rename centreon/lib/perl/centreon/{ => common}/db.pm (74%) rename centreon/lib/perl/centreon/{ => common}/lock.pm (93%) rename centreon/lib/perl/centreon/{ => common}/logger.pm (99%) rename centreon/lib/perl/{ => centreon}/reporting/CentreonAck.pm (98%) rename centreon/lib/perl/{ => centreon}/reporting/CentreonDashboard.pm (99%) rename centreon/lib/perl/{ => centreon}/reporting/CentreonDownTime.pm (99%) rename centreon/lib/perl/{ => centreon}/reporting/CentreonHost.pm (97%) rename centreon/lib/perl/{ => centreon}/reporting/CentreonHostStateEvents.pm (99%) rename centreon/lib/perl/{ => centreon}/reporting/CentreonLog.pm (98%) rename centreon/lib/perl/{ => centreon}/reporting/CentreonProcessStateEvents.pm (99%) rename centreon/lib/perl/{ => centreon}/reporting/CentreonService.pm (98%) rename centreon/lib/perl/{ => centreon}/reporting/CentreonServiceStateEvents.pm (99%) diff --git a/centreon/lib/perl/centstorage/CentstorageAction.pm b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm similarity index 97% rename from centreon/lib/perl/centstorage/CentstorageAction.pm rename to centreon/lib/perl/centreon/centstorage/CentstorageAction.pm index f75e8e33ac9..b4e00456611 100644 --- a/centreon/lib/perl/centstorage/CentstorageAction.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm @@ -2,9 +2,9 @@ use strict; use warnings; -package centstorage::CentstorageAction; +package centreon::centstorage::CentstorageAction; -use centstorage::CentstorageLib; +use centreon::centstorage::CentstorageLib; my %handlers = ('TERM' => {}); sub new { @@ -265,7 +265,7 @@ sub main { if (scalar(@rh_set) > 0) { foreach my $rh (@rh_set) { my $read_done = 0; - while ((my ($status_line, $readline) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + while ((my ($status_line, $readline) = centreon::centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { class_handle_TERM() if ($status_line == -1); last if ($status_line == 0); my ($method, @fields) = split(/\t/, $readline); diff --git a/centreon/lib/perl/centstorage/CentstorageLib.pm b/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm similarity index 99% rename from centreon/lib/perl/centstorage/CentstorageLib.pm rename to centreon/lib/perl/centreon/centstorage/CentstorageLib.pm index 207d6574909..18b45d8c208 100644 --- a/centreon/lib/perl/centstorage/CentstorageLib.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm @@ -1,5 +1,5 @@ -package centstorage::CentstorageLib; +package centreon::centstorage::CentstorageLib; use File::Basename; my $read_size = 1*1024*1024*10; # 10Mo diff --git a/centreon/lib/perl/centstorage/CentstoragePerfdataFile.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm similarity index 97% rename from centreon/lib/perl/centstorage/CentstoragePerfdataFile.pm rename to centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm index e44ec2f4877..96b9f9e09cc 100644 --- a/centreon/lib/perl/centstorage/CentstoragePerfdataFile.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm @@ -3,8 +3,8 @@ use strict; use warnings; use File::Copy; -package centstorage::CentstoragePerfdataFile; -use centstorage::CentstorageLib; +package centreon::centstorage::CentstoragePerfdataFile; +use centreon::centstorage::CentstorageLib; my $end_size_buffer = 1*1024*1024*10; # 10Mo sub new { diff --git a/centreon/lib/perl/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm similarity index 97% rename from centreon/lib/perl/centstorage/CentstoragePool.pm rename to centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index 278e8399621..136e6d9540c 100644 --- a/centreon/lib/perl/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -2,11 +2,11 @@ use strict; use warnings; -package centstorage::CentstoragePool; +package centreon::centstorage::CentstoragePool; -use centreon::db; -use centstorage::CentstorageLib; -use centstorage::CentstorageRebuild; +use centreon::common::db; +use centreon::centstorage::CentstorageLib; +use centreon::centstorage::CentstorageRebuild; my %handlers = ('TERM' => {}, 'CHLD' => {}); my %rrd_trans = ("g" => 0, "c" => 1, "d" => 2, "a" => 3); @@ -146,7 +146,7 @@ sub handle_TERM { if (scalar(@rh_set) > 0) { foreach my $rh (@rh_set) { my $read_done = 0; - while ((my ($status_line, $readline) = CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + while ((my ($status_line, $readline) = centreon::centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { last if ($status_line <= 0); if ($readline =~ /^UPDATE/) { $readline =~ s/^UPDATE\t//; @@ -946,16 +946,16 @@ sub rebuild { $self->{'dbcentstorage'}->set_inactive_destroy(); $self->{'dbcentreon'}->set_inactive_destroy(); - my $centreon_db_centstorage = centreon::db(logger => $self->{'logger'}, - db => $self->{'dbcentstorage'}->db(), - host => $self->{'dbcentstorage'}->host(), - user => $self->{'dbcentstorage'}->user(), - password => $self->{'dbcentstorage'}->password(), - port => $self->{'dbcentstorage'}->port(), - force => 0); + my $centreon_db_centstorage = centreon::common::db(logger => $self->{'logger'}, + db => $self->{'dbcentstorage'}->db(), + host => $self->{'dbcentstorage'}->host(), + user => $self->{'dbcentstorage'}->user(), + password => $self->{'dbcentstorage'}->password(), + port => $self->{'dbcentstorage'}->port(), + force => 0); $status = $centreon_db_centstorage->connect(); exit 1 if ($status == -1); - my $centstorage_rebuild = centstorage::CentstorageRebuild->new($self->{'logger'}); + my $centstorage_rebuild = centreon::centstorage::CentstorageRebuild->new($self->{'logger'}); $status = $centstorage_rebuild->main($centreon_db_centstorage, $rebuild_index_id, $self->{"cache_service"}->{$key_service}->{'check_interval'}, $self->{'rrd'}, $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); $centreon_db_centstorage->disconnect(); exit $status; @@ -1047,7 +1047,7 @@ sub main { $self->{'num_pool'} = $num_pool; $self->{'perfdata_parser_stop'} = $perfdata_parser_stop if (defined($perfdata_parser_stop)); - ($status, $self->{"main_perfdata_file"}) = centstorage::CentstorageLib::get_main_perfdata_file($self->{'dbcentreon'}); + ($status, $self->{"main_perfdata_file"}) = centreon::centstorage::CentstorageLib::get_main_perfdata_file($self->{'dbcentreon'}); ($status, $self->{"len_storage_rrd"}, $self->{"rrd_metrics_path"}, $self->{"rrd_status_path"}, $self->{"storage_type"}) = $self->get_centstorage_information(); ($status, $self->{"interval_time"}) = $self->get_centreon_intervaltime(); $self->{"rrd"}->metric_path($self->{"rrd_metrics_path"}); @@ -1072,7 +1072,7 @@ sub main { } foreach my $rh (@rh_set) { my $read_done = 0; - while ((my ($status_line, $readline) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + while ((my ($status_line, $readline) = centreon::centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { class_handle_TERM() if ($status_line == -1); last if ($status_line == 0); my ($method, @fields) = split(/\t/, $readline); diff --git a/centreon/lib/perl/centstorage/CentstorageRRD.pm b/centreon/lib/perl/centreon/centstorage/CentstorageRRD.pm similarity index 99% rename from centreon/lib/perl/centstorage/CentstorageRRD.pm rename to centreon/lib/perl/centreon/centstorage/CentstorageRRD.pm index 92246197038..50e6e1309c7 100644 --- a/centreon/lib/perl/centstorage/CentstorageRRD.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageRRD.pm @@ -3,7 +3,7 @@ use RRDs; use strict; use warnings; -package centstorage::CentstorageRRD; +package centreon::centstorage::CentstorageRRD; my @rrd_dst = ("GAUGE","COUNTER","DERIVE","ABSOLUTE"); diff --git a/centreon/lib/perl/centstorage/CentstorageRebuild.pm b/centreon/lib/perl/centreon/centstorage/CentstorageRebuild.pm similarity index 98% rename from centreon/lib/perl/centstorage/CentstorageRebuild.pm rename to centreon/lib/perl/centreon/centstorage/CentstorageRebuild.pm index 13de3825976..91dc5964926 100644 --- a/centreon/lib/perl/centstorage/CentstorageRebuild.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageRebuild.pm @@ -2,7 +2,7 @@ use strict; use warnings; -package centstorage::CentstorageRebuild; +package centreon::centstorage::CentstorageRebuild; my %handlers = ('TERM' => {}); sub new { diff --git a/centreon/lib/perl/centreon/db.pm b/centreon/lib/perl/centreon/common/db.pm similarity index 74% rename from centreon/lib/perl/centreon/db.pm rename to centreon/lib/perl/centreon/common/db.pm index f760b6e05f0..5bc01354bf8 100644 --- a/centreon/lib/perl/centreon/db.pm +++ b/centreon/lib/perl/centreon/common/db.pm @@ -1,46 +1,10 @@ -################################################################################ -# Copyright 2005-2011 MERETHIS -# Centreon is developped by : Julien Mathis and Romain Le Merlus under -# GPL Licence 2.0. -# -# This program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation ; either version 2 of the License. -# -# 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 General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this program; if not, see . -# -# Linking this program statically or dynamically with other modules is making a -# combined work based on this program. Thus, the terms and conditions of the GNU -# General Public License cover the whole combination. -# -# As a special exception, the copyright holders of this program give MERETHIS -# permission to link this program with independent modules to produce an executable, -# regardless of the license terms of these independent modules, and to copy and -# distribute the resulting executable under terms of MERETHIS choice, provided that -# MERETHIS also meet, for each linked independent module, the terms and conditions -# of the license of that module. An independent module is a module which is not -# derived from this program. If you modify this program, you may extend this -# exception to your version of the program, but you are not obliged to do so. If you -# do not wish to do so, delete this exception statement from your version. -# -# For more information : contact@centreon.com -# -# SVN : $URL -# SVN : $Id -# -#################################################################################### -package centreon::db; + +package centreon::common::db; use strict; use warnings; use DBI; - sub new { my ($class, %options) = @_; my %defaults = diff --git a/centreon/lib/perl/centreon/lock.pm b/centreon/lib/perl/centreon/common/lock.pm similarity index 93% rename from centreon/lib/perl/centreon/lock.pm rename to centreon/lib/perl/centreon/common/lock.pm index f4fd55369af..c5b8a3595ac 100644 --- a/centreon/lib/perl/centreon/lock.pm +++ b/centreon/lib/perl/centreon/common/lock.pm @@ -1,4 +1,4 @@ -package centreon::lock; +package centreon::common::lock; use strict; use warnings; @@ -25,9 +25,9 @@ sub set { die "Failed to set lock for $self->{name}" if $self->is_set(); } -package centreon::lock::file; +package centreon::common::lock::file; -use base qw(centreon::lock); +use base qw(centreon::common::lock); sub new { my $class = shift; @@ -62,9 +62,9 @@ sub DESTROY { } } -package centreon::lock::sql; +package centreon::common::lock::sql; -use base qw(centreon::lock); +use base qw(centreon::common::lock); sub new { my $class = shift; diff --git a/centreon/lib/perl/centreon/logger.pm b/centreon/lib/perl/centreon/common/logger.pm similarity index 99% rename from centreon/lib/perl/centreon/logger.pm rename to centreon/lib/perl/centreon/common/logger.pm index 3449528b8f9..3891c90effd 100644 --- a/centreon/lib/perl/centreon/logger.pm +++ b/centreon/lib/perl/centreon/common/logger.pm @@ -1,4 +1,4 @@ -package centreon::logger; +package centreon::common::logger; =head1 NOM diff --git a/centreon/lib/perl/reporting/CentreonAck.pm b/centreon/lib/perl/centreon/reporting/CentreonAck.pm similarity index 98% rename from centreon/lib/perl/reporting/CentreonAck.pm rename to centreon/lib/perl/centreon/reporting/CentreonAck.pm index 77ebb3cc729..132f479806e 100644 --- a/centreon/lib/perl/reporting/CentreonAck.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonAck.pm @@ -2,7 +2,7 @@ use strict; use warnings; -package reporting::CentreonAck; +package centreon::reporting::CentreonAck; # Constructor # parameters: diff --git a/centreon/lib/perl/reporting/CentreonDashboard.pm b/centreon/lib/perl/centreon/reporting/CentreonDashboard.pm similarity index 99% rename from centreon/lib/perl/reporting/CentreonDashboard.pm rename to centreon/lib/perl/centreon/reporting/CentreonDashboard.pm index f22d0a05da8..e3ead60b7f2 100644 --- a/centreon/lib/perl/reporting/CentreonDashboard.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonDashboard.pm @@ -2,7 +2,7 @@ use strict; use warnings; -package reporting::CentreonDashboard; +package centreon::reporting::CentreonDashboard; use POSIX; use Getopt::Long; diff --git a/centreon/lib/perl/reporting/CentreonDownTime.pm b/centreon/lib/perl/centreon/reporting/CentreonDownTime.pm similarity index 99% rename from centreon/lib/perl/reporting/CentreonDownTime.pm rename to centreon/lib/perl/centreon/reporting/CentreonDownTime.pm index 3a7c0c9d5c9..aba745c9969 100644 --- a/centreon/lib/perl/reporting/CentreonDownTime.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonDownTime.pm @@ -2,7 +2,7 @@ use strict; use warnings; -package reporting::CentreonDownTime; +package centreon::reporting::CentreonDownTime; # Constructor # parameters: diff --git a/centreon/lib/perl/reporting/CentreonHost.pm b/centreon/lib/perl/centreon/reporting/CentreonHost.pm similarity index 97% rename from centreon/lib/perl/reporting/CentreonHost.pm rename to centreon/lib/perl/centreon/reporting/CentreonHost.pm index a8c8b318918..106be7a3f9a 100644 --- a/centreon/lib/perl/reporting/CentreonHost.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonHost.pm @@ -2,7 +2,7 @@ use strict; use warnings; -package reporting::CentreonHost; +package centreon::reporting::CentreonHost; # Constructor # parameters: diff --git a/centreon/lib/perl/reporting/CentreonHostStateEvents.pm b/centreon/lib/perl/centreon/reporting/CentreonHostStateEvents.pm similarity index 99% rename from centreon/lib/perl/reporting/CentreonHostStateEvents.pm rename to centreon/lib/perl/centreon/reporting/CentreonHostStateEvents.pm index af301e74719..6ff6ede52bc 100644 --- a/centreon/lib/perl/reporting/CentreonHostStateEvents.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonHostStateEvents.pm @@ -2,7 +2,7 @@ use strict; use warnings; -package reporting::CentreonHostStateEvents; +package centreon::reporting::CentreonHostStateEvents; # Constructor # parameters: diff --git a/centreon/lib/perl/reporting/CentreonLog.pm b/centreon/lib/perl/centreon/reporting/CentreonLog.pm similarity index 98% rename from centreon/lib/perl/reporting/CentreonLog.pm rename to centreon/lib/perl/centreon/reporting/CentreonLog.pm index b122af34ba1..191ca8b3b2b 100644 --- a/centreon/lib/perl/reporting/CentreonLog.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonLog.pm @@ -2,7 +2,7 @@ use strict; use warnings; -package reporting::CentreonLog; +package centreon::reporting::CentreonLog; # Constructor # parameters: diff --git a/centreon/lib/perl/reporting/CentreonProcessStateEvents.pm b/centreon/lib/perl/centreon/reporting/CentreonProcessStateEvents.pm similarity index 99% rename from centreon/lib/perl/reporting/CentreonProcessStateEvents.pm rename to centreon/lib/perl/centreon/reporting/CentreonProcessStateEvents.pm index aa14f7526a2..e84f787fc8d 100644 --- a/centreon/lib/perl/reporting/CentreonProcessStateEvents.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonProcessStateEvents.pm @@ -2,7 +2,7 @@ use strict; use warnings; -package reporting::CentreonProcessStateEvents; +package centreon::reporting::CentreonProcessStateEvents; #use vars qw (%serviceStates %hostStates %servicStateIds %hostStateIds); #require "/home/msugumaran/merethis/centreon-bi-server/centreon/cron/perl-modules/variables.pm"; diff --git a/centreon/lib/perl/reporting/CentreonService.pm b/centreon/lib/perl/centreon/reporting/CentreonService.pm similarity index 98% rename from centreon/lib/perl/reporting/CentreonService.pm rename to centreon/lib/perl/centreon/reporting/CentreonService.pm index 8929a2834b7..64f20e02bf0 100644 --- a/centreon/lib/perl/reporting/CentreonService.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonService.pm @@ -2,7 +2,7 @@ use strict; use warnings; -package reporting::CentreonService; +package centreon::reporting::CentreonService; # Constructor # parameters: diff --git a/centreon/lib/perl/reporting/CentreonServiceStateEvents.pm b/centreon/lib/perl/centreon/reporting/CentreonServiceStateEvents.pm similarity index 99% rename from centreon/lib/perl/reporting/CentreonServiceStateEvents.pm rename to centreon/lib/perl/centreon/reporting/CentreonServiceStateEvents.pm index 111aae19610..350522e98c6 100644 --- a/centreon/lib/perl/reporting/CentreonServiceStateEvents.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonServiceStateEvents.pm @@ -2,7 +2,7 @@ use strict; use warnings; -package reporting::CentreonServiceStateEvents; +package centreon::reporting::CentreonServiceStateEvents; # Constructor # parameters: diff --git a/centreon/lib/perl/centreon/script.pm b/centreon/lib/perl/centreon/script.pm index b8c0fce7c0d..31d068ebe5f 100644 --- a/centreon/lib/perl/centreon/script.pm +++ b/centreon/lib/perl/centreon/script.pm @@ -5,9 +5,9 @@ use warnings; use FindBin; use Getopt::Long; use Pod::Usage; -use centreon::logger; -use centreon::db; -use centreon::lock; +use centreon::common::logger; +use centreon::common::db; +use centreon::common::lock; use vars qw($centreon_config); @@ -31,7 +31,7 @@ sub new { bless $self, $class; $self->{name} = $name; - $self->{logger} = centreon::logger->new(); + $self->{logger} = centreon::common::logger->new(); $self->{options} = { "config=s" => \$self->{config_file}, "logfile=s" => \$self->{log_file}, @@ -50,17 +50,17 @@ sub init { $self->{logger}->severity($self->{severity}); if ($self->{centreon_db_conn}) { - $self->{cdb} = centreon::db->new + $self->{cdb} = centreon::common::db->new (db => $self->{centreon_config}->{centreon_db}, host => $self->{centreon_config}->{db_host}, user => $self->{centreon_config}->{db_user}, password => $self->{centreon_config}->{db_passwd}, logger => $self->{logger}); - $self->{lock} = centreon::lock::sql->new($self->{name}, dbc => $self->{cdb}); + $self->{lock} = centreon::common::lock::sql->new($self->{name}, dbc => $self->{cdb}); $self->{lock}->set(); } if ($self->{centstorage_db_conn}) { - $self->{csdb} = centreon::db->new + $self->{csdb} = centreon::common::db->new (db => $self->{centreon_config}->{centstorage_db}, host => $self->{centreon_config}->{db_host}, user => $self->{centreon_config}->{db_user}, diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index 87f6a1b35b0..12d5fc6e421 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -7,13 +7,13 @@ use POSIX; use IO::Select; use IO::Handle; use centreon::script; -use centreon::db; -use centstorage::CentstorageLib; -use centstorage::CentstoragePool; -use centstorage::CentstoragePerfdataFile; -use centstorage::CentstorageAction; -use centstorage::CentstorageAction; -use centstorage::CentstorageRRD; +use centreon::common::db; +use centreon::centstorage::CentstorageLib; +use centreon::centstorage::CentstoragePool; +use centreon::centstorage::CentstoragePerfdataFile; +use centreon::centstorage::CentstorageAction; +use centreon::centstorage::CentstorageAction; +use centreon::centstorage::CentstorageRRD; use base qw(centreon::script); use vars qw(%centstorage_config); @@ -188,7 +188,7 @@ sub verify_pool { if (defined($create_pool) && $create_pool == 1) { # We have lost one. And if it's the pool rebuild, send progress finish if ($pool_num == $self->{rebuild_pool_choosen}) { - centstorage::CentstorageLib::call_pool_rebuild_finish(\%{$self->{pool_pipes}}, $self->{centstorage_config}->{pool_childs}, \%{$self->{delete_pipes}}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); + centreoncentstorage::CentstorageLib::call_pool_rebuild_finish(\%{$self->{pool_pipes}}, $self->{centstorage_config}->{pool_childs}, \%{$self->{delete_pipes}}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); } $self->create_pool_child($pool_num); } @@ -231,7 +231,7 @@ sub create_pool_child { if (!$current_pid) { close $self->{pool_pipes}{$pool_num}->{'reader_one'}; close $self->{pool_pipes}{$pool_num}->{'writer_two'}; - my $centreon_db_centreon = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, + my $centreon_db_centreon = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, host => $self->{centreon_config}->{db_host}, port => $self->{centreon_config}->{db_port}, user => $self->{centreon_config}->{db_user}, @@ -239,7 +239,7 @@ sub create_pool_child { force => 1, logger => $self->{logger}); $centreon_db_centreon->connect(); - my $centreon_db_centstorage = centreon::db->new(db => $self->{centreon_config}->{centstorage_db}, + my $centreon_db_centstorage = centreon::common::db->new(db => $self->{centreon_config}->{centstorage_db}, host => $self->{centreon_config}->{db_host}, port => $self->{centreon_config}->{db_port}, user => $self->{centreon_config}->{db_user}, @@ -248,9 +248,9 @@ sub create_pool_child { logger => $self->{logger}); $centreon_db_centstorage->connect(); - my $centstorage_rrd = centstorage::CentstorageRRD->new($self->{logger}); + my $centstorage_rrd = centreon::centstorage::CentstorageRRD->new($self->{logger}); - my $centstorage_pool = centstorage::CentstoragePool->new($self->{logger}, $centstorage_rrd, $self->{rebuild_progress}); + my $centstorage_pool = centreon::centstorage::CentstoragePool->new($self->{logger}, $centstorage_rrd, $self->{rebuild_progress}); $centstorage_pool->main($centreon_db_centreon, $centreon_db_centstorage, $self->{pool_pipes}{$pool_num}->{'reader_two'}, $self->{pool_pipes}{$pool_num}->{'writer_one'}, $pool_num, $self->{centstorage_config}->{rrd_cache_mode}, $self->{centstorage_config}->{rrd_flush_time}, $self->{centstorage_config}->{perfdata_parser_stop}); @@ -285,7 +285,7 @@ sub create_delete_child { if (!$current_pid) { close $self->{delete_pipes}{'reader_one'}; close $self->{delete_pipes}{'writer_two'}; - my $centreon_db_centreon = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, + my $centreon_db_centreon = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, host => $self->{centreon_config}->{db_host}, port => $self->{centreon_config}->{db_port}, user => $self->{centreon_config}->{db_user}, @@ -293,7 +293,7 @@ sub create_delete_child { force => 1, logger => $self->{logger}); $centreon_db_centreon->connect(); - my $centreon_db_centstorage = centreon::db->new(db => $self->{centreon_config}->{centstorage_db}, + my $centreon_db_centstorage = centreon::common::db->new(db => $self->{centreon_config}->{centstorage_db}, host => $self->{centreon_config}->{db_host}, port => $self->{centreon_config}->{db_port}, user => $self->{centreon_config}->{db_user}, @@ -302,7 +302,7 @@ sub create_delete_child { logger => $self->{logger}); $centreon_db_centstorage->connect(); - my $centstorage_action = centstorage::CentstorageAction->new($self->{logger}, $self->{rebuild_progress}, $self->{centstorage_config}->{centreon_23_compatibility}); + my $centstorage_action = centreon::centstorage::CentstorageAction->new($self->{logger}, $self->{rebuild_progress}, $self->{centstorage_config}->{centreon_23_compatibility}); $centstorage_action->main($centreon_db_centreon, $centreon_db_centstorage, $self->{delete_pipes}{'reader_two'}, $self->{delete_pipes}{'writer_one'}); exit(0); @@ -338,7 +338,7 @@ sub run { my $status; my $pools_perfdata_filename; - $self->{centreon_db_centreon} = centreon::db->new(db => $self->{centreon_config}->{centreon_db}, + $self->{centreon_db_centreon} = centreon::commmon::db->new(db => $self->{centreon_config}->{centreon_db}, host => $self->{centreon_config}->{db_host}, port => $self->{centreon_config}->{db_port}, user => $self->{centreon_config}->{db_user}, @@ -346,11 +346,11 @@ sub run { force => 1, logger => $self->{logger}); $self->{centreon_db_centreon}->connect(); - $self->handle_DIE("Censtorage option is '0'. Don't have to start") if (centstorage::CentstorageLib::start_or_not($self->{centreon_db_centreon}) == 0); + $self->handle_DIE("Censtorage option is '0'. Don't have to start") if (centreon::centstorage::CentstorageLib::start_or_not($self->{centreon_db_centreon}) == 0); while (!defined($main_perfdata) || $main_perfdata eq "") { - ($status, $main_perfdata) = centstorage::CentstorageLib::get_main_perfdata_file($self->{centreon_db_centreon}); + ($status, $main_perfdata) = centreon::centstorage::CentstorageLib::get_main_perfdata_file($self->{centreon_db_centreon}); if (defined($main_perfdata)) { - $pools_perfdata_filename = centstorage::CentstorageLib::check_pool_old_perfdata_file($main_perfdata, $self->{centstorage_config}->{pool_childs}); + $pools_perfdata_filename = centreon::centstorage::CentstorageLib::check_pool_old_perfdata_file($main_perfdata, $self->{centstorage_config}->{pool_childs}); } } $self->{centreon_db_centreon}->disconnect(); @@ -360,10 +360,10 @@ sub run { ### if (defined($pools_perfdata_filename)) { foreach (@$pools_perfdata_filename) { - $self->handle_DIE("Don't have righs on file '$_' (or the directory)") if (centstorage::CentstorageLib::can_write($_) == 0); + $self->handle_DIE("Don't have righs on file '$_' (or the directory)") if (centreon::centstorage::CentstorageLib::can_write($_) == 0); } } - $self->handle_DIE("Don't have righs on file '$main_perfdata' (or the directory)") if (centstorage::CentstorageLib::can_write($main_perfdata) == 0); + $self->handle_DIE("Don't have righs on file '$main_perfdata' (or the directory)") if (centreon::centstorage::CentstorageLib::can_write($main_perfdata) == 0); ### # Create Childs @@ -389,7 +389,7 @@ sub run { ### if (defined($pools_perfdata_filename)) { foreach (@$pools_perfdata_filename) { - $self->{centstorage_perfdata_file} = centstorage::CentstoragePerfdataFile->new($self->{logger}); + $self->{centstorage_perfdata_file} = centreon::centstorage::CentstoragePerfdataFile->new($self->{logger}); $self->{centstorage_perfdata_file}->compute($_, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); } $pools_perfdata_filename = undef; @@ -398,7 +398,7 @@ sub run { ### # Do main file ### - $self->{centstorage_perfdata_file} = centstorage::CentstoragePerfdataFile->new($self->{logger}); + $self->{centstorage_perfdata_file} = centreon::centstorage::CentstoragePerfdataFile->new($self->{logger}); $self->{centstorage_perfdata_file}->compute($main_perfdata, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); ### @@ -407,18 +407,18 @@ sub run { my @rh_set = $self->{read_select}->can_read(10); foreach my $rh (@rh_set) { my $read_done = 0; - while ((my ($status_line, $data_element) = centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{fileno_save_read}{fileno($rh)}}, \$read_done))) { + while ((my ($status_line, $data_element) = centreon::centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{fileno_save_read}{fileno($rh)}}, \$read_done))) { last if ($status_line <= 0); if ($data_element =~ /^REBUILDBEGIN/) { - centstorage::CentstorageLib::call_pool_rebuild($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); + centreon::centstorage::CentstorageLib::call_pool_rebuild($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); } elsif ($data_element =~ /^REBUILDFINISH/) { - centstorage::CentstorageLib::call_pool_rebuild_finish(\%{$self->{pool_pipes}}, $self->{centstorage_config}->{pool_childs}, \%{$self->{delete_pipes}}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); + centreon::centstorage::CentstorageLib::call_pool_rebuild_finish(\%{$self->{pool_pipes}}, $self->{centstorage_config}->{pool_childs}, \%{$self->{delete_pipes}}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); } elsif ($data_element =~ /^RENAMECLEAN/) { - centstorage::CentstorageLib::call_pool_rename_clean($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + centreon::centstorage::CentstorageLib::call_pool_rename_clean($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); } elsif ($data_element =~ /^RENAMEFINISH/) { - centstorage::CentstorageLib::call_pool_rename_finish($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + centreon::centstorage::CentstorageLib::call_pool_rename_finish($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); } elsif ($data_element =~ /^DELETECLEAN/) { - centstorage::CentstorageLib::call_pool_delete_clean($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + centreon::centstorage::CentstorageLib::call_pool_delete_clean($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); } } } diff --git a/centreon/lib/perl/centreon/script/centstorage_purge.pm b/centreon/lib/perl/centreon/script/centstorage_purge.pm index a709297fe95..ae9db04dbaa 100644 --- a/centreon/lib/perl/centreon/script/centstorage_purge.pm +++ b/centreon/lib/perl/centreon/script/centstorage_purge.pm @@ -3,7 +3,7 @@ package centreon::script::centstorage_purge; use strict; use warnings; use centreon::script; -use centreon::lock; +use centreon::common::lock; use base qw(centreon::script); @@ -59,7 +59,7 @@ sub run { eval { my $lock = undef; if ($self->{broker} eq "ndo") { - $lock = centreon::lock::sql("logAnalyser", dbc => $self->{cdb}); + $lock = centreon::common::lock::sql("logAnalyser", dbc => $self->{cdb}); $lock->set(); } $self->{csdb}->do("DELETE FROM `$table` WHERE `ctime` < '$last_log'"); diff --git a/centreon/lib/perl/centreon/script/eventReportBuilder.pm b/centreon/lib/perl/centreon/script/eventReportBuilder.pm index daed573c29b..52d7945e238 100644 --- a/centreon/lib/perl/centreon/script/eventReportBuilder.pm +++ b/centreon/lib/perl/centreon/script/eventReportBuilder.pm @@ -4,14 +4,14 @@ use strict; use POSIX; use Time::Local; -use reporting::CentreonHost; -use reporting::CentreonService; -use reporting::CentreonLog; -use reporting::CentreonServiceStateEvents; -use reporting::CentreonHostStateEvents; -use reporting::CentreonProcessStateEvents; -use reporting::CentreonDownTime; -use reporting::CentreonAck; +use centreon::reporting::CentreonHost; +use centreon::reporting::CentreonService; +use centreon::reporting::CentreonLog; +use centreon::reporting::CentreonServiceStateEvents; +use centreon::reporting::CentreonHostStateEvents; +use centreon::reporting::CentreonProcessStateEvents; +use centreon::reporting::CentreonDownTime; +use centreon::reporting::CentreonAck; use centreon::script; use base qw(centreon::script); From dbd2d44011f9d6fc0b1ccb16bf4371072e974bda Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 21 Mar 2013 10:39:31 +0100 Subject: [PATCH 011/458] Finish eventReportBuilder --- .../centstorage/CentstoragePerfdataFile.pm | 2 +- .../lib/perl/centreon/script/centstorage.pm | 2 +- .../centreon/script/eventReportBuilder.pm | 75 +++++++------------ 3 files changed, 31 insertions(+), 48 deletions(-) diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm index 96b9f9e09cc..c74ebc08d53 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm @@ -60,7 +60,7 @@ sub compute { } my $fh = $self->{"filehandler"}; - while ((my ($status, $readline) = centstorage::CentstorageLib::get_line_file($fh, \@{$self->{"buffer"}}, \$self->{"readed"}))) { + while ((my ($status, $readline) = centreon::centstorage::CentstorageLib::get_line_file($fh, \@{$self->{"buffer"}}, \$self->{"readed"}))) { last if ($status == -1); $readline =~ /([0-9]+?)\t+?([^\t]+?)\t+?([^\t]+?)\t/; if (defined($1) && defined($2) && defined($3)) { diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index 12d5fc6e421..4c5d00fa763 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -338,7 +338,7 @@ sub run { my $status; my $pools_perfdata_filename; - $self->{centreon_db_centreon} = centreon::commmon::db->new(db => $self->{centreon_config}->{centreon_db}, + $self->{centreon_db_centreon} = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, host => $self->{centreon_config}->{db_host}, port => $self->{centreon_config}->{db_port}, user => $self->{centreon_config}->{db_user}, diff --git a/centreon/lib/perl/centreon/script/eventReportBuilder.pm b/centreon/lib/perl/centreon/script/eventReportBuilder.pm index 52d7945e238..0fc40df5906 100644 --- a/centreon/lib/perl/centreon/script/eventReportBuilder.pm +++ b/centreon/lib/perl/centreon/script/eventReportBuilder.pm @@ -57,32 +57,6 @@ sub getDbLayer() { return "ndo"; } -# function that checks if the log is already built -sub dayAlreadyProcessed($$$$) { - my $self = shift; - my ($day, $month, $year) = (shift, shift, shift); - - my $tmp_file = $varLibCentreon . "/archive-monitoring-incidents.last"; - my $last; - my $now; - my $write_cmd; - - $now = $day.$month.$year; - if (-e "$tmp_file") { - chomp($last = `cat $tmp_file`); - $write_cmd = `echo $now > $tmp_file`; - if ($now == $last) { - print "[".time."] Error : day already processed\n"; - return 1; - } - else { - return 0; - } - } - $write_cmd = `echo $now > $tmp_file`; - return 0; -} - # Initialize objects for program sub initVars { my $self = shift; @@ -90,33 +64,40 @@ sub initVars { # Getting centstatus database name $self->{dbLayer} = getDbLayer(); if ($self->{dbLayer} eq "ndo") { - my $sth = $centreon->query("SELECT db_name, db_host, db_port, db_user, db_pass FROM cfg_ndo2db WHERE activate = '1' LIMIT 1"); + my $sth = $self->{cdb}->query("SELECT db_name, db_host, db_port, db_user, db_pass FROM cfg_ndo2db WHERE activate = '1' LIMIT 1"); if (my $row = $sth->fetchrow_hashref()) { #connecting to censtatus - $centstatus = CentreonDB->new($logger, $row->{"db_name"}, $row->{'db_host'}, $row->{'db_user'}, $row->{'db_pass'}, $row->{'db_port'}); + $centstatus = centreon::common::db->new(db => $row->{"db_name"}, + host => $row->{'db_host'}, + port => $row->{'db_port'}, + user => $row->{'db_user'}, + password => $row->{'db_pass'}, + force => 0, + logger => $self->{logger}); } } elsif ($self->{dbLayer} eq "broker") { - $centstatus = $centstorage; + $centstatus = $self->{csdb}; } else { - $self->{logger}->writeLogError("Unsupported database layer: " . $dbLayer); + $self->{logger}->writeLogError("Unsupported database layer: " . $self->{dbLayer}); $self->exit_pgr(); } # classes to query database tables - $host = CentreonHost->new($logger, $centreon); - $service = CentreonService->new($logger, $centreon); - $nagiosLog = CentreonLog->new($logger, $centstorage, $dbLayer); - my $centreonDownTime = CentreonDownTime->new($logger, $centstatus, $dbLayer); - my $centreonAck = CentreonAck->new($logger, $centstatus, $dbLayer); - $serviceEvents = CentreonServiceStateEvents->new($logger, $centstorage, $centreonAck, $centreonDownTime); - $hostEvents = CentreonHostStateEvents->new($logger, $centstorage, $centreonAck, $centreonDownTime); + $self->{host} = CentreonHost->new($self->{logger}, $self->{cdb}); + $self->{service} = CentreonService->new($self->{logger}, $self->{cdb}); + $self->{nagiosLog} = CentreonLog->new($self->{logger}, $self->{csdb}, $self->{dbLayer}); + my $centreonDownTime = CentreonDownTime->new($self->{logger}, $centstatus, $self->{dbLayer}); + my $centreonAck = CentreonAck->new($self->{logger}, $centstatus, $self->{dbLayer}); + $self->{serviceEvents} = CentreonServiceStateEvents->new($self->{logger}, $self->{csdb}, $centreonAck, $centreonDownTime); + $self->{hostEvents} = CentreonHostStateEvents->new($self->{logger}, $self->{csdb}, $centreonAck, $centreonDownTime); # Class that builds events - $processEvents = CentreonProcessStateEvents->new($logger, $host, $service, $nagiosLog, $hostEvents, $serviceEvents, $centreonDownTime, $dbLayer); + $self->{processEvents} = CentreonProcessStateEvents->new($self->{logger}, $self->{host}, $self->{service}, $self->{nagiosLog}, $self->{hostEvents}, $self->{serviceEvents}, $centreonDownTime, $self->{dbLayer}); } # For a given period returns in a table each sub getDaysFromPeriod { + my $self = shift; my ($start, $end) = (shift, shift); my @days; @@ -150,18 +131,20 @@ sub getDaysFromPeriod { # rebuild all events sub rebuildIncidents { + my $self = shift; my $time_period = shift; + # Empty tables - $serviceEvents->truncateStateEvents(); - $hostEvents->truncateStateEvents(); + $self->{serviceEvents}->truncateStateEvents(); + $self->{hostEvents}->truncateStateEvents(); # Getting first log and last log times my ($start, $end) = $nagiosLog->getFirstLastLogTime(); - my $periods = getDaysFromPeriod($start, $end); + my $periods = $self->getDaysFromPeriod($start, $end); # archiving logs for each days foreach(@$periods) { $self->{logger}->writeLogInfo("Processing period: ".localtime($_->{"day_start"})." => ".localtime($_->{"day_end"})); - $processEvents->parseHostLog($_->{"day_start"}, $_->{"day_end"}); - $processEvents->parseServiceLog($_->{"day_start"}, $_->{"day_end"}); + $self->{processEvents}->parseHostLog($_->{"day_start"}, $_->{"day_end"}); + $self->{processEvents}->parseServiceLog($_->{"day_start"}, $_->{"day_end"}); } } @@ -174,7 +157,7 @@ sub run { $self->{logger}->writeLogInfo("Starting program..."); - if (defined($options{'rebuild'})) { + if (defined($self->{opt_rebuild})) { $self->rebuildIncidents(); }else { my $currentTime = time; @@ -182,8 +165,8 @@ sub run { my $end = mktime(0,0,0,$day,$month,$year,0,0,-1); my $start = mktime(0,0,0,$day-1,$month,$year,0,0,-1); $self->{logger}->writeLogInfo("Processing period: ".localtime($start)." => ".localtime($end)); - $processEvents->parseHostLog($start, $end); - $processEvents->parseServiceLog($start, $end); + $self->{processEvents}->parseHostLog($start, $end); + $self->{processEvents}->parseServiceLog($start, $end); } $self->exit_pgr(); From e95d6b99d06e8bf5893d2b5afbdf0a9d87a9961e Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 21 Mar 2013 10:56:23 +0100 Subject: [PATCH 012/458] Mod request returns --- centreon/lib/perl/centreon/reporting/CentreonAck.pm | 4 ++-- .../lib/perl/centreon/reporting/CentreonDashboard.pm | 12 ++++++------ .../lib/perl/centreon/reporting/CentreonDownTime.pm | 2 +- centreon/lib/perl/centreon/reporting/CentreonHost.pm | 2 +- .../centreon/reporting/CentreonHostStateEvents.pm | 6 +++--- centreon/lib/perl/centreon/reporting/CentreonLog.pm | 6 +++--- .../lib/perl/centreon/reporting/CentreonService.pm | 4 ++-- .../centreon/reporting/CentreonServiceStateEvents.pm | 6 +++--- .../lib/perl/centreon/script/eventReportBuilder.pm | 11 +++++++---- 9 files changed, 28 insertions(+), 25 deletions(-) diff --git a/centreon/lib/perl/centreon/reporting/CentreonAck.pm b/centreon/lib/perl/centreon/reporting/CentreonAck.pm index 132f479806e..1bb79a817cc 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonAck.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonAck.pm @@ -58,7 +58,7 @@ sub getServiceAckTime { " ORDER BY `entry_time` asc"; } - my $sth = $centreon->query($query); + my ($status, $sth) = $centreon->query($query); my $ackTime = "NULL"; if (my $row = $sth->fetchrow_hashref()) { $ackTime = $row->{'ack_time'}; @@ -97,7 +97,7 @@ sub getHostAckTime { " ORDER BY `entry_time` asc"; } - my $sth = $centreon->query($query); + my ($status, $sth) = $centreon->query($query); my $ackTime = "NULL"; if (my $row = $sth->fetchrow_hashref()) { $ackTime = $row->{'ack_time'}; diff --git a/centreon/lib/perl/centreon/reporting/CentreonDashboard.pm b/centreon/lib/perl/centreon/reporting/CentreonDashboard.pm index e3ead60b7f2..cbe1507bfbc 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonDashboard.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonDashboard.pm @@ -44,7 +44,7 @@ sub insertHostStats { my $query_end = ""; my $firstHost = 1; my $count = 0; - my $sth; + my ($status, $sth); while (my ($key, $value) = each %$names) { if ($firstHost == 1) { $firstHost = 0; @@ -64,14 +64,14 @@ sub insertHostStats { } $count++; if ($count == 5000) { - $sth = $centstorage->query($query_start.$query_end); + ($status, $sth) = $centstorage->query($query_start.$query_end); $firstHost = 1; $query_end = ""; $count = 0; } } if ($count) { - $sth = $centstorage->query($query_start.$query_end); + ($status, $sth) = $centstorage->query($query_start.$query_end); } } @@ -99,7 +99,7 @@ sub insertServiceStats { my $query_end = ""; my $firstService = 1; my $count = 0; - my $sth; + my ($status, $sth); while (my ($key, $value) = each %$names) { if ($firstService == 1) { $firstService = 0; @@ -120,14 +120,14 @@ sub insertServiceStats { } $count++; if ($count == 5000) { - $sth = $centstorage->query($query_start.$query_end); + ($status, $sth) = $centstorage->query($query_start.$query_end); $firstService = 1; $query_end = ""; $count = 0; } } if ($count) { - $sth = $centstorage->query($query_start.$query_end); + ($status, $sth) = $centstorage->query($query_start.$query_end); } } diff --git a/centreon/lib/perl/centreon/reporting/CentreonDownTime.pm b/centreon/lib/perl/centreon/reporting/CentreonDownTime.pm index aba745c9969..029e3ed22bd 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonDownTime.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonDownTime.pm @@ -61,7 +61,7 @@ sub getDownTime { "ORDER BY name1 ASC, start_time ASC, end_time ASC"; } - my $sth = $centreon->query($query); + my ($status, $sth) = $centreon->query($query); my @periods = (); while (my $row = $sth->fetchrow_hashref()) { diff --git a/centreon/lib/perl/centreon/reporting/CentreonHost.pm b/centreon/lib/perl/centreon/reporting/CentreonHost.pm index 106be7a3f9a..d38bf06a70d 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonHost.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonHost.pm @@ -37,7 +37,7 @@ sub getAllHosts { if ($activated == 1) { $query .= " AND `host_activate` ='1'"; } - my $sth = $centreon->query($query); + my ($status, $sth) = $centreon->query($query); while (my $row = $sth->fetchrow_hashref()) { $host_ids{$row->{"host_name"}} = $row->{"host_id"}; $host_names{$row->{"host_id"}} = $row->{"host_name"}; diff --git a/centreon/lib/perl/centreon/reporting/CentreonHostStateEvents.pm b/centreon/lib/perl/centreon/reporting/CentreonHostStateEvents.pm index 6ff6ede52bc..4dcf9d31260 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonHostStateEvents.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonHostStateEvents.pm @@ -35,7 +35,7 @@ sub getStateEventDurations { " WHERE `start_time` < ".$end. " AND `end_time` > ".$start. " AND `state` < 3"; # STATE PENDING AND UNKNOWN NOT HANDLED - my $sth = $centstorage->query($query); + my ($status, $sth) = $centstorage->query($query); while (my $row = $sth->fetchrow_hashref()) { if ($row->{"start_time"} < $start) { $row->{"start_time"} = $start; @@ -81,7 +81,7 @@ sub getLastStates { my $query = "SELECT `host_id`, `state`, `hoststateevent_id`, `end_time`, `in_downtime`". " FROM `hoststateevents`". " WHERE `last_update` = 1"; - my $sth = $centstorage->query($query); + my ($status, $sth) = $centstorage->query($query); while(my $row = $sth->fetchrow_hashref()) { if (defined($hostNames->{$row->{'host_id'}})) { my @tab = ($row->{'end_time'}, $row->{'state'}, $row->{'hoststateevent_id'}, $row->{'in_downtime'}); @@ -190,7 +190,7 @@ sub getFirstLastIncidentTimes { my $centstorage = $self->{"centstorage"}; my $query = "SELECT min(`start_time`) as minc, max(`end_time`) as maxc FROM `hoststateevents`"; - my $sth = $centstorage->query($query); + my ($status, $sth) = $centstorage->query($query); my ($start, $end) = (0,0); if (my $row = $sth->fetchrow_hashref()) { ($start, $end) = ($row->{"minc"}, $row->{"maxc"}); diff --git a/centreon/lib/perl/centreon/reporting/CentreonLog.pm b/centreon/lib/perl/centreon/reporting/CentreonLog.pm index 191ca8b3b2b..c11ad4a6017 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonLog.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonLog.pm @@ -54,7 +54,7 @@ sub getLogOfServices { " AND `msg_type` IN ('0', '1', '6', '7', '8', '9')". " ORDER BY `ctime`"; } - my $result = $centstorage->query($query); + my ($status, $result) = $centstorage->query($query); return $result; } @@ -90,7 +90,7 @@ sub getLogOfHosts { " AND `service_id` IS NULL". " ORDER BY `ctime`"; } - my $result = $centstorage->query($query); + my ($status, $result) = $centstorage->query($query); return $result; } @@ -105,7 +105,7 @@ sub getFirstLastLogTime { } elsif ($self->{'dbLayer'} eq "broker") { $query = "SELECT min(`ctime`) as minc, max(`ctime`) as maxc FROM `logs`"; } - my $sth = $centstorage->query($query); + my ($status, $sth) = $centstorage->query($query); my ($start, $end) = (0,0); if (my $row = $sth->fetchrow_hashref()) { ($start, $end) = ($row->{"minc"}, $row->{"maxc"}); diff --git a/centreon/lib/perl/centreon/reporting/CentreonService.pm b/centreon/lib/perl/centreon/reporting/CentreonService.pm index 64f20e02bf0..0ef539451e8 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonService.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonService.pm @@ -39,7 +39,7 @@ sub getAllServices { if ($activated == 1) { $query .= " AND `service_activate`='1'"; } - my $sth = $centreon->query($query); + my ($status, $sth) = $centreon->query($query); while(my $row = $sth->fetchrow_hashref()) { $service_ids{$row->{'host_name'}.";;".$row->{'service_description'}} = $row->{'host_id'}.";;".$row->{'service_id'}; $service_names{$row->{'host_id'}.";;".$row->{'service_id'}} = $row->{'host_name'}.";;".$row->{'service_description'}; @@ -59,7 +59,7 @@ sub getAllServices { } $query .= " AND hg.hg_id = hgr.hostgroup_hg_id"; - $sth = $centreon->query($query); + ($status, $sth) = $centreon->query($query); while(my $row = $sth->fetchrow_hashref()) { $service_ids{$row->{'host_name'}.";;".$row->{'service_description'}} = $row->{'host_id'}.";;".$row->{'service_id'}; $service_names{$row->{'host_id'}.";;".$row->{'service_id'}} = $row->{'host_name'}.";;".$row->{'service_description'}; diff --git a/centreon/lib/perl/centreon/reporting/CentreonServiceStateEvents.pm b/centreon/lib/perl/centreon/reporting/CentreonServiceStateEvents.pm index 350522e98c6..1b098044f4c 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonServiceStateEvents.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonServiceStateEvents.pm @@ -36,7 +36,7 @@ sub getStateEventDurations { " WHERE `start_time` < ".$end. " AND `end_time` > ".$start. " AND `state` < 4"; # NOT HANDLING PENDING STATE - my $sth = $centstorage->query($query); + my ($status, $sth) = $centstorage->query($query); while (my $row = $sth->fetchrow_hashref()) { if ($row->{"start_time"} < $start) { $row->{"start_time"} = $start; @@ -84,7 +84,7 @@ sub getLastStates { my $query = "SELECT `host_id`, `service_id`, `state`, `servicestateevent_id`, `end_time`, `in_downtime`". " FROM `servicestateevents`". " WHERE `last_update` = 1"; - my $sth = $centstorage->query($query); + my ($status, $sth) = $centstorage->query($query); while(my $row = $sth->fetchrow_hashref()) { my $serviceId = $row->{'host_id'}.";;".$row->{'service_id'}; if (defined($serviceNames->{$serviceId})) { @@ -191,7 +191,7 @@ sub getFirstLastIncidentTimes { my $centstorage = $self->{"centstorage"}; my $query = "SELECT min(`start_time`) as minc, max(`end_time`) as maxc FROM `servicestateevents`"; - my $sth = $centstorage->query($query); + my ($status, $sth) = $centstorage->query($query); my ($start, $end) = (0,0); if (my $row = $sth->fetchrow_hashref()) { ($start, $end) = ($row->{"minc"}, $row->{"maxc"}); diff --git a/centreon/lib/perl/centreon/script/eventReportBuilder.pm b/centreon/lib/perl/centreon/script/eventReportBuilder.pm index 0fc40df5906..103806797af 100644 --- a/centreon/lib/perl/centreon/script/eventReportBuilder.pm +++ b/centreon/lib/perl/centreon/script/eventReportBuilder.pm @@ -1,4 +1,6 @@ +package centreon::script::eventReportBuilder; + use warnings; use strict; use POSIX; @@ -50,7 +52,7 @@ sub exit_pgr() { sub getDbLayer() { my $self = shift; - my $res = $self->{cdb}->query("SELECT `value` FROM `options` WHERE `key` = 'broker'"); + my ($status, $res) = $self->{cdb}->query("SELECT `value` FROM `options` WHERE `key` = 'broker'"); if (my $row = $res->fetchrow_hashref()) { return $row->{'value'}; } @@ -60,11 +62,12 @@ sub getDbLayer() { # Initialize objects for program sub initVars { my $self = shift; + my $centstatus; # Getting centstatus database name - $self->{dbLayer} = getDbLayer(); + $self->{dbLayer} = $self->getDbLayer(); if ($self->{dbLayer} eq "ndo") { - my $sth = $self->{cdb}->query("SELECT db_name, db_host, db_port, db_user, db_pass FROM cfg_ndo2db WHERE activate = '1' LIMIT 1"); + my ($status, $sth) = $self->{cdb}->query("SELECT db_name, db_host, db_port, db_user, db_pass FROM cfg_ndo2db WHERE activate = '1' LIMIT 1"); if (my $row = $sth->fetchrow_hashref()) { #connecting to censtatus $centstatus = centreon::common::db->new(db => $row->{"db_name"}, @@ -138,7 +141,7 @@ sub rebuildIncidents { $self->{serviceEvents}->truncateStateEvents(); $self->{hostEvents}->truncateStateEvents(); # Getting first log and last log times - my ($start, $end) = $nagiosLog->getFirstLastLogTime(); + my ($start, $end) = $self->{nagiosLog}->getFirstLastLogTime(); my $periods = $self->getDaysFromPeriod($start, $end); # archiving logs for each days foreach(@$periods) { From b45e711163612e60ca22154d4bb253d6397d5889 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 21 Mar 2013 11:03:15 +0100 Subject: [PATCH 013/458] Finish migrate eventReportBuilder --- .../centreon/script/eventReportBuilder.pm | 130 +++++++++--------- 1 file changed, 65 insertions(+), 65 deletions(-) diff --git a/centreon/lib/perl/centreon/script/eventReportBuilder.pm b/centreon/lib/perl/centreon/script/eventReportBuilder.pm index 103806797af..9090e236e09 100644 --- a/centreon/lib/perl/centreon/script/eventReportBuilder.pm +++ b/centreon/lib/perl/centreon/script/eventReportBuilder.pm @@ -44,7 +44,7 @@ sub new { sub exit_pgr() { my $self = shift; - $self->{logger}->writeLogInfo("INFO", "Exiting program..."); + $self->{logger}->writeLogInfo("INFO", "Exiting program..."); exit (0); } @@ -52,24 +52,24 @@ sub exit_pgr() { sub getDbLayer() { my $self = shift; - my ($status, $res) = $self->{cdb}->query("SELECT `value` FROM `options` WHERE `key` = 'broker'"); - if (my $row = $res->fetchrow_hashref()) { - return $row->{'value'}; - } - return "ndo"; + my ($status, $res) = $self->{cdb}->query("SELECT `value` FROM `options` WHERE `key` = 'broker'"); + if (my $row = $res->fetchrow_hashref()) { + return $row->{'value'}; + } + return "ndo"; } # Initialize objects for program sub initVars { - my $self = shift; + my $self = shift; my $centstatus; - - # Getting centstatus database name - $self->{dbLayer} = $self->getDbLayer(); - if ($self->{dbLayer} eq "ndo") { - my ($status, $sth) = $self->{cdb}->query("SELECT db_name, db_host, db_port, db_user, db_pass FROM cfg_ndo2db WHERE activate = '1' LIMIT 1"); - if (my $row = $sth->fetchrow_hashref()) { - #connecting to censtatus + + # Getting centstatus database name + $self->{dbLayer} = $self->getDbLayer(); + if ($self->{dbLayer} eq "ndo") { + my ($status, $sth) = $self->{cdb}->query("SELECT db_name, db_host, db_port, db_user, db_pass FROM cfg_ndo2db WHERE activate = '1' LIMIT 1"); + if (my $row = $sth->fetchrow_hashref()) { + #connecting to censtatus $centstatus = centreon::common::db->new(db => $row->{"db_name"}, host => $row->{'db_host'}, port => $row->{'db_port'}, @@ -77,38 +77,38 @@ sub initVars { password => $row->{'db_pass'}, force => 0, logger => $self->{logger}); - } - } elsif ($self->{dbLayer} eq "broker") { - $centstatus = $self->{csdb}; - } else { - $self->{logger}->writeLogError("Unsupported database layer: " . $self->{dbLayer}); - $self->exit_pgr(); - } - - # classes to query database tables - $self->{host} = CentreonHost->new($self->{logger}, $self->{cdb}); - $self->{service} = CentreonService->new($self->{logger}, $self->{cdb}); - $self->{nagiosLog} = CentreonLog->new($self->{logger}, $self->{csdb}, $self->{dbLayer}); - my $centreonDownTime = CentreonDownTime->new($self->{logger}, $centstatus, $self->{dbLayer}); - my $centreonAck = CentreonAck->new($self->{logger}, $centstatus, $self->{dbLayer}); - $self->{serviceEvents} = CentreonServiceStateEvents->new($self->{logger}, $self->{csdb}, $centreonAck, $centreonDownTime); - $self->{hostEvents} = CentreonHostStateEvents->new($self->{logger}, $self->{csdb}, $centreonAck, $centreonDownTime); - - # Class that builds events - $self->{processEvents} = CentreonProcessStateEvents->new($self->{logger}, $self->{host}, $self->{service}, $self->{nagiosLog}, $self->{hostEvents}, $self->{serviceEvents}, $centreonDownTime, $self->{dbLayer}); + } + } elsif ($self->{dbLayer} eq "broker") { + $centstatus = $self->{csdb}; + } else { + $self->{logger}->writeLogError("Unsupported database layer: " . $self->{dbLayer}); + $self->exit_pgr(); + } + + # classes to query database tables + $self->{host} = centreon::reporting::CentreonHost->new($self->{logger}, $self->{cdb}); + $self->{service} = centreon::reporting::CentreonService->new($self->{logger}, $self->{cdb}); + $self->{nagiosLog} = centreon::reporting::CentreonLog->new($self->{logger}, $self->{csdb}, $self->{dbLayer}); + my $centreonDownTime = centreon::reporting::CentreonDownTime->new($self->{logger}, $centstatus, $self->{dbLayer}); + my $centreonAck = centreon::reporting::CentreonAck->new($self->{logger}, $centstatus, $self->{dbLayer}); + $self->{serviceEvents} = centreon::reporting::CentreonServiceStateEvents->new($self->{logger}, $self->{csdb}, $centreonAck, $centreonDownTime); + $self->{hostEvents} = centreon::reporting::CentreonHostStateEvents->new($self->{logger}, $self->{csdb}, $centreonAck, $centreonDownTime); + + # Class that builds events + $self->{processEvents} = centreon::reporting::CentreonProcessStateEvents->new($self->{logger}, $self->{host}, $self->{service}, $self->{nagiosLog}, $self->{hostEvents}, $self->{serviceEvents}, $centreonDownTime, $self->{dbLayer}); } -# For a given period returns in a table each +# For a given period returns in a table each sub getDaysFromPeriod { my $self = shift; - my ($start, $end) = (shift, shift); - - my @days; + my ($start, $end) = (shift, shift); + + my @days; # Check if $end is > to current time - my ($day,$month,$year) = (localtime(time))[3,4,5]; + my ($day,$month,$year) = (localtime(time))[3,4,5]; my $today_begin = mktime(0,0,0,$day,$month,$year,0,0,-1); if ($end > $today_begin) { - $end = $today_begin; + $end = $today_begin; } # get start day as mm/dd/yyyy 00:00 ($day,$month,$year) = (localtime($start))[3,4,5]; @@ -116,18 +116,18 @@ sub getDaysFromPeriod { my $previousDay = mktime(0,0,0,$day - 1,$month,$year,0,0,-1); while ($start < $end) { - # getting day beginning => 00h 00min - # if there is few hour gap (time change : winter/summer), we also readjust it - if ($start == $previousDay) { - $start = mktime(0,0,0, ++$day, $month, $year,0,0,-1); - } - # setting day beginning/end hour and minute with the value set in centreon DB - my $dayEnd =mktime(0, 0, 0, ++$day, $month, $year, 0, 0, -1); - my %period = ("day_start" => $start, "day_end" => $dayEnd); - $days[scalar(@days)] = \%period; - - $previousDay = $start; - $start = $dayEnd; + # getting day beginning => 00h 00min + # if there is few hour gap (time change : winter/summer), we also readjust it + if ($start == $previousDay) { + $start = mktime(0,0,0, ++$day, $month, $year,0,0,-1); + } + # setting day beginning/end hour and minute with the value set in centreon DB + my $dayEnd =mktime(0, 0, 0, ++$day, $month, $year, 0, 0, -1); + my %period = ("day_start" => $start, "day_end" => $dayEnd); + $days[scalar(@days)] = \%period; + + $previousDay = $start; + $start = $dayEnd; } return \@days; } @@ -142,12 +142,12 @@ sub rebuildIncidents { $self->{hostEvents}->truncateStateEvents(); # Getting first log and last log times my ($start, $end) = $self->{nagiosLog}->getFirstLastLogTime(); - my $periods = $self->getDaysFromPeriod($start, $end); + my $periods = $self->getDaysFromPeriod($start, $end); # archiving logs for each days foreach(@$periods) { - $self->{logger}->writeLogInfo("Processing period: ".localtime($_->{"day_start"})." => ".localtime($_->{"day_end"})); - $self->{processEvents}->parseHostLog($_->{"day_start"}, $_->{"day_end"}); - $self->{processEvents}->parseServiceLog($_->{"day_start"}, $_->{"day_end"}); + $self->{logger}->writeLogInfo("Processing period: ".localtime($_->{"day_start"})." => ".localtime($_->{"day_end"})); + $self->{processEvents}->parseHostLog($_->{"day_start"}, $_->{"day_end"}); + $self->{processEvents}->parseServiceLog($_->{"day_start"}, $_->{"day_end"}); } } @@ -161,18 +161,18 @@ sub run { $self->{logger}->writeLogInfo("Starting program..."); if (defined($self->{opt_rebuild})) { - $self->rebuildIncidents(); - }else { - my $currentTime = time; - my ($day,$month,$year) = (localtime($currentTime))[3,4,5]; - my $end = mktime(0,0,0,$day,$month,$year,0,0,-1); - my $start = mktime(0,0,0,$day-1,$month,$year,0,0,-1); - $self->{logger}->writeLogInfo("Processing period: ".localtime($start)." => ".localtime($end)); - $self->{processEvents}->parseHostLog($start, $end); - $self->{processEvents}->parseServiceLog($start, $end); + $self->rebuildIncidents(); + } else { + my $currentTime = time; + my ($day,$month,$year) = (localtime($currentTime))[3,4,5]; + my $end = mktime(0,0,0,$day,$month,$year,0,0,-1); + my $start = mktime(0,0,0,$day-1,$month,$year,0,0,-1); + $self->{logger}->writeLogInfo("Processing period: ".localtime($start)." => ".localtime($end)); + $self->{processEvents}->parseHostLog($start, $end); + $self->{processEvents}->parseServiceLog($start, $end); } - $self->exit_pgr(); + $self->exit_pgr(); } 1; From 00e31d8baf8aa48962403b1d89b381e4e438c391 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 31 May 2013 17:08:23 +0200 Subject: [PATCH 014/458] Mig dasboardBuilder Conflicts: bin/logAnalyser --- .../perl/centreon/script/dashboardBuilder.pm | 269 ++++++++++++++++++ 1 file changed, 269 insertions(+) create mode 100644 centreon/lib/perl/centreon/script/dashboardBuilder.pm diff --git a/centreon/lib/perl/centreon/script/dashboardBuilder.pm b/centreon/lib/perl/centreon/script/dashboardBuilder.pm new file mode 100644 index 00000000000..c6a70124a72 --- /dev/null +++ b/centreon/lib/perl/centreon/script/dashboardBuilder.pm @@ -0,0 +1,269 @@ + +package centreon::script::dashboardBuilder; + +use warnings; +use strict; +use POSIX; +use Time::Local; + +use centreon::reporting::CentreonHost; +use centreon::reporting::CentreonService; +use centreon::reporting::CentreonServiceStateEvents; +use centreon::reporting::CentreonHostStateEvents; +use centreon::reporting::CentreonDashboard; +use centreon::script; + +use base qw(centreon::script); + +my @weekDays = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("dashboardBuilder", + centreon_db_conn => 1, + centstorage_db_conn => 1 + ); + + bless $self, $class; + $self->add_options( + "r" => \$self->{opt_rebuild}, "rebuild" => \$self->{opt_rebuild}, + "s=s" => \$self->{opt_startperiod}, "start-period=s" => \$self->{opt_startperiod}, + "e=s" => \$self->{opt_endperiod}, "end-period=s" => \$self->{opt_endperiod}, + "host-only" => \$self->{opt_hostonly}, + "service-only" => \$self->{opt_serviceonly}, + ); + $self->{serviceEvents} = undef; + $self->{hostEvents} = undef; + $self->{dashboard} = undef; + $self->{liveService} = undef; + $self->{service} = undef; + $self->{host} = undef; + $self->{dbLayer} = undef; + return $self; +} + +# program exit function +sub exit_pgr() { + my $self = shift; + + $self->{logger}->writeLogInfo("INFO", "Exiting program..."); + exit (0); +} + +# get informations about an hidden feature +# reporting can be calculated on a specific time range for each day of the week +sub getLiveService { + my $self = shift; + my %result = (); + + my ($status, $sth) = $self->{cdb}->query("SELECT * FROM `contact_param` WHERE `cp_contact_id` is null"); + while (my $row = $sth->fetchrow_hashref()) { + $result{$row->{"cp_key"}} = $row->{"cp_value"}; + } + $sth->finish; + # verifying if all variables are set + if (!defined($result{"report_hour_start"})) { + $result{"report_hour_start"} = 0; + } + if (!defined($result{"report_minute_start"})) { + $result{"report_minute_start"} = 0; + } + if (!defined($result{"report_hour_end"})) { + $result{"report_hour_end"} = 24; + } + if (!defined($result{"report_minute_end"})) { + $result{"report_minute_end"} = 0; + } + foreach(@weekDays) { + my $day = $_; + if (!defined($result{"report_".$day})) { + $result{"report_".$day} = 1; + } + } + return(\%result); +} + +# Initialize objects for program +sub initVars { + my $self = shift; + + # classes to query database tables + $self->{host} = centreon::reporting::CentreonHost->new($self->{logger}, $self->{cdb}); + $self->{service} = centreon::reporting::CentreonService->new($self->{logger}, $self->{cdb}); + $self->{serviceEvents} = centreon::reporting::CentreonServiceStateEvents->new($self->{logger}, $self->{csdb}); + $self->{hostEvents} = centreon::reporting::CentreonHostStateEvents->new($self->{logger}, $self->{csdb}); + + # Class that builds events + $self->{dashboard} = centreon::reporting::CentreonDashboard->new($self->{logger}, $self->{csdb}); + $self->{liveService} = $self->getLiveService(); +} + +# For a given period returns in a table each +sub getDaysFromPeriod { + my $self = shift; + my ($start, $end) = (shift, shift); + + my @days; + # Check if $end is > to current time + my ($day,$month,$year) = (localtime(time))[3,4,5]; + my $todayStart = mktime(0,0,0,$day,$month,$year,0,0,-1); + if ($end > $todayStart) { + $end = $todayStart; + } + # get start day as mm/dd/yyyy 00:00 + ($day,$month,$year) = (localtime($start))[3,4,5]; + $start = mktime(0,0,0,$day,$month,$year,0,0,-1); + my $previousDay = mktime(0,0,0,$day - 1,$month,$year,0,0,-1); + + while ($start < $end) { + # getting day beginning => 00h 00min + # if there is few hour gap (time change : winter/summer), we also readjust it + if ($start == $previousDay) { + $start = mktime(0,0,0, ++$day, $month, $year,0,0,-1); + } + my $currentDayOfWeek = (localtime($start))[6]; + # If in the configuration, this day of week is not selected, the reporting is not calculated + if (defined($self->{liveService}->{"report_".$weekDays[$currentDayOfWeek]}) && $self->{liveService}->{"report_".$weekDays[$currentDayOfWeek]} == 1) { + # setting reporting date and time ranges + my $dayStart = mktime(0,$self->{liveService}->{"report_minute_start"},$self->{liveService}->{"report_hour_start"},$day,$month,$year,0,0,-1); + my $dayEnd = mktime(0,$self->{liveService}->{"report_minute_end"},$self->{liveService}->{"report_hour_end"},$day,$month,$year,0,0,-1); + my %period = ("day_start" => $dayStart, "day_end" => $dayEnd); + $days[scalar(@days)] = \%period; + } else { + $day++; + } + + $previousDay = $start; + $start = mktime(0,0,0, $day, $month, $year,0,0,-1); + } + return \@days; +} + +# rebuild all events +sub rebuildIncidents { + my $self = shift; + my ($start, $end, $purgeType, $hostOnly, $serviceOnly) = (shift, shift, shift, shift, shift); + + if (!defined($start) || !defined($end)) { + $self->{logger}->writeLogError("Cannot determine reporting rebuild period"); + } + # purge tables in order to rebuild statistics + my $periods = $self->getDaysFromPeriod($start, $end); + if (!scalar(@$periods)) { + $self->{logger}->writeLogInfo("Incorrect rebuild period"); + } + if ($purgeType eq "truncate") { + $self->{dashboard}->truncateServiceStats(); + $self->{dashboard}->truncateHostStats(); + }else { + $self->{dashboard}->deleteServiceStats($start, $end); + $self->{dashboard}->deleteHostStats($start, $end); + } + if (defined($start) && defined($end) && !$serviceOnly) { + my ($allIds, $allNames) = $self->{host}->getAllHosts(0); + # archiving logs for each days + foreach(@$periods) { + $self->{logger}->writeLogInfo("[HOST] Processing period: ".localtime($_->{"day_start"})." => ".localtime($_->{"day_end"})); + my $hostStateDurations = $self->{hostEvents}->getStateEventDurations($_->{"day_start"}, $_->{"day_end"}); + $self->{dashboard}->insertHostStats($allNames, $hostStateDurations, $_->{"day_start"}, $_->{"day_end"}); + } + } + if (defined($start) && defined($end) && !$hostOnly) { + my ($allIds, $allNames) = $service->getAllServices(0); + # archiving logs for each days + foreach(@$periods) { + $self->{logger}->writeLogInfo("[SERVICE] Processing period: ".localtime($_->{"day_start"})." => ".localtime($_->{"day_end"})); + my $serviceStateDurations = $self->{serviceEvents}->getStateEventDurations($_->{"day_start"}, $_->{"day_end"}); + $self->{dashboard}->insertServiceStats($allNames, $serviceStateDurations, $_->{"day_start"}, $_->{"day_end"}); + } + } +} + +# returns the reporting rebuild period that could be retrieved form DB or given in parameter +# returns also reporting tables purge type truncate or delete for a specific period +sub getRebuildOptions { + my $self = shift; + my ($paramStartDate, $paramEndDate, $hostOnly, $serviceOnly) = (shift, shift, shift, shift); + + if (!defined($hostOnly)) { + $hostOnly = 0; + } else { + $hostOnly = 1; + } + if (!defined($serviceOnly)) { + $serviceOnly = 0; + } else { + $serviceOnly = 1; + } + my ($start, $end); + my $purgeType = "truncate"; + if (defined($paramStartDate)){ + if ($paramStartDate =~ /^([0-9]{4})\-([0-9]{2})\-([0-9]{2})$/) { + $start = mktime(0,0,0,$3,$2 - 1,$1 - 1900,0,0,-1); + $purgeType = "delete"; + }else { + $self->{logger}->writeLogError("Bad paramater syntax for option [-s|--period-start]. Syntax example: 2011-11-09"); + } + } + if (defined($paramEndDate)){ + if ($paramEndDate =~ /^([0-9]{4})\-([0-9]{2})\-([0-9]{2})$/) { + $end = mktime(0,0,0,$3,$2 - 1,$1 - 1900,0,0,-1); + $purgeType = "delete"; + }else { + $self->{logger}->writeLogError("Bad paramater syntax for option [-e|--period-end]. Syntax example: 2011-11-09"); + } + } + + my ($dbStart, $dbEnd) = $self->{hostEvents}->getFirstLastIncidentTimes(); + if (!defined($start)) { + $start = $dbStart; + } + if (!defined($end)) { + $end = $dbEnd; + } + return ($start, $end, $purgeType, $hostOnly, $serviceOnly); +} + + +sub run { + my $self = shift; + + $self->SUPER::run(); + $self->{logger}->redirect_output(); + $self->initVars(); + + $self->{logger}->writeLogInfo("Starting program..."); + + if (defined($self->{opt_rebuild})) { + $self->rebuildIncidents($self->getRebuildOptions($self->{opt_startperiod}, $self->{opt_endperiod}, $self->{opt_hostonly}, $self->{opt_serviceonly})); + }else { + my $currentTime = time; + my ($day,$month,$year, $dayOfWeek) = (localtime($currentTime))[3,4,5,6]; + # getting day of week of date to process + if ($dayOfWeek == 0) { + $dayOfWeek = 6; + }else { + $dayOfWeek--; + } + # If in the configuration, this day of week is not selected, the reporting is not calculated + if (defined($self->{liveService}->{"report_".$weekDays[$dayOfWeek]}) && $self->{liveService}->{"report_".$weekDays[$dayOfWeek]} != 1) { + $self->{logger}->writeLogInfo("Reporting must not be calculated for this day, check your configuration"); + $self->exit_pgr(); + } + # setting reporting date and time ranges + my $end = mktime(0,$self->{liveService}->{"report_minute_end"},$self->{liveService}->{"report_hour_end"},$day - 1,$month,$year,0,0,-1); + my $start = mktime(0,$self->{liveService}->{"report_minute_start"},$self->{liveService}->{"report_hour_start"},$day - 1,$month,$year,0,0,-1); + + my ($serviceIds, $serviceNames) = $self->{service}->getAllServices(0); + my ($hostIds, $hostNames) = $self->{host}->getAllHosts(0); + $self->{logger}->writeLogInfo("Processing period: ".localtime($start)." => ".localtime($end)); + my $hostStateDurations = $self->{hostEvents}->getStateEventDurations($start, $end); + $self->{dashboard}->insertHostStats($hostNames, $hostStateDurations, $start, $end); + my $serviceStateDurations = $self->{serviceEvents}->getStateEventDurations($start, $end); + $self->{dashboard}->insertServiceStats($serviceNames, $serviceStateDurations, $start, $end); + } + + $self->exit_pgr(); +} + +1; From bd0150d42163e5d13212245b146d8c0f15196dcd Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 21 Mar 2013 11:59:36 +0100 Subject: [PATCH 015/458] Finish dashboard --- centreon/lib/perl/centreon/script/dashboardBuilder.pm | 6 +++--- centreon/lib/perl/centreon/script/eventReportBuilder.pm | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/centreon/script/dashboardBuilder.pm b/centreon/lib/perl/centreon/script/dashboardBuilder.pm index c6a70124a72..d2c19ff456f 100644 --- a/centreon/lib/perl/centreon/script/dashboardBuilder.pm +++ b/centreon/lib/perl/centreon/script/dashboardBuilder.pm @@ -46,7 +46,7 @@ sub new { sub exit_pgr() { my $self = shift; - $self->{logger}->writeLogInfo("INFO", "Exiting program..."); + $self->{logger}->writeLogInfo("Exiting program..."); exit (0); } @@ -168,8 +168,8 @@ sub rebuildIncidents { $self->{dashboard}->insertHostStats($allNames, $hostStateDurations, $_->{"day_start"}, $_->{"day_end"}); } } - if (defined($start) && defined($end) && !$hostOnly) { - my ($allIds, $allNames) = $service->getAllServices(0); + if (defined($start) && defined($end) && !$hostOnly) { + my ($allIds, $allNames) = $self->{service}->getAllServices(0); # archiving logs for each days foreach(@$periods) { $self->{logger}->writeLogInfo("[SERVICE] Processing period: ".localtime($_->{"day_start"})." => ".localtime($_->{"day_end"})); diff --git a/centreon/lib/perl/centreon/script/eventReportBuilder.pm b/centreon/lib/perl/centreon/script/eventReportBuilder.pm index 9090e236e09..c78fe113a86 100644 --- a/centreon/lib/perl/centreon/script/eventReportBuilder.pm +++ b/centreon/lib/perl/centreon/script/eventReportBuilder.pm @@ -44,7 +44,7 @@ sub new { sub exit_pgr() { my $self = shift; - $self->{logger}->writeLogInfo("INFO", "Exiting program..."); + $self->{logger}->writeLogInfo("Exiting program..."); exit (0); } From cfbb5637c65bc59112bf811e34b3e0e8dcbcb78d Mon Sep 17 00:00:00 2001 From: Antoine Nguyen Date: Thu, 21 Mar 2013 15:45:01 +0100 Subject: [PATCH 016/458] Using prepared statements. --- .../lib/perl/centreon/script/logAnalyser.pm | 135 +++++++----------- 1 file changed, 49 insertions(+), 86 deletions(-) diff --git a/centreon/lib/perl/centreon/script/logAnalyser.pm b/centreon/lib/perl/centreon/script/logAnalyser.pm index 27fa5a0faa4..f8c528454a7 100644 --- a/centreon/lib/perl/centreon/script/logAnalyser.pm +++ b/centreon/lib/perl/centreon/script/logAnalyser.pm @@ -18,7 +18,7 @@ sub new { $self->add_options( "a" => \$self->{opt_a}, "archives" => \$self->{opt_a}, "p=s" => \$self->{opt_p}, "poller" => \$self->{opt_p}, - "s=s" => \$self->{opt_s}, "startdate" => \$self->{opt_s} + "s=s" => \$self->{opt_s}, "startdate=s" => \$self->{opt_s} ); $self->{launch_time} = time(); $self->{msg_type5_disabled} = 0; @@ -79,8 +79,10 @@ EOQ } sub commit_to_log { - my ($self, $instance, $ctime, $counter) = @_; + my ($self, $sth, $log_table_rows, $instance, $ctime, $counter) = @_; + my @tuple_status; + $sth->execute_for_fetch(sub { shift @$log_table_rows }, \@tuple_status); $self->{csdb}->do(<<"EOQ"); UPDATE instance SET log_flag='$counter', last_ctime='$ctime' WHERE instance_id = '$instance' EOQ @@ -98,6 +100,7 @@ sub parse_file($$$) { my $ctime = 0; my $logdir = "$self->{centreon_config}->{VarLib}/log/$instance"; my ($last_position, $nbqueries, $counter) = (0, 0, 0); + my @log_table_rows; if (!-d $logdir) { mkpath($logdir); @@ -139,135 +142,95 @@ EOQ $self->{csdb}->transaction_mode(1); eval { + my $sth = $self->{csdb}->query(<<"EOQ"); +INSERT INTO log (ctime, host_name, service_description, status, output, notification_cmd, notification_contact, type, retry, msg_type, instance) +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) +EOQ + while () { my $cur_ctime; if ($_ =~ m/^\[([0-9]*)\]\sSERVICE ALERT\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; - $tab[0] =~ s/\\/\\\\/g; - $tab[0] =~ s/\'/\\\'/g; - $tab[1] =~ s/\\/\\\\/g; - $tab[1] =~ s/\'/\\\'/g; - $tab[5] =~ s/\\/\\\\/g; - $tab[5] =~ s/\'/\\\'/g; - my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `host_name` , `service_description`, `status`, `type`, `retry`, `output`, `instance`) VALUES ('0', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."','".$tab[4]."','".$tab[5]."', '".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{cdbs}->quote($_) : "" } + ($cur_ctime, $tab[0], $tab[1], $tab[2], $tab[5], '', '', $tab[3], $tab[4], '0', $instance); } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST ALERT\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; - $tab[0] =~ s/\\/\\\\/g; - $tab[0] =~ s/\'/\\\'/g; - if (defined($tab[4]) && $tab[4]) { - $tab[4] =~ s/\\/\\\\/g; - $tab[4] =~ s/\'/\\\'/g; - } - my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `host_name` , `status`, `type`, `retry`, `output`, `instance`) VALUES ('1', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."','".$tab[3]."','".$tab[4]."', '".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{csdb}->quote($_) : "" } + ($cur_ctime, $tab[0], '', $tab[1], $tab[4], '', '', $tab[2], $tab[3], '1', $instance); } elsif ($_ =~ m/^\[([0-9]*)\]\sSERVICE NOTIFICATION\:\s(.*)$/) { my @tab = split(/;/, $2); - $cur_ctime = $1; - $tab[2] =~ s/\\/\\\\/g; - $tab[2] =~ s/\'/\\\'/g; - $tab[1] =~ s/\\/\\\\/g; - $tab[1] =~ s/\'/\\\'/g; - if (defined($tab[5])) { - $tab[5] =~ s/\\/\\\\/g; - $tab[5] =~ s/\'/\\\'/g; - } else { - $tab[5] = ""; - } - my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `host_name` , `service_description`, `status`, `notification_cmd`, `notification_contact`, `output`, `instance`) VALUES ('2', '$cur_ctime', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."', '".$tab[4]."','".$tab[0]."','".$tab[5]."', '".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{csdb}->quote($_) : "" } + ($cur_ctime, $tab[1], $tab[2], $tab[3], $tab[5], $tab[4], $tab[0], '', '', '2', $instance); } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST NOTIFICATION\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; - if (defined($tab[4])) { - $tab[4] =~ s/\\/\\\\/g; - $tab[4] =~ s/\'/\\\'/g; - } else { - $tab[4] = ""; - } - my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `notification_contact`, `host_name` , `status`, `notification_cmd`, `output`, `instance`) VALUES ('3', '$cur_ctime', '".$tab[0]."','".$tab[1]."', '".$tab[2]."', '".$tab[3]."','".$tab[4]."', '".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{csdb}->quote($_) : "" } + ($cur_ctime, $tab[1], '', $tab[2], $tab[4], $tab[3], $tab[0], '', '', '3', $instance); } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sHOST\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; - $tab[0] =~ s/\\/\\\\/g; - $tab[0] =~ s/\'/\\\'/g; - my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name` , `status`, `type`, `instance`) VALUES ('7', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{csdb}->quote($_) : "" } + ($cur_ctime, $tab[0], '', $tab[1], '', '', '', $tab[2], '', '7', $instance); } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sSERVICE\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; - $tab[0] =~ s/\\/\\\\/g; - $tab[0] =~ s/\'/\\\'/g; - $tab[1] =~ s/\\/\\\\/g; - $tab[1] =~ s/\'/\\\'/g; - my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `service_description` , `status`, `type`, `instance`) VALUES ('6', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."', '".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{csdb}->quote($_) : "" } + ($cur_ctime, $tab[0], $tab[1], $tab[2], '', '', '', $tab[3], '', '6', $instance); } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sHOST\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; - $tab[0] =~ s/\\/\\\\/g; - $tab[0] =~ s/\'/\\\'/g; - my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name` , `status`, `type`, `instance`) VALUES ('9', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{csdb}->quote($_) : "" } + ($cur_ctime, $tab[0], '', $tab[1], '', '', '', $tab[2], '', '9', $instance); } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sSERVICE\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; - $tab[0] =~ s/\\/\\\\/g; - $tab[0] =~ s/\'/\\\'/g; - $tab[1] =~ s/\\/\\\\/g; - $tab[1] =~ s/\'/\\\'/g; - my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `service_description` , `status`, `type`, `instance`) VALUES ('8', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[2]."', '".$tab[3]."', '".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{csdb}->quote($_) : "" } + ($cur_ctime, $tab[0], $tab[1], $tab[2], '', '', '', $tab[3], '', '8', $instance); } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_SVC\_PROBLEM\;(.*)$/) { $cur_ctime = $1; my @tab = split(/;/, $2); - $tab[0] =~ s/\\/\\\\/g; - $tab[0] =~ s/\'/\\\'/g; - $tab[1] =~ s/\\/\\\\/g; - $tab[1] =~ s/\'/\\\'/g; - if (!defined($tab[6])) { - $tab[6] = ""; - } - $tab[6] =~ s/\\/\\\\/g; - $tab[6] =~ s/\'/\\\'/g; - my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `service_description`, `notification_contact`, `output`, `instance`) VALUES ('10', '$cur_ctime', '".$tab[0]."', '".$tab[1]."', '".$tab[5]."', '".$tab[6]."','".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{csdb}->quote($_) : "" } + ($cur_ctime, $tab[0], $tab[1], '', $tab[6], '', $tab[5], '', '', '10', $instance); } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_HOST\_PROBLEM\;(.*)$/) { $cur_ctime = $1; my @tab = split(/;/, $2); - $tab[0] =~ s/\\/\\\\/g; - $tab[0] =~ s/\'/\\\'/g; - $tab[5] =~ s/\\/\\\\/g; - $tab[5] =~ s/\'/\\\'/g; - my $rq = "INSERT INTO `log` (`msg_type`, `ctime`, `host_name`, `notification_contact`, `output`, `instance`) VALUES ('11', '$cur_ctime', '".$tab[0]."', '".$tab[4]."', '".$tab[5]."','".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{csdb}->quote($_) : "" } + ($cur_ctime, $tab[0], '', '', $tab[5], '', $tab[4], '', '', '11', $instance); } elsif ($_ =~ m/^\[([0-9]*)\]\sWarning\:\s(.*)$/) { my $tab = $2; $cur_ctime = $1; - $tab =~ s/\\/\\\\/g; - $tab =~ s/\'/\\\'/g; - my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `output`, `instance`) VALUES ('4','$cur_ctime', '".$tab."', '".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{csdb}->quote($_) : "" } + ($cur_ctime, '', '', '', $tab, '', '', '', '', '4', $instance); } elsif ($_ =~ m/^\[([0-9]*)\]\s(.*)$/ && (!$self->{msg_type5_disabled})) { $cur_ctime = $1; my $tab = $2; - $tab =~ s/\\/\\\\/g; - $tab =~ s/\'/\\\'/g; - my $rq = "INSERT INTO `log` (`msg_type`,`ctime`, `output`, `instance`) VALUES ('5','$cur_ctime', '".$tab."', '".$instance."')"; - my $res = $self->{csdb}->do($rq); + push @log_table_rows, + map { defined $_ ? $self->{csdb}->quote($_) : "" } + ($cur_ctime, '', '', '', $tab, '', '', '', '', '5', $instance); } $counter++; $nbqueries++; if ($nbqueries == $self->{queries_per_transaction}) { - $self->commit_to_log($instance, $ctime, $counter); + $self->commit_to_log($sth, \@log_table_rows, $instance, $ctime, $counter); $nbqueries = 0; + @log_table_rows = (); } } - $self->commit_to_log($instance, $ctime, $counter); + $self->commit_to_log($sth, \@log_table_rows, $instance, $ctime, $counter); }; close FILE; if ($@) { From 03163058bce298f33d1671cd144fe4fb3e9004c7 Mon Sep 17 00:00:00 2001 From: Antoine Nguyen Date: Thu, 21 Mar 2013 16:48:36 +0100 Subject: [PATCH 017/458] Few fixes. --- .../lib/perl/centreon/script/logAnalyser.pm | 39 +++++++------------ 1 file changed, 14 insertions(+), 25 deletions(-) diff --git a/centreon/lib/perl/centreon/script/logAnalyser.pm b/centreon/lib/perl/centreon/script/logAnalyser.pm index f8c528454a7..61aa94e5799 100644 --- a/centreon/lib/perl/centreon/script/logAnalyser.pm +++ b/centreon/lib/perl/centreon/script/logAnalyser.pm @@ -142,7 +142,7 @@ EOQ $self->{csdb}->transaction_mode(1); eval { - my $sth = $self->{csdb}->query(<<"EOQ"); + my $sth = $self->{csdb}->{instance}->prepare(<<"EOQ"); INSERT INTO log (ctime, host_name, service_description, status, output, notification_cmd, notification_contact, type, retry, msg_type, instance) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) EOQ @@ -154,73 +154,62 @@ EOQ my @tab = split(/;/, $2); $cur_ctime = $1; push @log_table_rows, - map { defined $_ ? $self->{cdbs}->quote($_) : "" } - ($cur_ctime, $tab[0], $tab[1], $tab[2], $tab[5], '', '', $tab[3], $tab[4], '0', $instance); + [($cur_ctime, $tab[0], $tab[1], $tab[2], $tab[5], '', '', $tab[3], $tab[4], '0', $instance)]; } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST ALERT\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; push @log_table_rows, - map { defined $_ ? $self->{csdb}->quote($_) : "" } - ($cur_ctime, $tab[0], '', $tab[1], $tab[4], '', '', $tab[2], $tab[3], '1', $instance); + [($cur_ctime, $tab[0], '', $tab[1], $tab[4], '', '', $tab[2], $tab[3], '1', $instance)]; } elsif ($_ =~ m/^\[([0-9]*)\]\sSERVICE NOTIFICATION\:\s(.*)$/) { my @tab = split(/;/, $2); + $cur_ctime = $1; push @log_table_rows, - map { defined $_ ? $self->{csdb}->quote($_) : "" } - ($cur_ctime, $tab[1], $tab[2], $tab[3], $tab[5], $tab[4], $tab[0], '', '', '2', $instance); + [($cur_ctime, $tab[1], $tab[2], $tab[3], $tab[5], $tab[4], $tab[0], '', 0, '2', $instance)]; } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST NOTIFICATION\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; push @log_table_rows, - map { defined $_ ? $self->{csdb}->quote($_) : "" } - ($cur_ctime, $tab[1], '', $tab[2], $tab[4], $tab[3], $tab[0], '', '', '3', $instance); + [($cur_ctime, $tab[1], '', $tab[2], $tab[4], $tab[3], $tab[0], '', 0, '3', $instance)]; } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sHOST\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; push @log_table_rows, - map { defined $_ ? $self->{csdb}->quote($_) : "" } - ($cur_ctime, $tab[0], '', $tab[1], '', '', '', $tab[2], '', '7', $instance); + [($cur_ctime, $tab[0], '', $tab[1], '', '', '', $tab[2], 0, '7', $instance)]; } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sSERVICE\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; push @log_table_rows, - map { defined $_ ? $self->{csdb}->quote($_) : "" } - ($cur_ctime, $tab[0], $tab[1], $tab[2], '', '', '', $tab[3], '', '6', $instance); + [($cur_ctime, $tab[0], $tab[1], $tab[2], '', '', '', $tab[3], 0, '6', $instance)]; } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sHOST\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; push @log_table_rows, - map { defined $_ ? $self->{csdb}->quote($_) : "" } - ($cur_ctime, $tab[0], '', $tab[1], '', '', '', $tab[2], '', '9', $instance); + [($cur_ctime, $tab[0], '', $tab[1], '', '', '', $tab[2], 0, '9', $instance)]; } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sSERVICE\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); $cur_ctime = $1; push @log_table_rows, - map { defined $_ ? $self->{csdb}->quote($_) : "" } - ($cur_ctime, $tab[0], $tab[1], $tab[2], '', '', '', $tab[3], '', '8', $instance); + [($cur_ctime, $tab[0], $tab[1], $tab[2], '', '', '', $tab[3], 0, '8', $instance)]; } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_SVC\_PROBLEM\;(.*)$/) { $cur_ctime = $1; my @tab = split(/;/, $2); push @log_table_rows, - map { defined $_ ? $self->{csdb}->quote($_) : "" } - ($cur_ctime, $tab[0], $tab[1], '', $tab[6], '', $tab[5], '', '', '10', $instance); + [($cur_ctime, $tab[0], $tab[1], '', $tab[6], '', $tab[5], '', 0, '10', $instance)]; } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_HOST\_PROBLEM\;(.*)$/) { $cur_ctime = $1; my @tab = split(/;/, $2); push @log_table_rows, - map { defined $_ ? $self->{csdb}->quote($_) : "" } - ($cur_ctime, $tab[0], '', '', $tab[5], '', $tab[4], '', '', '11', $instance); + [($cur_ctime, $tab[0], '', '', $tab[5], '', $tab[4], '', 0, '11', $instance)]; } elsif ($_ =~ m/^\[([0-9]*)\]\sWarning\:\s(.*)$/) { my $tab = $2; $cur_ctime = $1; push @log_table_rows, - map { defined $_ ? $self->{csdb}->quote($_) : "" } - ($cur_ctime, '', '', '', $tab, '', '', '', '', '4', $instance); + [($cur_ctime, '', '', '', $tab, '', '', '', 0, '4', $instance)]; } elsif ($_ =~ m/^\[([0-9]*)\]\s(.*)$/ && (!$self->{msg_type5_disabled})) { $cur_ctime = $1; my $tab = $2; push @log_table_rows, - map { defined $_ ? $self->{csdb}->quote($_) : "" } - ($cur_ctime, '', '', '', $tab, '', '', '', '', '5', $instance); + [($cur_ctime, '', '', '', $tab, '', '', '', 0, '5', $instance)]; } $counter++; $nbqueries++; From f2e9cbc9c7bae950729d809a77d5bd5ae0163cb3 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 21 Mar 2013 17:20:06 +0100 Subject: [PATCH 018/458] Beginning trapd mig --- centreon/lib/perl/centreon/common/logger.pm | 9 + .../lib/perl/centreon/script/centreontrapd.pm | 623 ++++++++++++++++ centreon/lib/perl/centreon/trapd/lib.pm | 685 ++++++++++++++++++ 3 files changed, 1317 insertions(+) create mode 100644 centreon/lib/perl/centreon/script/centreontrapd.pm create mode 100644 centreon/lib/perl/centreon/trapd/lib.pm diff --git a/centreon/lib/perl/centreon/common/logger.pm b/centreon/lib/perl/centreon/common/logger.pm index 3891c90effd..22611382df9 100644 --- a/centreon/lib/perl/centreon/common/logger.pm +++ b/centreon/lib/perl/centreon/common/logger.pm @@ -77,6 +77,15 @@ sub is_file_mode { return 0; } +sub is_debug { + my $self = shift; + + if (($self->{severity} & 4) == 0) { + return 0; + } + return 1; +} + sub syslog_mode($$$) { my ($self, $logopt, $facility) = @_; diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm new file mode 100644 index 00000000000..834832634a8 --- /dev/null +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -0,0 +1,623 @@ + +package centreon::script::trapd; + +use strict; +use warnings; +use centreon::script; +use centreon::common::db; +use centreon::trapd::lib; + +use base qw(centreon::script); +use vars qw(%centreontrapd_config); + +my %handlers = ('TERM' => {}, 'HUP' => {}); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("centreontrapd", + centreon_db_conn => 0, + centstorage_db_conn => 0 + ); + + bless $self, $class; + $self->add_options( + "config-extra" => \$self->{opt_extra}, + ); + + my %centreontrapd_default_config = + ( + daemon => 0, + spool_directory => "/var/spool/centreontrapd/", + sleep => 2, + use_trap_time => 1, + net_snmp_perl_enable => 1, + mibs_environment => '', + remove_backslash_from_quotes => 1, + dns_enable => 0, + separator => ' ', + strip_domain => 0, + strip_domain_list => (), + duplicate_trap_window => 1, + date_format => "", + time_format => "", + date_time_format => "", + cache_unknown_traps_enable => 1, + cache_unknown_traps_retention => 600, + cache_unknown_traps_file => "/tmp/centreontrapd.cache", + mode => 0, + cmdFile => "/var/lib/centreon/centcore.cmd", + cmd_timeout => 10, + centreon_user => "centreon" + ); + + if (!defined($self->{opt_extra})) { + $self->{opt_extra} = "/etc/centreon/centreontrapd.pm"; + } + if (-f $self->{opt_extra}) { + require $self->{opt_extra}; + } else { + $self->{logger}->writeLogInfo("Can't find extra config file $self->{opt_extra}"); + } + + $self->{centreontrapd_config} = {%centreontrapd_default_config, %centreontrapd_config}; + + $self->{htmlentities} = 0; + @{$self->{var}} = undef; # Variables of trap received by SNMPTRAPD + @{$self->{entvar}} = undef; # Enterprise variable values of trap received by SNMPTRAPD + @{$self->{entvarname}} = undef; # Enterprise variable names of trap received by SNMPTRAPD + $self->{agent_dns_name} = undef; + $self->{trap_date} = undef; + $self->{trap_time} = undef; + $self->{trap_date_time} = undef; + $self->{trap_date_time_epoch} = undef; + %{$self->{duplicate_traps}} = undef; + $self->{timetoreload} = 0; + $self->{timetodie} = 0; + @{self->{filenames}} = undef; + $self->{input} = undef; + $self->{oids_cache} = undef; + $self->{last_cache_time} = undef; + $self->{whoami} = undef; + + $self->{cmdFile} = undef; + + # Daemon Only + if ($self->{centreontrapd_config}->{daemon} == 0) { + $self->set_signal_handlers; + } + return $self; +} + +sub set_signal_handlers { + my $self = shift; + + $SIG{TERM} = \&class_handle_TERM; + $handlers{TERM}->{$self} = sub { $self->handle_TERM() }; + $SIG{HUP} = \&class_handle_HUP; + $handlers{HUP}->{$self} = sub { $self->handle_HUP() }; +} + +sub class_handle_TERM { + foreach (keys %{$handlers{TERM}}) { + &{$handlers{TERM}->{$_}}(); + } +} + +sub class_handle_HUP { + foreach (keys %{$handlers{HUP}}) { + &{$handlers{HUP}->{$_}}(); + } +} + +sub handle_TERM { + my $self = shift; + $self->{timetodie} = 1; +} + +sub handle_HUP { + my $self = shift; + $self->{timetoreload} = 1; +} + +sub reload_config { + my $self = shift; + my $file = $_[0]; + + unless (my $return = do $file) { + $self->{logger}->writeLogError("couldn't parse $file: $@") if $@; + $self->{logger}->writeLogError("couldn't do $file: $!") unless defined $return; + $self->{logger}->writeLogError("couldn't run $file") unless $return; + } +} + +############################### +## Execute a command Nagios or Centcore +# +sub send_command { + eval { + local $SIG{ALRM} = sub { die "TIMEOUT"; }; + alarm($centrapmanager_cmd_timeout); + system @_; + alarm(0); + }; + if ($@) { + if ($@ =~ "TIMEOUT") { + logit("ERROR: Send command timeout", "EE"); + return 0; + } + } + return 1; +} + +############################### +## GET HOSTNAME FROM IP ADDRESS +# +sub get_hostinfos($$$) { + my %host = (); + + my $sth = $_[0]->prepare("SELECT host_id, host_name FROM host WHERE host_address='$_[1]' OR host_address='$_[2]'"); + $sth->execute(); + while (my ($host_id, $host_name) = $sth->fetchrow_array()) { + $host{$host_id} = $host_name; + } + $sth->finish(); + return %host; +} + +############################### +## GET host location +# +sub get_hostlocation($$) { + my $sth = $_[0]->prepare("SELECT localhost FROM host, `ns_host_relation`, nagios_server WHERE host.host_id = ns_host_relation.host_host_id AND ns_host_relation.nagios_server_id = nagios_server.id AND host.host_name = '".$_[1]."'"); + $sth->execute(); + if ($sth->rows()){ + my $temp = $sth->fetchrow_array(); + $sth->finish(); + return $temp; + } else { + return 0; + } +} + +############################## +## Connect to MySQL +# +sub connectDB() { + my $dbh = DBI->connect("dbi:mysql:".$mysql_database_oreon.";host=".$mysql_host, $mysql_user, $mysql_passwd) or myDie("Echec de la connexion"); + return $dbh; +} + +################################## +## GET nagios server id for a host +# +sub get_hostNagiosServerID($$) { + my $sth = $_[0]->prepare("SELECT id FROM host, `ns_host_relation`, nagios_server WHERE host.host_id = ns_host_relation.host_host_id AND ns_host_relation.nagios_server_id = nagios_server.id AND (host.host_name = '".$_[1]."' OR host.host_address = '".$_[1]."')"); + $sth->execute(); + if ($sth->rows()){ + my $temp = $sth->fetchrow_array(); + $sth->finish(); + return $temp; + } else { + return 0; + } +} + +##################################################################### +## GET SERVICES FOR GIVEN HOST (GETTING SERVICES TEMPLATES IN ACCOUNT) +# +sub getServicesIncludeTemplate($$$$) { + my ($dbh, $sth_st, $host_id, $trap_id) = @_; + my @service; + $sth_st->execute(); + + while (my @temp = $sth_st->fetchrow_array()) { + my $tr_query = "SELECT `traps_id` FROM `traps_service_relation` WHERE `service_id` = '".$temp[0]."' AND `traps_id` = '".$trap_id."'"; + my $sth_st3 = $dbh->prepare($tr_query); + $sth_st3->execute(); + my @trap = $sth_st3->fetchrow_array(); + if (defined($trap[0])) { + $service[scalar(@service)] = $temp[1]; + } else { + if (defined($temp[2])) { + my $found = 0; + my $service_template = $temp[2]; + while (!$found) { + my $st1_query = "SELECT `service_id`, `service_template_model_stm_id`, `service_description` FROM service s WHERE `service_id` = '".$service_template."'"; + my $sth_st1 = $dbh->prepare($st1_query); + $sth_st1 -> execute(); + my @st1_result = $sth_st1->fetchrow_array(); + if (defined($st1_result[0])) { + my $sth_st2 = $dbh->prepare("SELECT `traps_id` FROM `traps_service_relation` WHERE `service_id` = '".$service_template."' AND `traps_id` = '".$trap_id."'"); + $sth_st2->execute(); + my @st2_result = $sth_st2->fetchrow_array(); + if (defined($st2_result[0])) { + $found = 1; + $service[scalar(@service)] = $temp[1]; + } else { + $found = 1; + if (defined($st1_result[1]) && $st1_result[1]) { + $service_template = $st1_result[1]; + $found = 0; + } + } + $sth_st2->finish; + } + $sth_st1->finish; + } + } + } + $sth_st3->finish; + } + return (@service); +} + + + +########################## +# GET SERVICE DESCRIPTION +# +sub getServiceInformations($$$) { + + my $sth = $_[0]->prepare("SELECT `traps_id`, `traps_status`, `traps_submit_result_enable`, `traps_execution_command`, `traps_reschedule_svc_enable`, `traps_execution_command_enable`, `traps_advanced_treatment`, `traps_args` FROM `traps` WHERE `traps_oid` = '$_[1]'"); + $sth->execute(); + my ($trap_id, $trap_status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output) = $sth->fetchrow_array(); + return(undef) if (!defined $trap_id); + $sth->finish(); + + ###################################################### + # getting all "services by host" for given host + my $st_query = "SELECT s.service_id, service_description, service_template_model_stm_id FROM service s, host_service_relation h"; + $st_query .= " where s.service_id = h.service_service_id and h.host_host_id='$_[2]'"; + my $sth_st = $_[0]->prepare($st_query); + my @service = getServicesIncludeTemplate($_[0], $sth_st, $_[2], $trap_id); + $sth_st->finish; + + ###################################################### + # getting all "services by hostgroup" for given host + my $query_hostgroup_services = "SELECT s.service_id, service_description, service_template_model_stm_id FROM hostgroup_relation hgr, service s, host_service_relation hsr"; + $query_hostgroup_services .= " WHERE hgr.host_host_id = '".$_[2]."' AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id"; + $query_hostgroup_services .= " AND s.service_id = hsr.service_service_id"; + $sth_st = $_[0]->prepare($query_hostgroup_services); + $sth_st->execute(); + @service = (@service, getServicesIncludeTemplate($_[0], $sth_st, $_[2], $trap_id)); + $sth_st->finish; + + return $trap_id, $trap_status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, \@service; +} + +###################################### +## Force a new check for selected services +# +sub forceCheck($$$$) { + my ($dbh, $this_host, $this_service, $datetime) = @_; + my $result; + + my $id = get_hostNagiosServerID($dbh, $this_host); + if (defined($id) && $id != 0) { + my $submit; + + if ($whoami eq $CENTREON_USER) { + $submit = "/bin/echo \"EXTERNALCMD:$id:[$datetime] SCHEDULE_FORCED_SVC_CHECK;$this_host;$this_service;$datetime\" >> $cmdFile"; + } else { + $submit = "su -l $CENTREON_USER -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] SCHEDULE_FORCED_SVC_CHECK;$this_host;$this_service;$datetime\" >> $cmdFile'"; + } + $result = send_command($submit); + + logit("FORCE: Reschedule linked service", "II"); + logit("FORCE: Launched command: $submit", "II"); + + } + return $result; +} + +####################################### +## Submit result via external command +# +sub submitResult($$$$$$) { + my ($dbh, $this_host, $this_service, $datetime, $status, $traps_output) = @_; + my $result; + + # No matching rules + my $id = get_hostNagiosServerID($dbh, $this_host); + if (defined($id) && $id != 0) { + my $str = "PROCESS_SERVICE_CHECK_RESULT;$this_host;$this_service;$status;$traps_output"; + + my $submit; + if ($whoami eq $CENTREON_USER) { + $str =~ s/"/\\"/g; + $submit = "/bin/echo \"EXTERNALCMD:$id:[$datetime] $str\" >> $cmdFile"; + } else { + $str =~ s/'/'\\''/g; + $str =~ s/"/\\"/g; + $submit = "su -l $CENTREON_USER -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] $str\" >> $cmdFile'"; + } + $result = send_command($submit); + + logit("SUBMIT: Force service status via passive check update", "II"); + logit("SUBMIT: Launched command: $submit", "II"); + } + return $result; +} + +########################## +## REPLACE +# +sub substitute_string { + my $str = $_[0]; + + # Substitute @{oid_value} and $1, $2,... + for (my $i=0; $i <= $#entvar; $i++) { + my $x = $i + 1; + $str =~ s/\@\{$entvarname[$i]\}/$entvar[$i]/g; + $str =~ s/\$$x(\s|$)/$entvar[$i]/g; + } + + # Substitute $* + my $sub_str = join($centrapmanager_seperator, @entvar); + $str =~ s/\$\*/$sub_str/g; + + # Clean OID + $str =~ s/\@\{[\.0-9]*\}//g; + return $str; +} + +####################################### +## Check Advanced Matching Rules +# +sub checkMatchingRules($$$$$$$$$) { + my ($dbh, $trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status) = @_; + + # Check matching options + my $sth = $dbh->prepare("SELECT tmo_regexp, tmo_status, tmo_string FROM traps_matching_properties WHERE trap_id = '".$trap_id."' ORDER BY tmo_order"); + $sth->execute(); + while (my ($regexp, $tmoStatus, $tmoString) = $sth->fetchrow_array()) { + logit("[$tmoString][$regexp] => $tmoStatus", "DD") if ($centrapmanager_log_debug >= 2); + + my @temp = split(//, $regexp); + my $i = 0; + my $len = length($regexp); + $regexp = ""; + foreach (@temp) { + if ($i eq 0 && $_ =~ "/") { + $regexp = $regexp . ""; + } elsif ($i eq ($len - 1) && $_ =~ "/") { + $regexp = $regexp . ""; + } else { + $regexp = $regexp . $_; + } + $i++; + } + + $tmoString = substitute_string($tmoString); + + ########################## + # REPLACE special Chars + if ($htmlentities == 1) { + $tmoString = decode_entities($tmoString); + } else { + $tmoString =~ s/\"\;/\"/g; + $tmoString =~ s/\'\;\'\;/"/g; + } + $tmoString =~ s/\@HOSTNAME\@/$this_host/g; + $tmoString =~ s/\@HOSTADDRESS\@/$ip/g; + $tmoString =~ s/\@HOSTADDRESS2\@/$hostname/g; + $tmoString =~ s/\@SERVICEDESC\@/$this_service/g; + $tmoString =~ s/\@TRAPOUTPUT\@/$traps_output/g; + $tmoString =~ s/\@OUTPUT\@/$traps_output/g; + $tmoString =~ s/\@TIME\@/$datetime/g; + + # Integrate OID Matching + if (defined($tmoString) && $tmoString =~ m/$regexp/g) { + $status = $tmoStatus; + logit("Regexp: String:$tmoString => REGEXP:$regexp", "II"); + logit("Status: $status ($tmoStatus)", "II"); + last; + } + } + $sth->finish(); + return $status; +} + +################################ +## Execute a specific command +# +sub executeCommand($$$$$$$$) { + my ($traps_execution_command, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status) = @_; + + $traps_execution_command = substitute_string($traps_execution_command); + + ########################## + # REPLACE MACROS + if ($htmlentities == 1) { + $traps_execution_command = decode_entities($traps_execution_command); + } else { + $traps_execution_command =~ s/\"\;/\"/g; + $traps_execution_command =~ s/\'\;\'\;/"/g; + $traps_execution_command =~ s/\'\;/'/g; + } + $traps_execution_command =~ s/\@HOSTNAME\@/$this_host/g; + $traps_execution_command =~ s/\@HOSTADDRESS\@/$_[1]/g; + $traps_execution_command =~ s/\@HOSTADDRESS2\@/$_[2]/g; + $traps_execution_command =~ s/\@SERVICEDESC\@/$this_service/g; + $traps_execution_command =~ s/\@TRAPOUTPUT\@/$traps_output/g; + $traps_execution_command =~ s/\@OUTPUT\@/$traps_output/g; + $traps_execution_command =~ s/\@STATUS\@/$status/g; + $traps_execution_command =~ s/\@TIME\@/$datetime/g; + + ########################## + # SEND COMMAND + if ($traps_execution_command) { + logit("EXEC: Launch specific command", "II"); + logit("EXEC: Launched command: $traps_execution_command", "II"); + + my $output = `$traps_execution_command`; + if ($?) { + logit("EXEC: Execution error: $!", "EE"); + } + if ($output) { + logit("EXEC: Output : $output", "II"); + } + } +} + + +####################################### +## GET HOSTNAME AND SERVICE DESCRIPTION +# +sub getTrapsInfos($$$) { + my $ip = shift; + my $hostname = shift; + my $oid = shift; + + my $status; + + my %host = get_hostinfos($dbh, $ip, $hostname); + foreach my $host_id (keys %host) { + my $this_host = $host{$host_id}; + my ($trap_id, $status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, $ref_servicename) = getServiceInformations($dbh, $oid, $host_id); + if (!defined($trap_id)) { + return ; + } + my @servicename = @{$ref_servicename}; + + foreach (@servicename) { + my $this_service = $_; + + if ($centrapmanager_log_debug >= 2) { + logit("Trap found on service \'$this_service\' for host \'$this_host\'.", "DD"); + } + + my $datetime = `date +%s`; + chomp($datetime); + + $traps_output = substitute_string($traps_output); + + ###################################################################### + # Advanced matching rules + if (defined($traps_advanced_treatment) && $traps_advanced_treatment eq 1) { + $status = checkMatchingRules($dbh, $trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status); + } + + ##################################################################### + # Submit value to passive service + if (defined($traps_submit_result_enable) && $traps_submit_result_enable eq 1) { + submitResult($dbh, $this_host, $this_service, $datetime, $status, $traps_output); + } + + ###################################################################### + # Force service execution with external command + if (defined($traps_reschedule_svc_enable) && $traps_reschedule_svc_enable eq 1) { + forceCheck($dbh, $this_host, $this_service, $datetime); + } + + ###################################################################### + # Execute special command + if (defined($traps_execution_command_enable) && $traps_execution_command_enable) { + executeCommand($traps_execution_command, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status); + } + } + } +} + +#################################### +## GenerateError +# + + + +######################################################### +# Beginning +# + +sub run { + my $self = shift; + + $self->SUPER::run(); + $self->{logger}->redirect_output(); + + ($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}) = + centreon::trapd::lib::manage_params_conf($self->{centreontrapd_config}->{date_format}, + $self->{centreontrapd_config}->{time_format}); + centreon::trapd::lib::init_modules(logger => $self->{logger}, config => $self->{centreontrapd_config}, htmlentities => \$self->{htmlentities}); + + $self->{logger}->writeLogDebug("centrapmaanger launched...."); + $self->{logger}->writeLogDebug("PID: $$"); + + $self->{cdb} = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 0, + logger => $self->{logger}); + if ($self->{centreon_config}->{mode} == 0) { + $self->{cmdFile} = $self->{centreon_config}->{cmdFile}; + } else { + # Dirty!!! Need to know the poller + my ($status, $sth) = $self->{cdb}->query("SELECT `command_file` FROM `cfg_nagios` WHERE `nagios_activate` = '1' LIMIT 1"); + my @conf = $sth->fetchrow_array(); + $self->{cmdFile} = $conf[0]; + } + $self->{whoami} = getpwuid($<); + + if ($self->{centreontrapd_config}->{daemon} == 1) { + while (!$self->{timetodie}) { + centreon::trapd::lib::purge_duplicate_trap(); + while ((my $file = centreon::trapd::lib::get_trap())) { + $self->{logger}->writeLogDebug("Processing file: $file"); + + if (open FILE, $self->{spool_directory} . $file) { + my $trap_is_a_duplicate = 0; + my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, + handle => 'FILE'); + + if ($readtrap_result == 1) { + if (centreon::trapd::lib::check_known_trap($var[3]) == 1) { + getTrapsInfos($var[1], $var[2], $var[3]); + } + } elsif ($readtrap_result == 0) { + $self->{logger}->writeLogDebug("Error processing trap file $file. Skipping..."); + } elsif ($readtrap_result == -1) { + $trap_is_a_duplicate = 1; + $self->{logger}->writeLogInfo("Duplicate trap detected in trap file $file. Skipping..."); + } + + close FILE; + unless (unlink($file)) { + $self->{logger}->writeLogError("Unable to delete trap file $file from spool dir:$!"); + } + } else { + $self->{logger}->writeLogError("Could not open trap file $spool_directory$file: ($!)"); + } + } + + $self->{logger}->writeLogDebug("Sleeping for $centrapmanager_sleep seconds"); + sleep $self->{centreontrapd_config}->{sleep}; + + if ($self->{timetoreload} == 1) { + $self->{logger}->writeLogDebug("Reloading configuration file"); + $self->reload_config($self->{opt_extra}); + ($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}) = + centreon::trapd::lib::manage_params_conf($self->{centreontrapd_config}->{date_format}, + $self->{centreontrapd_config}->{time_format}); + centreon::trapd::lib::init_modules(); + centreon::trapd::lib::get_cache_oids(); + $self->{timetoreload} = 0; + } + } + } else { + my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, + handle => 'STDIN'); + if ($readtrap_result == 1) { + if (centreon::trapd::lib::check_known_trap($var[3]) == 1) { + getTrapsInfos($var[1], $var[2], $var[3]); + } + } elsif ($readtrap_result == 0) { + $self->{logger}->writeLogDebug("Error processing trap file. Skipping..."); + } + } +} + +1; + +__END__ diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm new file mode 100644 index 00000000000..7de9df2fe69 --- /dev/null +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -0,0 +1,685 @@ + +package centreon::trapd::lib; + +use warnings; +use strict; +use POSIX qw(strftime); +use File::stat; + +sub init_modules { + # logger => obj + # htmlentities => (ref) + # config => hash + my %args = @_; + + #### + # SNMP Module + #### + if ($args{config}->{net_snmp_perl_enable} == 1) { + eval 'require SNMP;'; + if ($@) { + $args{logger}->writeLogError($@); + $args{logger}->writeLogError("Could not load the Perl module SNMP! If net_snmp_perl_enable is"); + $args{logger}->writeLogError("enabled then the SNMP module is required"); + $args{logger}->writeLogError("for system requirements. Note: uses the Net-SNMP package's"); + $args{logger}->writeLogError("SNMP module, NOT the CPAN Net::SNMP module!"); + die("Quit"); + } + require SNMP; + if (defined ($args{config}->{mibs_environment}) && $args{config}->{mibs_environment} ne '') { + $ENV{'MIBS'} = $args{config}->{mibs_environment}; + } + &SNMP::initMib(); + + $args{logger}->writeLogInfo("********** Net-SNMP version $SNMP::VERSION Perl module enabled **********"); + if (defined ($args{config}->{mibs_environment})) { + $args{logger}->writeLogDebug("********** MIBS: " . $args{config}->{mibs_environment} . " **********"); + } + } + + #### + # Socket Module + #### + if ($args{config}->{dns_enable} == 1) { + eval 'require Socket;'; + if ($@) { + $args{logger}->writeLogError($@); + $args{logger}->writeLogError("Could not load the Perl module Socket! If dns_enable"); + $args{logger}->writeLogError("is enabled then the Socket module is required"); + $args{logger}->writeLogError("for system requirements"); + die("Quit"); + } + require Socket; + $args{logger}->writeLogInfo("********** DNS enabled **********"); + } + + if ($args{config}->{duplicate_trap_window} > 0) { + eval 'require Digest::MD5;'; + if ($@) { + $args{logger}->writeLogError($@, "EE"); + $args{logger}->writeLogError("Could not load the Perl module Digest::MD5! If centrapmanager_duplicate_trap_window"); + $args{logger}->writeLogError("is set then the Digest::MD5 module is required"); + $args{logger}->writeLogError("for system requirements."); + die("Quit"); + } + require Digest::MD5; + } + + eval "use HTML::Entities"; + if ($@) { + ${$args{htmlentities}} = 0; + } else { + ${$args{htmlentities}} = 1; + } +} + +sub manage_params_conf { + my ($date_format, $time_format) = @_; + + if (!defined($date_format) || $date_format eq "") { + $date_format = "%a %b %e %Y"; + } + if (!defined($time_format) || $time_format eq "") { + $time_format = "%H:%M:%S"; + } + + return ($date_format, $time_format); +} + +############## +# CACHE MANAGEMENT +############## + +sub get_cache_oids { + my $sth = $dbh->prepare("SELECT traps_oid FROM traps"); + if (!$sth->execute()) { + logit("SELECT traps_oid from traps error: " . $sth->errstr, "EE"); + return 1; + } + $oids_cache = $sth->fetchall_hashref("traps_oid"); + $last_cache_time = time(); + return 0; +} + +sub write_cache_file { + if (!open(FILECACHE, ">", $centrapmanager_cache_unknown_traps_file)) { + logit("Can't write $centrapmanager_cache_unknown_traps_file; $!", "EE"); + logit("Go to DB to get info", "EE"); + return 1; + } + my $oids_value = join("\n", keys %$oids_cache); + print FILECACHE $oids_value; + close FILECACHE; + logit("Cache file refreshed", "II") if ($centrapmanager_log_debug >= 1); + return 0; +} + +sub check_known_trap { + # logger => obj + # config => hash + # oid2verif => val + my %args = @_; + my $oid2verif = $args{oid2verif}; + my $db_mode = 1; + + if ($centrapmanager_cache_unknown_traps_enable == 1) { + if ($centrapmanager_daemon != 1) { + $db_mode = 0; + if (-e $centrapmanager_cache_unknown_traps_file) { + if ((my $result = stat($centrapmanager_cache_unknown_traps_file))) { + if ((time() - $result->mtime) > $centrapmanager_cache_unknown_traps_retention) { + $args{logger}->writeLogInfo("Try to rewrite cache"); + !($db_mode = get_cache_oids()) && ($db_mode = write_cache_file()); + } + } else { + $args{logger}->writeLogError("Can't stat file $centrapmanager_cache_unknown_traps_file: $!"); + $args{logger}->writeLogError("Go to DB to get info"); + $db_mode = 1; + } + } else { + !($db_mode = get_cache_oids()) && ($db_mode = write_cache_file()); + } + } else { + if (!defined($last_cache_time) || ((time() - $last_cache_time) > $centrapmanager_cache_unknown_traps_retention)) { + $db_mode = get_cache_oids(); + } + } + } + + if ($db_mode == 0) { + if (defined($oids_cache)) { + if (defined($oids_cache->{$oid2verif})) { + return 1; + } else { + $args{logger}->writeLogInfo("Unknown trap"); + return 0; + } + } else { + if (!open FILECACHE, $centrapmanager_cache_unknown_traps_file) { + $args{logger}->writeLogError("Can't read file $centrapmanager_cache_unknown_traps_file: $!"); + $db_mode = 1; + } else { + while () { + if (/^$oid2verif$/m) { + return 1; + } + } + close FILECACHE; + $args{logger}->writeLogInfo("Unknown trap"); + return 0; + } + } + } + + if ($db_mode == 1) { + # Read db + my $sth = $dbh->prepare("SELECT traps_oid FROM traps WHERE traps_oid = " . $dbh->quote($oid2verif)); + if (!$sth->execute()) { + #$args{logger}->writeLogError("SELECT traps_oid from traps error: " . $sth->errstr); + return 0; + } + if ($sth->rows == 0) { + $args{logger}->writeLogInfo("Unknown trap"); + return 0; + } + } + + return 1; +} + + + +### +# Code from SNMPTT Modified +# Copyright 2002-2009 Alex Burger +# alex_b@users.sourceforge.net +### + +sub get_trap { + if (!@filenames) { + if (!(chdir($spool_directory))) { + logit("Unable to enter spool dir $spool_directory:$!", "EE"); + return undef; + } + if (!(opendir(DIR, "."))) { + logit("Unable to open spool dir $spool_directory:$!", "EE"); + return undef; + } + if (!(@filenames = readdir(DIR))) { + logit("Unable to read spool dir $spool_directory:$!", "EE"); + return undef; + } + closedir(DIR); + @filenames = sort (@filenames); + } + + while (($file = shift @filenames)) { + next if ($file eq "."); + next if ($file eq ".."); + return $file; + } + return undef; +} + +sub purge_duplicate_trap { + if ($centrapmanager_duplicate_trap_window) { + # Purge traps older than duplicate_trap_window in %duplicate_traps + my $duplicate_traps_current_time = time(); + foreach my $key (sort keys %duplicate_traps) { + if ($duplicate_traps{$key} < $duplicate_traps_current_time - $centrapmanager_duplicate_trap_window) { + # Purge the record + delete $duplicate_traps{$key}; + } + } + } +} + +sub readtrap { + # logger => obj + # config => hash + # handle => str + my %args = @_; + my $input = $args{handle}; + + # Flush out @tempvar, @var and @entvar + my @tempvar = (); + @var = (); + @entvar = (); + @entvarname = (); + my @rawtrap = (); + + $self->{logger}->writeLogDebug("Reading trap. Current time: " . scalar(localtime())); + + if ($centrapmanager_daemon == 1) { + chomp($trap_date_time_epoch = (<$input>)); # Pull time trap was spooled + push(@rawtrap, $trap_date_time_epoch); + if ($trap_date_time_epoch eq "") { + if ($self->{logger}->isDebug()) { + $self->{logger}->writeLogDebug(" Invalid trap file. Expected a serial time on the first line but got nothing"); + return 0; + } + } + $trap_date_time_epoch =~ s(`)(')g; #` Replace any back ticks with regular single quote + } else { + $trap_date_time_epoch = time(); # Use current time as time trap was received + } + + my @localtime_array; + if ($centrapmanager_daemon == 1 && $centrapmanager_use_trap_time == 1) { + @localtime_array = localtime($trap_date_time_epoch); + + if ($centrapmanager_date_time_format eq "") { + $trap_date_time = localtime($trap_date_time_epoch); + } else { + $trap_date_time = strftime($centrapmanager_date_time_format, @localtime_array); + } + } else { + @localtime_array = localtime(); + + if ($centrapmanager_date_time_format eq "") { + $trap_date_time = localtime(); + } else { + $trap_date_time = strftime($centrapmanager_date_time_format, @localtime_array); + } + } + + $trap_date = strftime($centrapmanager_date_format, @localtime_array); + $trap_time = strftime($centrapmanager_time_format, @localtime_array); + + # Pull in passed SNMP info from snmptrapd via STDIN and place in the array @tempvar + chomp($tempvar[0]=<$input>); # hostname + push(@rawtrap, $tempvar[0]); + $tempvar[0] =~ s(`)(')g; #` Replace any back ticks with regular single quote + if ($tempvar[0] eq "") { + if ($self->{logger}->isDebug()) { + $self->{logger}->writeLogDebug(" Invalid trap file. Expected a hostname on line 2 but got nothing"); + return 0; + } + } + + chomp($tempvar[1]=<$input>); # ip address + push(@rawtrap, $tempvar[1]); + $tempvar[1] =~ s(`)(')g; #` Replace any back ticks with regular single quote + if ($tempvar[1] eq "") { + if ($self->{logger}->isDebug()) { + $self->{logger}->writeLogDebug(" Invalid trap file. Expected an IP address on line 3 but got nothing"); + return 0; + } + } + + # Some systems pass the IP address as udp:ipaddress:portnumber. This will pull + # out just the IP address + $tempvar[1] =~ /(\d+\.\d+\.\d+\.\d+)/; + $tempvar[1] = $1; + + # Net-SNMP 5.4 has a bug which gives for the hostname + if ($tempvar[0] =~ //) { + $tempvar[0] = $tempvar[1]; + } + + #Process varbinds + #Separate everything out, keeping both the variable name and the value + my $linenum = 1; + while (defined(my $line = <$input>)) { + push(@rawtrap, $line); + $line =~ s(`)(')g; #` Replace any back ticks with regular single quote + + # Remove escape from quotes if enabled + if ($centrapmanager_remove_backslash_from_quotes == 1) { + $line =~ s/\\\"/"/g; + } + + my $temp1; + my $temp2; + + ($temp1, $temp2) = split (/ /, $line, 2); + + chomp ($temp1); # Variable NAME + chomp ($temp2); # Variable VALUE + chomp ($line); + + my $variable_fix; + #if ($linenum == 1) { + # Check if line 1 contains 'variable value' or just 'value' + if (defined($temp2)) { + $variable_fix = 0; + } else { + $variable_fix = 1; + } + #} + + if ($variable_fix == 0 ) { + # Make sure variable names are numerical + $temp1 = translate_symbolic_to_oid($temp1); + + # If line begins with a double quote (") but does not END in a double quote then we need to merge + # the following lines together into one until we find the closing double quote. Allow for escaped quotes. + # Net-SNMP sometimes divides long lines into multiple lines.. + if ( ($temp2 =~ /^\"/) && ( ! ($temp2 =~ /[^\\]\"$/)) ) { + $self->{logger}->writeLogDebug(" Multi-line value detected - merging onto one line..."); + chomp $temp2; # Remove the newline character + while (defined(my $line2 = <$input>)) { + chomp $line2; + push(@rawtrap, $line2); + $temp2.=" ".$line2; + # Ends in a non-escaped quote + if ($line2 =~ /[^\\]\"$/) { + last; + } + } + } + + # If the value is blank, set it to (null) + if ($temp2 eq "") { + $temp2 = "(null)"; + } + + # Have quotes around it? + if ($temp2 =~ /^\"/ && $temp2 =~ /\"$/) { + $temp2 = substr($temp2,1,(length($temp2)-2)); # Remove quotes + push(@tempvar, $temp1); + push(@tempvar, $temp2); + } else { + push(@tempvar, $temp1); + push(@tempvar, $temp2); + } + } else { + # Should have been variable value, but only value found. Workaround + # + # Normally it is expected that a line contains a variable name + # followed by a space followed by the value (except for the + # first line which is the hostname and the second which is the + # IP address). If there is no variable name on the line (only + # one string), then add a variable string called 'variable' so + # it is handled correctly in the next section. + # This happens with ucd-snmp v4.2.3 but not v4.2.1 or v4.2.5. + # This appears to be a bug in ucd-snmp v4.2.3. This works around + # the problem by using 'variable' for the variable name, although + # v4.2.3 should NOT be used with SNMPTT as it prevents SNMP V2 traps + # from being handled correctly. + + $self->{logger}->writeLogDebug("Data passed from snmptrapd is incorrect. UCD-SNMP v4.2.3 is known to cause this"); + + # If line begins with a double quote (") but does not END in a double quote then we need to merge + # the following lines together into one until we find the closing double quote. Allow for escaped quotes. + # Net-SNMP sometimes divides long lines into multiple lines.. + if ( ($line =~ /^\"/) && ( ! ($line =~ /[^\\]\"$/)) ) { + $self->{logger}->writeLogDebug(" Multi-line value detected - merging onto one line..."); + chomp $line; # Remove the newline character + while (defined(my $line2 = <$input>)) { + chomp $line2; + push(@rawtrap, $line2); + $line.=" ".$line2; + # Ends in a non-escaped quote + if ($line2 =~ /[^\\]\"$/) { + last; + } + } + } + + # If the value is blank, set it to (null) + if ($line eq "") { + $line = "(null)"; + } + + # Have quotes around it? + if ($line =~ /^\"/ && $line =~ /$\"/) { + $line = substr($line,1,(length($line)-2)); # Remove quotes + push(@tempvar, "variable"); + push(@tempvar, $line); + } else { + push(@tempvar, "variable"); + push(@tempvar, $line); + } + } + + $linenum++; + } + + if ($self->{logger}->isDebug()) { + # Print out raw trap passed from snmptrapd + $self->{logger}->writeLogDebug("Raw trap passed from snmptrapd:"); + for (my $i=0;$i <= $#rawtrap;$i++) { + chomp($rawtrap[$i]); + $self->{logger}->writeLogDebug("$rawtrap[$i]"); + } + + # Print out all items passed from snmptrapd + $self->{logger}->writeLogDebug("Items passed from snmptrapd:"); + for (my $i=0;$i <= $#tempvar;$i++) { + $self->{logger}->writeLogDebug("value $i: $tempvar[$i]"); + } + } + + # Copy what I need to new variables to make it easier to manipulate later + + # Standard variables + $var[0] = $tempvar[0]; # hostname + $var[1] = $tempvar[1]; # ip address + $var[2] = $tempvar[3]; # uptime + $var[3] = $tempvar[5]; # trapname / OID - assume first value after uptime is + # the trap OID (value for .1.3.6.1.6.3.1.1.4.1.0) + + $var[4] = ""; # Clear ip address from trap agent + $var[5] = ""; # Clear trap community string + $var[6] = ""; # Clear enterprise + $var[7] = ""; # Clear securityEngineID + $var[8] = ""; # Clear securityName + $var[9] = ""; # Clear contextEngineID + $var[10] = ""; # Clear contextName + + # Make sure trap OID is numerical as event lookups are done using numerical OIDs only + $var[3] = translate_symbolic_to_oid($var[3]); + + # Cycle through remaining variables searching for for agent IP (.1.3.6.1.6.3.18.1.3.0), + # community name (.1.3.6.1.6.3.18.1.4.0) and enterpise (.1.3.6.1.6.3.1.1.4.3.0) + # All others found are regular passed variables + my $j=0; + for (my $i=6;$i <= $#tempvar; $i+=2) { + + if ($tempvar[$i] =~ /^.1.3.6.1.6.3.18.1.3.0$/) { # ip address from trap agent + $var[4] = $tempvar[$i+1]; + } elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.18.1.4.0$/) { # trap community string + $var[5] = $tempvar[$i+1]; + } elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.1.1.4.3.0$/) { # enterprise + # $var[6] = $tempvar[$i+1]; + # Make sure enterprise value is numerical + $var[6] = translate_symbolic_to_oid($tempvar[$i+1]); + } elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.10.2.1.1.0$/) { # securityEngineID + $var[7] = $tempvar[$i+1]; + } elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.18.1.1.1.3$/) { # securityName + $var[8] = $tempvar[$i+1]; + } elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.18.1.1.1.4$/) { # contextEngineID + $var[9] = $tempvar[$i+1]; + } + elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.18.1.1.1.5$/) { # contextName + $var[10] = $tempvar[$i+1]; + } else { # application specific variables + $entvarname[$j] = $tempvar[$i]; + $entvar[$j] = $tempvar[$i+1]; + $j++; + } + } + + # Only if it's not already resolved + if ($centrapmanager_dns_enable == 1 && $var[0] =~ /^\d+\.\d+\.\d+\.\d+$/) { + my $temp = gethostbyaddr(Socket::inet_aton($var[0]),Socket::AF_INET()); + if (defined ($temp)) { + $self->{logger}->writeLogDebug("Host IP address ($var[0]) resolved to: $temp"); + $var[0] = $temp; + } else { + $self->{logger}->writeLogDebug("Host IP address ($var[0]) could not be resolved by DNS. Variable \$r / \$R etc will use the IP address"); + } + } + + # If the agent IP is blank, copy the IP from the host IP. + # var[4] would only be blank if it wasn't passed from snmptrapd, which + # should only happen with ucd-snmp 4.2.3, which you should be using anyway! + if ($var[4] eq '') { + $var[4] = $var[1]; + $self->{logger}->writeLogDebug("Agent IP address was blank, so setting to the same as the host IP address of $var[1]"); + } + + # If the agent IP is the same as the host IP, then just use the host DNS name, no need + # to look up, as it's obviously the same.. + if ($var[4] eq $var[1]) { + $self->{logger}->writeLogDebug("Agent IP address ($var[4]) is the same as the host IP, so copying the host name: $var[0]"); + $agent_dns_name = $var[0]; + } else { + $agent_dns_name = $var[4]; # Default to IP address + if ($centrapmanager_dns_enable == 1 && $var[4] ne '') { + my $temp = gethostbyaddr(Socket::inet_aton($var[4]),Socket::AF_INET()); + if (defined ($temp)) { + $self->{logger}->writeLogDebug("Agent IP address ($var[4]) resolved to: $temp"); + $agent_dns_name = $temp; + } else { + $self->{logger}->writeLogDebug("Agent IP address ($var[4]) could not be resolved by DNS. Variable \$A etc will use the IP address"); + } + } + } + + if ($centrapmanager_strip_domain) { + $var[0] = strip_domain_name($var[0], $centrapmanager_strip_domain); + $agent_dns_name = strip_domain_name($agent_dns_name, $centrapmanager_strip_domain); + } + + $self->{logger}->writeLogDebug("Trap received from $tempvar[0]: $tempvar[5]"); + + if ($self->{logger}->isDebug()) { + $self->{logger}->writeLogDebug("0: hostname"); + $self->{logger}->writeLogDebug("1: ip address"); + $self->{logger}->writeLogDebug("2: uptime"); + $self->{logger}->writeLogDebug("3: trapname / OID"); + $self->{logger}->writeLogDebug("4: ip address from trap agent"); + $self->{logger}->writeLogDebug("5: trap community string"); + $self->{logger}->writeLogDebug("6: enterprise"); + $self->{logger}->writeLogDebug("7: securityEngineID (not use)"); + $self->{logger}->writeLogDebug("8: securityName (not use)"); + $self->{logger}->writeLogDebug("9: contextEngineID (not use)"); + $self->{logger}->writeLogDebug("10: contextName (not)"); + $self->{logger}->writeLogDebug("0+: passed variables"); + + #print out all standard variables + for (my $i=0;$i <= $#var;$i++) { + $self->{logger}->writeLogDebug("Value $i: $var[$i]"); + } + + $self->{logger}->writeLogDebug("Agent dns name: $agent_dns_name"); + + #print out all enterprise specific variables + for (my $i=0;$i <= $#entvar;$i++) { + $self->{logger}->writeLogDebug("Ent Value $i (\$" . ($i+1) . "): $entvarname[$i]=$entvar[$i]"); + } + } + + # Generate hash of trap and detect duplicates + if ($centrapmanager_duplicate_trap_window) { + my $md5 = Digest::MD5->new; + # All variables except for uptime. + $md5->add($var[0],$var[1].$var[3].$var[4].$var[5].$var[6].$var[7].$var[8].$var[9].$var[10]."@entvar"); + + my $trap_digest = $md5->hexdigest; + + $self->{logger}->writeLogDebug("Trap digest: $trap_digest"); + + if ($duplicate_traps{$trap_digest}) { + # Duplicate trap detected. Skipping trap... + return -1; + } + + $duplicate_traps{$trap_digest} = time(); + } + + return 1; + + # Variables of trap received by SNMPTRAPD: + # + # $var[0] hostname + # $var[1] ip address + # $var[2] uptime + # $var[3] trapname / OID + # $var[4] ip address from trap agent + # $var[5] trap community string + # $var[6] enterprise + # $var[7] securityEngineID (snmptthandler-embedded required) + # $var[8] securityName (snmptthandler-embedded required) + # $var[9] contextEngineID (snmptthandler-embedded required) + # $var[10] contextName (snmptthandler-embedded required) + # + # $entvarname[0] passed variable name 1 + # $entvarname[1] passed variable name 2 + # + # $entvar[0] passed variable 1 + # $entvar[1] passed variable 2 + # . + # . + # etc.. + # + ############################################################################## +} + +# Used when reading received traps to symbolic names in variable names and +# values to numerical +sub translate_symbolic_to_oid +{ + my $temp = shift; + + # Check to see if OID passed from snmptrapd is fully numeric. If not, try to translate + if (! ($temp =~ /^(\.\d+)+$/)) { + # Not numeric + # Try to convert to numerical + if ($centrapmanager_log_debug >= 2) { + logit("Symbolic trap variable name detected ($temp). Will attempt to translate to a numerical OID", "DD"); + } + if ($centrapmanager_net_snmp_perl_enable == 1) { + my $temp3 = SNMP::translateObj("$temp",0); + if (defined ($temp3) ) { + if ($centrapmanager_log_debug >= 2) { + logit(" Translated to $temp3\n", "DD"); + } + $temp = $temp3; + } else { + # Could not translate default to numeric + if ($centrapmanager_log_debug >= 2) { + logit(" Could not translate - will leave as-is", "DD"); + } + } + } else { + if ($centrapmanager_log_debug >= 2) { + logit(" Could not translate - Net-SNMP Perl module not enabled - will leave as-is", "DD"); + } + } + } + return $temp; +} + +# Strip domain name from hostname +sub strip_domain_name { + my $name = shift; + my $mode = shift; + + # If mode = 1, strip off all domain names leaving only the host + if ($mode == 1 && !($name =~ /^\d+\.\d+\.\d+\.\d+$/)) { + if ($name =~ /\./) { # Contain a . ? + $name =~ /^([^\.]+?)\./; + $name = $1; + } + } elsif ($mode == 2 && !($name =~ /^\d+\.\d+\.\d+\.\d+$/)) { # If mode = 2, strip off the domains as listed in strip_domain_list in .ini file + if (@centrapmanager_strip_domain_list) { + foreach my $strip_domain_list_temp (@centrapmanager_strip_domain_list) { + if ($strip_domain_list_temp =~ /^\..*/) { # If domain from list starts with a '.' then remove it first + ($strip_domain_list_temp) = $strip_domain_list_temp =~ /^\.(.*)/; + } + + if ($name =~ /^.+\.$strip_domain_list_temp/) { # host is something . domain name? + $name =~ /(.*)\.$strip_domain_list_temp/; # strip the domain name + $name = $1; + last; # Only process once + } + } + } + } + return $name; +} + +1; \ No newline at end of file From 3304542d3cffe21fe5a50dfbc6095c7a7e2bcfdd Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 22 Mar 2013 14:11:11 +0100 Subject: [PATCH 019/458] Continue trapd works --- .../lib/perl/centreon/script/centreontrapd.pm | 148 ++++---- centreon/lib/perl/centreon/trapd/lib.pm | 339 ++++++++++-------- 2 files changed, 266 insertions(+), 221 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 834832634a8..843ea860568 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -74,7 +74,6 @@ sub new { $self->{timetoreload} = 0; $self->{timetodie} = 0; @{self->{filenames}} = undef; - $self->{input} = undef; $self->{oids_cache} = undef; $self->{last_cache_time} = undef; $self->{whoami} = undef; @@ -134,6 +133,8 @@ sub reload_config { ## Execute a command Nagios or Centcore # sub send_command { + my $self = shift; + eval { local $SIG{ALRM} = sub { die "TIMEOUT"; }; alarm($centrapmanager_cmd_timeout); @@ -142,7 +143,7 @@ sub send_command { }; if ($@) { if ($@ =~ "TIMEOUT") { - logit("ERROR: Send command timeout", "EE"); + $self->{logger}->writeLogError("ERROR: Send command timeout"); return 0; } } @@ -153,6 +154,7 @@ sub send_command { ## GET HOSTNAME FROM IP ADDRESS # sub get_hostinfos($$$) { + my $self = shift; my %host = (); my $sth = $_[0]->prepare("SELECT host_id, host_name FROM host WHERE host_address='$_[1]' OR host_address='$_[2]'"); @@ -168,6 +170,8 @@ sub get_hostinfos($$$) { ## GET host location # sub get_hostlocation($$) { + my $self = shift; + my $sth = $_[0]->prepare("SELECT localhost FROM host, `ns_host_relation`, nagios_server WHERE host.host_id = ns_host_relation.host_host_id AND ns_host_relation.nagios_server_id = nagios_server.id AND host.host_name = '".$_[1]."'"); $sth->execute(); if ($sth->rows()){ @@ -179,18 +183,12 @@ sub get_hostlocation($$) { } } -############################## -## Connect to MySQL -# -sub connectDB() { - my $dbh = DBI->connect("dbi:mysql:".$mysql_database_oreon.";host=".$mysql_host, $mysql_user, $mysql_passwd) or myDie("Echec de la connexion"); - return $dbh; -} - ################################## ## GET nagios server id for a host # sub get_hostNagiosServerID($$) { + my $self = shift; + my $sth = $_[0]->prepare("SELECT id FROM host, `ns_host_relation`, nagios_server WHERE host.host_id = ns_host_relation.host_host_id AND ns_host_relation.nagios_server_id = nagios_server.id AND (host.host_name = '".$_[1]."' OR host.host_address = '".$_[1]."')"); $sth->execute(); if ($sth->rows()){ @@ -206,6 +204,7 @@ sub get_hostNagiosServerID($$) { ## GET SERVICES FOR GIVEN HOST (GETTING SERVICES TEMPLATES IN ACCOUNT) # sub getServicesIncludeTemplate($$$$) { + my $self = shift; my ($dbh, $sth_st, $host_id, $trap_id) = @_; my @service; $sth_st->execute(); @@ -257,7 +256,7 @@ sub getServicesIncludeTemplate($$$$) { # GET SERVICE DESCRIPTION # sub getServiceInformations($$$) { - + my $self = shift; my $sth = $_[0]->prepare("SELECT `traps_id`, `traps_status`, `traps_submit_result_enable`, `traps_execution_command`, `traps_reschedule_svc_enable`, `traps_execution_command_enable`, `traps_advanced_treatment`, `traps_args` FROM `traps` WHERE `traps_oid` = '$_[1]'"); $sth->execute(); my ($trap_id, $trap_status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output) = $sth->fetchrow_array(); @@ -269,7 +268,7 @@ sub getServiceInformations($$$) { my $st_query = "SELECT s.service_id, service_description, service_template_model_stm_id FROM service s, host_service_relation h"; $st_query .= " where s.service_id = h.service_service_id and h.host_host_id='$_[2]'"; my $sth_st = $_[0]->prepare($st_query); - my @service = getServicesIncludeTemplate($_[0], $sth_st, $_[2], $trap_id); + my @service = $self->getServicesIncludeTemplate($_[0], $sth_st, $_[2], $trap_id); $sth_st->finish; ###################################################### @@ -279,7 +278,7 @@ sub getServiceInformations($$$) { $query_hostgroup_services .= " AND s.service_id = hsr.service_service_id"; $sth_st = $_[0]->prepare($query_hostgroup_services); $sth_st->execute(); - @service = (@service, getServicesIncludeTemplate($_[0], $sth_st, $_[2], $trap_id)); + @service = (@service, $self->getServicesIncludeTemplate($_[0], $sth_st, $_[2], $trap_id)); $sth_st->finish; return $trap_id, $trap_status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, \@service; @@ -289,10 +288,11 @@ sub getServiceInformations($$$) { ## Force a new check for selected services # sub forceCheck($$$$) { + my $self = shift; my ($dbh, $this_host, $this_service, $datetime) = @_; my $result; - my $id = get_hostNagiosServerID($dbh, $this_host); + my $id = $self->get_hostNagiosServerID($dbh, $this_host); if (defined($id) && $id != 0) { my $submit; @@ -301,11 +301,10 @@ sub forceCheck($$$$) { } else { $submit = "su -l $CENTREON_USER -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] SCHEDULE_FORCED_SVC_CHECK;$this_host;$this_service;$datetime\" >> $cmdFile'"; } - $result = send_command($submit); - - logit("FORCE: Reschedule linked service", "II"); - logit("FORCE: Launched command: $submit", "II"); + $result = $self->send_command($submit); + $self->{logger}->writeLogInfo("FORCE: Reschedule linked service"); + $self->{logger}->writeLogInfo("FORCE: Launched command: $submit"); } return $result; } @@ -314,11 +313,12 @@ sub forceCheck($$$$) { ## Submit result via external command # sub submitResult($$$$$$) { + my $self = shift; my ($dbh, $this_host, $this_service, $datetime, $status, $traps_output) = @_; my $result; # No matching rules - my $id = get_hostNagiosServerID($dbh, $this_host); + my $id = $self->get_hostNagiosServerID($dbh, $this_host); if (defined($id) && $id != 0) { my $str = "PROCESS_SERVICE_CHECK_RESULT;$this_host;$this_service;$status;$traps_output"; @@ -331,10 +331,10 @@ sub submitResult($$$$$$) { $str =~ s/"/\\"/g; $submit = "su -l $CENTREON_USER -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] $str\" >> $cmdFile'"; } - $result = send_command($submit); + $result = $self->send_command($submit); - logit("SUBMIT: Force service status via passive check update", "II"); - logit("SUBMIT: Launched command: $submit", "II"); + $self->{logger}->writeLogInfo("SUBMIT: Force service status via passive check update"); + $self->{logger}->writeLogInfo("SUBMIT: Launched command: $submit"); } return $result; } @@ -343,17 +343,18 @@ sub submitResult($$$$$$) { ## REPLACE # sub substitute_string { + my $self = shift; my $str = $_[0]; # Substitute @{oid_value} and $1, $2,... - for (my $i=0; $i <= $#entvar; $i++) { + for (my $i=0; $i <= $#{$self->{entvar}}; $i++) { my $x = $i + 1; - $str =~ s/\@\{$entvarname[$i]\}/$entvar[$i]/g; - $str =~ s/\$$x(\s|$)/$entvar[$i]/g; + $str =~ s/\@\{${$self->{entvarname}}[$i]\}/${self->{entvar}}[$i]/g; + $str =~ s/\$$x(\s|$)/${self->{entvar}}[$i]/g; } # Substitute $* - my $sub_str = join($centrapmanager_seperator, @entvar); + my $sub_str = join($self->{centreontrapd_config}->{seperator}, @{$self->{entvar}}); $str =~ s/\$\*/$sub_str/g; # Clean OID @@ -365,13 +366,14 @@ sub substitute_string { ## Check Advanced Matching Rules # sub checkMatchingRules($$$$$$$$$) { + my $self = shift; my ($dbh, $trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status) = @_; # Check matching options my $sth = $dbh->prepare("SELECT tmo_regexp, tmo_status, tmo_string FROM traps_matching_properties WHERE trap_id = '".$trap_id."' ORDER BY tmo_order"); $sth->execute(); while (my ($regexp, $tmoStatus, $tmoString) = $sth->fetchrow_array()) { - logit("[$tmoString][$regexp] => $tmoStatus", "DD") if ($centrapmanager_log_debug >= 2); + $self->{logger}->writeLogDebug("[$tmoString][$regexp] => $tmoStatus"); my @temp = split(//, $regexp); my $i = 0; @@ -409,12 +411,11 @@ sub checkMatchingRules($$$$$$$$$) { # Integrate OID Matching if (defined($tmoString) && $tmoString =~ m/$regexp/g) { $status = $tmoStatus; - logit("Regexp: String:$tmoString => REGEXP:$regexp", "II"); - logit("Status: $status ($tmoStatus)", "II"); + $self->{logger}->writeLogInfo("Regexp: String:$tmoString => REGEXP:$regexp"); + $self->{logger}->writeLogInfo("Status: $status ($tmoStatus)"); last; } } - $sth->finish(); return $status; } @@ -422,9 +423,10 @@ sub checkMatchingRules($$$$$$$$$) { ## Execute a specific command # sub executeCommand($$$$$$$$) { + my $self = shift; my ($traps_execution_command, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status) = @_; - $traps_execution_command = substitute_string($traps_execution_command); + $traps_execution_command = $self->substitute_string($traps_execution_command); ########################## # REPLACE MACROS @@ -447,15 +449,15 @@ sub executeCommand($$$$$$$$) { ########################## # SEND COMMAND if ($traps_execution_command) { - logit("EXEC: Launch specific command", "II"); - logit("EXEC: Launched command: $traps_execution_command", "II"); + $self->{logger}->writeLogInfo("EXEC: Launch specific command"); + $self->{logger}->writeLogInfo("EXEC: Launched command: $traps_execution_command"); my $output = `$traps_execution_command`; if ($?) { - logit("EXEC: Execution error: $!", "EE"); + $self->{logger}->writeLogError("EXEC: Execution error: $!"); } if ($output) { - logit("EXEC: Output : $output", "II"); + $self->{logger}->writeLogInfo("EXEC: Output : $output"); } } } @@ -465,13 +467,14 @@ sub executeCommand($$$$$$$$) { ## GET HOSTNAME AND SERVICE DESCRIPTION # sub getTrapsInfos($$$) { + my $self = shift; my $ip = shift; my $hostname = shift; my $oid = shift; my $status; - my %host = get_hostinfos($dbh, $ip, $hostname); + my %host = $self->get_hostinfos($dbh, $ip, $hostname); foreach my $host_id (keys %host) { my $this_host = $host{$host_id}; my ($trap_id, $status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, $ref_servicename) = getServiceInformations($dbh, $oid, $host_id); @@ -483,52 +486,40 @@ sub getTrapsInfos($$$) { foreach (@servicename) { my $this_service = $_; - if ($centrapmanager_log_debug >= 2) { - logit("Trap found on service \'$this_service\' for host \'$this_host\'.", "DD"); - } + $self->{logger}->writeLogDebug("Trap found on service \'$this_service\' for host \'$this_host\'."); my $datetime = `date +%s`; chomp($datetime); - $traps_output = substitute_string($traps_output); + $traps_output = $self->substitute_string($traps_output); ###################################################################### # Advanced matching rules if (defined($traps_advanced_treatment) && $traps_advanced_treatment eq 1) { - $status = checkMatchingRules($dbh, $trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status); + $status = $self->checkMatchingRules($dbh, $trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status); } ##################################################################### # Submit value to passive service if (defined($traps_submit_result_enable) && $traps_submit_result_enable eq 1) { - submitResult($dbh, $this_host, $this_service, $datetime, $status, $traps_output); + $self->submitResult($dbh, $this_host, $this_service, $datetime, $status, $traps_output); } ###################################################################### # Force service execution with external command if (defined($traps_reschedule_svc_enable) && $traps_reschedule_svc_enable eq 1) { - forceCheck($dbh, $this_host, $this_service, $datetime); + $self->forceCheck($dbh, $this_host, $this_service, $datetime); } ###################################################################### # Execute special command if (defined($traps_execution_command_enable) && $traps_execution_command_enable) { - executeCommand($traps_execution_command, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status); + $self->executeCommand($traps_execution_command, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status); } } } } -#################################### -## GenerateError -# - - - -######################################################### -# Beginning -# - sub run { my $self = shift; @@ -562,18 +553,36 @@ sub run { if ($self->{centreontrapd_config}->{daemon} == 1) { while (!$self->{timetodie}) { - centreon::trapd::lib::purge_duplicate_trap(); - while ((my $file = centreon::trapd::lib::get_trap())) { + centreon::trapd::lib::purge_duplicate_trap(config => $self->{centreontrapd_config}, + duplicate_traps => \%{$self->{duplicate_traps}}); + while ((my $file = centreon::trapd::lib::get_trap(logger => $self->{logger}, + config => $self->{centreontrapd_config}, + filenames => \@{$self->{filenames}}))) { $self->{logger}->writeLogDebug("Processing file: $file"); if (open FILE, $self->{spool_directory} . $file) { my $trap_is_a_duplicate = 0; my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, - handle => 'FILE'); + config => $self->{centreontrapd_config}, + handle => 'FILE', + agent_dns => \$self->{agent_dns}, + trap_date => \$self->{trap_date}, + trap_time => \$self->{trap_time}, + trap_date_time => \$self->{trap_date_time}, + trap_date_time_epoch => \$self->{trap_date_time_epoch}, + duplicate_traps => \%{$self->{duplicate_traps}}, + var => \@{$self->{var}}, + entvar => \%{$self->{entvar}}, + entvarname => \%{$self->{entvarname}}); if ($readtrap_result == 1) { - if (centreon::trapd::lib::check_known_trap($var[3]) == 1) { - getTrapsInfos($var[1], $var[2], $var[3]); + if (centreon::trapd::lib::check_known_trap(logger => $self->{logger}, + config => $self->{centreontrapd_config}, + oid2verif => $var[3], + cdb => $self->{cdb}, + last_cache_time => \$self->{last_cache_time}, + oids_cache => \$self->{oids_cache}) == 1) { + $self->getTrapsInfos($var[1], $var[2], $var[3]); } } elsif ($readtrap_result == 0) { $self->{logger}->writeLogDebug("Error processing trap file $file. Skipping..."); @@ -607,10 +616,25 @@ sub run { } } else { my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, - handle => 'STDIN'); + config => $self->{centreontrapd_config}, + handle => 'STDIN', + agent_dns => \$self->{agent_dns}, + trap_date => \$self->{trap_date}, + trap_time => \$self->{trap_time}, + trap_date_time => \$self->{trap_date_time}, + trap_date_time_epoch => \$self->{trap_date_time_epoch}, + duplicate_traps => \%{$self->{duplicate_traps}}, + var => \@{$self->{var}}, + entvar => \%{$self->{entvar}}, + entvarname => \%{$self->{entvarname}}); if ($readtrap_result == 1) { - if (centreon::trapd::lib::check_known_trap($var[3]) == 1) { - getTrapsInfos($var[1], $var[2], $var[3]); + if (centreon::trapd::lib::check_known_trap(logger => $self->{logger}, + config => $self->{centreontrapd_config}, + oid2verif => $var[3], + cdb => $self->{cdb}, + last_cache_time => \$self->{last_cache_time}, + oids_cache => \$self->{oids_cache}) == 1) { + $self->getTrapsInfos($var[1], $var[2], $var[3]); } } elsif ($readtrap_result == 0) { $self->{logger}->writeLogDebug("Error processing trap file. Skipping..."); diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 7de9df2fe69..417b4d360d4 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -56,7 +56,7 @@ sub init_modules { if ($args{config}->{duplicate_trap_window} > 0) { eval 'require Digest::MD5;'; if ($@) { - $args{logger}->writeLogError($@, "EE"); + $args{logger}->writeLogError($@); $args{logger}->writeLogError("Could not load the Perl module Digest::MD5! If centrapmanager_duplicate_trap_window"); $args{logger}->writeLogError("is set then the Digest::MD5 module is required"); $args{logger}->writeLogError("for system requirements."); @@ -91,26 +91,33 @@ sub manage_params_conf { ############## sub get_cache_oids { - my $sth = $dbh->prepare("SELECT traps_oid FROM traps"); - if (!$sth->execute()) { - logit("SELECT traps_oid from traps error: " . $sth->errstr, "EE"); - return 1; - } - $oids_cache = $sth->fetchall_hashref("traps_oid"); - $last_cache_time = time(); + # cdb => connection db + # last_cache_time => ref + # oids_cache => ref + my %args = @_; + + my ($status, $sth) = $args{cdb}->query("SELECT traps_oid FROM traps"); + return 1 if ($status == -1); + ${$args{oids_cache}} = $sth->fetchall_hashref("traps_oid"); + ${$args{last_cache_time}} = time(); return 0; } sub write_cache_file { - if (!open(FILECACHE, ">", $centrapmanager_cache_unknown_traps_file)) { - logit("Can't write $centrapmanager_cache_unknown_traps_file; $!", "EE"); - logit("Go to DB to get info", "EE"); + # logger => obj + # config => hash + # oids_cache => val (not ref) + my %args = @_; + + if (!open(FILECACHE, ">", $args{config}->{cache_unknown_traps_file})) { + $args{logger}->writeLogError("Can't write " . $args{config}->{cache_unknown_traps_file} . ": $!"); + $args{logger}->writeLogError("Go to DB to get info"); return 1; } - my $oids_value = join("\n", keys %$oids_cache); + my $oids_value = join("\n", keys %{$args->{oids_cache}}); print FILECACHE $oids_value; close FILECACHE; - logit("Cache file refreshed", "II") if ($centrapmanager_log_debug >= 1); + $args{logger}->writeLogInfo("Cache file refreshed"); return 0; } @@ -118,18 +125,21 @@ sub check_known_trap { # logger => obj # config => hash # oid2verif => val + # cdb => db connection + # last_cache_time => ref + # oids_cache => ref my %args = @_; my $oid2verif = $args{oid2verif}; my $db_mode = 1; - if ($centrapmanager_cache_unknown_traps_enable == 1) { - if ($centrapmanager_daemon != 1) { + if ($args{config}->{cache_unknown_traps_enable} == 1) { + if ($args{config}->{daemon} != 1) { $db_mode = 0; - if (-e $centrapmanager_cache_unknown_traps_file) { - if ((my $result = stat($centrapmanager_cache_unknown_traps_file))) { - if ((time() - $result->mtime) > $centrapmanager_cache_unknown_traps_retention) { + if (-e $args{config}->{cache_unknown_traps_file}) { + if ((my $result = stat($args{config}->{cache_unknown_traps_file}))) { + if ((time() - $result->mtime) > $args{config}->{cache_unknown_traps_retention}) { $args{logger}->writeLogInfo("Try to rewrite cache"); - !($db_mode = get_cache_oids()) && ($db_mode = write_cache_file()); + !($db_mode = get_cache_oids(cdb => $args{cdb}, oids_cache => $args{oids_cache}, last_cache_time => $args{last_cache_time})) && ($db_mode = write_cache_file(logger => $args{logger}, config => $args{config}, oids_cache => $args{oids_cache})); } } else { $args{logger}->writeLogError("Can't stat file $centrapmanager_cache_unknown_traps_file: $!"); @@ -137,25 +147,25 @@ sub check_known_trap { $db_mode = 1; } } else { - !($db_mode = get_cache_oids()) && ($db_mode = write_cache_file()); + !($db_mode = get_cache_oids(cdb => $args{cdb}, oids_cache => $args{oids_cache}, last_cache_time => $args{last_cache_time})) && ($db_mode = write_cache_file(logger => $args{logger}, config => $args{config}, oids_cache => $args{oids_cache})); } } else { - if (!defined($last_cache_time) || ((time() - $last_cache_time) > $centrapmanager_cache_unknown_traps_retention)) { - $db_mode = get_cache_oids(); + if (!defined(${$args{last_cache_time}}) || ((time() - ${$args{last_cache_time}}) > $args{config}->{cache_unknown_traps_retention})) { + $db_mode = get_cache_oids(cdb => $args{cdb}, oids_cache => $args{oids_cache}, last_cache_time => $args{last_cache_time}); } } } if ($db_mode == 0) { - if (defined($oids_cache)) { - if (defined($oids_cache->{$oid2verif})) { + if (defined(${$args{oids_cache}})) { + if (defined(${$args{oids_cache}}->{$oid2verif})) { return 1; } else { $args{logger}->writeLogInfo("Unknown trap"); return 0; } } else { - if (!open FILECACHE, $centrapmanager_cache_unknown_traps_file) { + if (!open FILECACHE, $args{config}->{cache_unknown_traps_file}) { $args{logger}->writeLogError("Can't read file $centrapmanager_cache_unknown_traps_file: $!"); $db_mode = 1; } else { @@ -173,11 +183,8 @@ sub check_known_trap { if ($db_mode == 1) { # Read db - my $sth = $dbh->prepare("SELECT traps_oid FROM traps WHERE traps_oid = " . $dbh->quote($oid2verif)); - if (!$sth->execute()) { - #$args{logger}->writeLogError("SELECT traps_oid from traps error: " . $sth->errstr); - return 0; - } + my ($status, $sth) = $args{cdb}->query("SELECT traps_oid FROM traps WHERE traps_oid = " . $args{cdb}->quote($oid2verif)); + return 0 if ($status == -1); if ($sth->rows == 0) { $args{logger}->writeLogInfo("Unknown trap"); return 0; @@ -196,24 +203,29 @@ sub check_known_trap { ### sub get_trap { - if (!@filenames) { - if (!(chdir($spool_directory))) { - logit("Unable to enter spool dir $spool_directory:$!", "EE"); + # logger => obj + # config => hash + # filenames => ref array + my %args = @_; + + if (!@{$args{filenames}}) { + if (!(chdir($args{config}->{spool_directory}))) { + $args{logger}->writeLogError("Unable to enter spool dir " . $args{config}->{spool_directory} . ":$!"); return undef; } if (!(opendir(DIR, "."))) { - logit("Unable to open spool dir $spool_directory:$!", "EE"); + $args{logger}->writeLogError("Unable to open spool dir " . $args{config}->{spool_directory} . ":$!"); return undef; } - if (!(@filenames = readdir(DIR))) { - logit("Unable to read spool dir $spool_directory:$!", "EE"); + if (!(@{$args{filenames}} = readdir(DIR))) { + $args{logger}->writeLogError("Unable to read spool dir " . $args{config}->{spool_directory} . ":$!"); return undef; } closedir(DIR); - @filenames = sort (@filenames); + @{$args{filenames}} = sort (@{$args{filenames}}); } - while (($file = shift @filenames)) { + while (($file = shift @{$args{filenames}})) { next if ($file eq "."); next if ($file eq ".."); return $file; @@ -222,11 +234,15 @@ sub get_trap { } sub purge_duplicate_trap { - if ($centrapmanager_duplicate_trap_window) { + # config => hash + # duplicate_traps => ref hash + my %args = @_; + + if ($args{config}->{duplicate_trap_window}) { # Purge traps older than duplicate_trap_window in %duplicate_traps my $duplicate_traps_current_time = time(); - foreach my $key (sort keys %duplicate_traps) { - if ($duplicate_traps{$key} < $duplicate_traps_current_time - $centrapmanager_duplicate_trap_window) { + foreach my $key (sort keys %{$args{duplicate_traps}}) { + if (${args{duplicate_traps}}{$key} < $duplicate_traps_current_time - $args{config}->{duplicate_trap_window}) { # Purge the record delete $duplicate_traps{$key}; } @@ -238,61 +254,71 @@ sub readtrap { # logger => obj # config => hash # handle => str + # agent_dns => ref + # trap_date => ref + # trap_time => ref + # trap_date_time => ref + # trap_date_time_epoch => ref + # duplicate_traps => ref hash + # var => ref array + # entvar => ref array + # entvarname => ref array + my %args = @_; my $input = $args{handle}; # Flush out @tempvar, @var and @entvar my @tempvar = (); - @var = (); - @entvar = (); - @entvarname = (); + @{$args{var}} = (); + @{$args{entvar}} = (); + @{$args{entvarname}} = (); my @rawtrap = (); - $self->{logger}->writeLogDebug("Reading trap. Current time: " . scalar(localtime())); + $args{logger}->writeLogDebug("Reading trap. Current time: " . scalar(localtime())); - if ($centrapmanager_daemon == 1) { - chomp($trap_date_time_epoch = (<$input>)); # Pull time trap was spooled - push(@rawtrap, $trap_date_time_epoch); - if ($trap_date_time_epoch eq "") { - if ($self->{logger}->isDebug()) { - $self->{logger}->writeLogDebug(" Invalid trap file. Expected a serial time on the first line but got nothing"); + if ($args{config}->{daemon} == 1) { + chomp(${$args{trap_date_time_epoch}} = (<$input>)); # Pull time trap was spooled + push(@rawtrap, ${$args{trap_date_time_epoch}}); + if (${$args{trap_date_time_epoch}} eq "") { + if ($args{logger}->isDebug()) { + $args{logger}->writeLogDebug(" Invalid trap file. Expected a serial time on the first line but got nothing"); return 0; } } - $trap_date_time_epoch =~ s(`)(')g; #` Replace any back ticks with regular single quote + ${$args{trap_date_time_epoch}} =~ s(`)(')g; #` Replace any back ticks with regular single quote } else { - $trap_date_time_epoch = time(); # Use current time as time trap was received + ${$args{trap_date_time_epoch}} = time(); # Use current time as time trap was received } my @localtime_array; - if ($centrapmanager_daemon == 1 && $centrapmanager_use_trap_time == 1) { - @localtime_array = localtime($trap_date_time_epoch); + if ($args{config}->{daemon} == 1 && $args{config}->{use_trap_time} == 1) { + @localtime_array = localtime(${$args{trap_date_time_epoch}}); - if ($centrapmanager_date_time_format eq "") { - $trap_date_time = localtime($trap_date_time_epoch); + if ($args{config}->{date_time_format} eq "") { + ${$args{trap_date_time}} = localtime(${$args{trap_date_time_epoch}}); } else { - $trap_date_time = strftime($centrapmanager_date_time_format, @localtime_array); + ${$args{trap_date_time}} = strftime($args{config}->{date_time_format}, @localtime_array); } } else { @localtime_array = localtime(); - if ($centrapmanager_date_time_format eq "") { - $trap_date_time = localtime(); + if ($args{config}->{date_time_format} eq "") { + ${$args{trap_date_time}} = localtime(); } else { - $trap_date_time = strftime($centrapmanager_date_time_format, @localtime_array); + ${$args{trap_date_time}} = strftime($args{config}->{date_time_format}, @localtime_array); } } - $trap_date = strftime($centrapmanager_date_format, @localtime_array); - $trap_time = strftime($centrapmanager_time_format, @localtime_array); + ${$args{trap_date}} = strftime($args{config}->{date_format}, @localtime_array); + ${$args{trap_time}} = strftime($args{config}->{time_format}, @localtime_array); # Pull in passed SNMP info from snmptrapd via STDIN and place in the array @tempvar chomp($tempvar[0]=<$input>); # hostname push(@rawtrap, $tempvar[0]); $tempvar[0] =~ s(`)(')g; #` Replace any back ticks with regular single quote if ($tempvar[0] eq "") { - if ($self->{logger}->isDebug()) { - $self->{logger}->writeLogDebug(" Invalid trap file. Expected a hostname on line 2 but got nothing"); + if ($args{logger}->isDebug()) { + $args{logger}->writeLogDebug(" Invalid trap file. Expected a hostname on line 2 but got nothing"); return 0; } } @@ -301,8 +327,8 @@ sub readtrap { push(@rawtrap, $tempvar[1]); $tempvar[1] =~ s(`)(')g; #` Replace any back ticks with regular single quote if ($tempvar[1] eq "") { - if ($self->{logger}->isDebug()) { - $self->{logger}->writeLogDebug(" Invalid trap file. Expected an IP address on line 3 but got nothing"); + if ($args{logger}->isDebug()) { + $args{logger}->writeLogDebug(" Invalid trap file. Expected an IP address on line 3 but got nothing"); return 0; } } @@ -325,7 +351,7 @@ sub readtrap { $line =~ s(`)(')g; #` Replace any back ticks with regular single quote # Remove escape from quotes if enabled - if ($centrapmanager_remove_backslash_from_quotes == 1) { + if ($args{config}->{remove_backslash_from_quotes} == 1) { $line =~ s/\\\"/"/g; } @@ -350,13 +376,13 @@ sub readtrap { if ($variable_fix == 0 ) { # Make sure variable names are numerical - $temp1 = translate_symbolic_to_oid($temp1); + $temp1 = translate_symbolic_to_oid($temp1, $args{logger}, $args{config}); # If line begins with a double quote (") but does not END in a double quote then we need to merge # the following lines together into one until we find the closing double quote. Allow for escaped quotes. # Net-SNMP sometimes divides long lines into multiple lines.. if ( ($temp2 =~ /^\"/) && ( ! ($temp2 =~ /[^\\]\"$/)) ) { - $self->{logger}->writeLogDebug(" Multi-line value detected - merging onto one line..."); + $args{logger}->writeLogDebug(" Multi-line value detected - merging onto one line..."); chomp $temp2; # Remove the newline character while (defined(my $line2 = <$input>)) { chomp $line2; @@ -398,13 +424,13 @@ sub readtrap { # v4.2.3 should NOT be used with SNMPTT as it prevents SNMP V2 traps # from being handled correctly. - $self->{logger}->writeLogDebug("Data passed from snmptrapd is incorrect. UCD-SNMP v4.2.3 is known to cause this"); + $args{logger}->writeLogDebug("Data passed from snmptrapd is incorrect. UCD-SNMP v4.2.3 is known to cause this"); # If line begins with a double quote (") but does not END in a double quote then we need to merge # the following lines together into one until we find the closing double quote. Allow for escaped quotes. # Net-SNMP sometimes divides long lines into multiple lines.. if ( ($line =~ /^\"/) && ( ! ($line =~ /[^\\]\"$/)) ) { - $self->{logger}->writeLogDebug(" Multi-line value detected - merging onto one line..."); + $args{logger}->writeLogDebug(" Multi-line value detected - merging onto one line..."); chomp $line; # Remove the newline character while (defined(my $line2 = <$input>)) { chomp $line2; @@ -436,40 +462,40 @@ sub readtrap { $linenum++; } - if ($self->{logger}->isDebug()) { + if ($args{logger}->isDebug()) { # Print out raw trap passed from snmptrapd - $self->{logger}->writeLogDebug("Raw trap passed from snmptrapd:"); + $args{logger}->writeLogDebug("Raw trap passed from snmptrapd:"); for (my $i=0;$i <= $#rawtrap;$i++) { chomp($rawtrap[$i]); - $self->{logger}->writeLogDebug("$rawtrap[$i]"); + $args{logger}->writeLogDebug("$rawtrap[$i]"); } # Print out all items passed from snmptrapd - $self->{logger}->writeLogDebug("Items passed from snmptrapd:"); + $args{logger}->writeLogDebug("Items passed from snmptrapd:"); for (my $i=0;$i <= $#tempvar;$i++) { - $self->{logger}->writeLogDebug("value $i: $tempvar[$i]"); + $args{logger}->writeLogDebug("value $i: $tempvar[$i]"); } } # Copy what I need to new variables to make it easier to manipulate later # Standard variables - $var[0] = $tempvar[0]; # hostname - $var[1] = $tempvar[1]; # ip address - $var[2] = $tempvar[3]; # uptime - $var[3] = $tempvar[5]; # trapname / OID - assume first value after uptime is + ${$args{var}}[0] = $tempvar[0]; # hostname + ${$args{var}}[1] = $tempvar[1]; # ip address + ${$args{var}}[2] = $tempvar[3]; # uptime + ${$args{var}}[3] = $tempvar[5]; # trapname / OID - assume first value after uptime is # the trap OID (value for .1.3.6.1.6.3.1.1.4.1.0) - $var[4] = ""; # Clear ip address from trap agent - $var[5] = ""; # Clear trap community string - $var[6] = ""; # Clear enterprise - $var[7] = ""; # Clear securityEngineID - $var[8] = ""; # Clear securityName - $var[9] = ""; # Clear contextEngineID - $var[10] = ""; # Clear contextName + ${$args{var}}[4] = ""; # Clear ip address from trap agent + ${$args{var}}[5] = ""; # Clear trap community string + ${$args{var}}[6] = ""; # Clear enterprise + ${$args{var}}[7] = ""; # Clear securityEngineID + ${$args{var}}[8] = ""; # Clear securityName + ${$args{var}}[9] = ""; # Clear contextEngineID + ${$args{var}}[10] = ""; # Clear contextName # Make sure trap OID is numerical as event lookups are done using numerical OIDs only - $var[3] = translate_symbolic_to_oid($var[3]); + ${$args{var}}[3] = translate_symbolic_to_oid(${$args{var}}[3], $args{logger}, $args{config}); # Cycle through remaining variables searching for for agent IP (.1.3.6.1.6.3.18.1.3.0), # community name (.1.3.6.1.6.3.18.1.4.0) and enterpise (.1.3.6.1.6.3.1.1.4.3.0) @@ -478,116 +504,116 @@ sub readtrap { for (my $i=6;$i <= $#tempvar; $i+=2) { if ($tempvar[$i] =~ /^.1.3.6.1.6.3.18.1.3.0$/) { # ip address from trap agent - $var[4] = $tempvar[$i+1]; + ${$args{var}}[4] = $tempvar[$i+1]; } elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.18.1.4.0$/) { # trap community string - $var[5] = $tempvar[$i+1]; + ${$args{var}}[5] = $tempvar[$i+1]; } elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.1.1.4.3.0$/) { # enterprise - # $var[6] = $tempvar[$i+1]; + # ${$args{var}}[6] = $tempvar[$i+1]; # Make sure enterprise value is numerical - $var[6] = translate_symbolic_to_oid($tempvar[$i+1]); + ${$args{var}}[6] = translate_symbolic_to_oid($tempvar[$i+1], $args{logger}, $args{config}); } elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.10.2.1.1.0$/) { # securityEngineID - $var[7] = $tempvar[$i+1]; + ${$args{var}}[7] = $tempvar[$i+1]; } elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.18.1.1.1.3$/) { # securityName - $var[8] = $tempvar[$i+1]; + ${$args{var}}[8] = $tempvar[$i+1]; } elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.18.1.1.1.4$/) { # contextEngineID - $var[9] = $tempvar[$i+1]; + ${$args{var}}[9] = $tempvar[$i+1]; } elsif ($tempvar[$i] =~ /^.1.3.6.1.6.3.18.1.1.1.5$/) { # contextName - $var[10] = $tempvar[$i+1]; + ${$args{var}}[10] = $tempvar[$i+1]; } else { # application specific variables - $entvarname[$j] = $tempvar[$i]; - $entvar[$j] = $tempvar[$i+1]; + ${$args{entvarname}}[$j] = $tempvar[$i]; + ${$args{entvar}}[$j] = $tempvar[$i+1]; $j++; } } # Only if it's not already resolved - if ($centrapmanager_dns_enable == 1 && $var[0] =~ /^\d+\.\d+\.\d+\.\d+$/) { - my $temp = gethostbyaddr(Socket::inet_aton($var[0]),Socket::AF_INET()); + if ($args{config}->{dns_enable} == 1 && ${$args{var}}[0] =~ /^\d+\.\d+\.\d+\.\d+$/) { + my $temp = gethostbyaddr(Socket::inet_aton(${$args{var}}[0]),Socket::AF_INET()); if (defined ($temp)) { - $self->{logger}->writeLogDebug("Host IP address ($var[0]) resolved to: $temp"); - $var[0] = $temp; + $args{logger}->writeLogDebug("Host IP address (" . ${$args{var}}[0] . ") resolved to: $temp"); + ${$args{var}}[0] = $temp; } else { - $self->{logger}->writeLogDebug("Host IP address ($var[0]) could not be resolved by DNS. Variable \$r / \$R etc will use the IP address"); + $args{logger}->writeLogDebug("Host IP address (" . ${$args{var}}[0] . ") could not be resolved by DNS. Variable \$r / \$R etc will use the IP address"); } } # If the agent IP is blank, copy the IP from the host IP. # var[4] would only be blank if it wasn't passed from snmptrapd, which # should only happen with ucd-snmp 4.2.3, which you should be using anyway! - if ($var[4] eq '') { - $var[4] = $var[1]; - $self->{logger}->writeLogDebug("Agent IP address was blank, so setting to the same as the host IP address of $var[1]"); + if (${$args{var}}[4] eq '') { + ${$args{var}}[4] = ${$args{var}}[1]; + $args{logger}->writeLogDebug("Agent IP address was blank, so setting to the same as the host IP address of " . ${$args{var}}[1]); } # If the agent IP is the same as the host IP, then just use the host DNS name, no need # to look up, as it's obviously the same.. - if ($var[4] eq $var[1]) { - $self->{logger}->writeLogDebug("Agent IP address ($var[4]) is the same as the host IP, so copying the host name: $var[0]"); - $agent_dns_name = $var[0]; + if (${$args{var}}[4] eq ${$args{var}}[1]) { + $args{logger}->writeLogDebug("Agent IP address (" . ${$args{var}}[4] . ") is the same as the host IP, so copying the host name: " . ${$args{var}}[0]); + ${$args{agent_dns_name}} = ${$args{var}}[0]; } else { - $agent_dns_name = $var[4]; # Default to IP address - if ($centrapmanager_dns_enable == 1 && $var[4] ne '') { - my $temp = gethostbyaddr(Socket::inet_aton($var[4]),Socket::AF_INET()); + ${$args{agent_dns_name}} = ${$args{var}}[4]; # Default to IP address + if ($args{config}->{dns_enable} == 1 && ${$args{var}}[4] ne '') { + my $temp = gethostbyaddr(Socket::inet_aton(${$args{var}}[4]),Socket::AF_INET()); if (defined ($temp)) { - $self->{logger}->writeLogDebug("Agent IP address ($var[4]) resolved to: $temp"); - $agent_dns_name = $temp; + $args{logger}->writeLogDebug("Agent IP address (" . ${$args{var}}[4] . ") resolved to: $temp"); + ${$args{agent_dns_name}} = $temp; } else { - $self->{logger}->writeLogDebug("Agent IP address ($var[4]) could not be resolved by DNS. Variable \$A etc will use the IP address"); + $args{logger}->writeLogDebug("Agent IP address (" . ${$args{var}}[4] . ") could not be resolved by DNS. Variable \$A etc will use the IP address"); } } } - if ($centrapmanager_strip_domain) { - $var[0] = strip_domain_name($var[0], $centrapmanager_strip_domain); - $agent_dns_name = strip_domain_name($agent_dns_name, $centrapmanager_strip_domain); + if ($args{config}->{strip_domain}) { + ${$args{var}}[0] = strip_domain_name(${$args{var}}[0], $args{config}->{strip_domain}, $args{config}); + ${$args{agent_dns_name}} = strip_domain_name(${$args{agent_dns_name}}, $args{config}->{strip_domain}, $args{config}); } - $self->{logger}->writeLogDebug("Trap received from $tempvar[0]: $tempvar[5]"); - - if ($self->{logger}->isDebug()) { - $self->{logger}->writeLogDebug("0: hostname"); - $self->{logger}->writeLogDebug("1: ip address"); - $self->{logger}->writeLogDebug("2: uptime"); - $self->{logger}->writeLogDebug("3: trapname / OID"); - $self->{logger}->writeLogDebug("4: ip address from trap agent"); - $self->{logger}->writeLogDebug("5: trap community string"); - $self->{logger}->writeLogDebug("6: enterprise"); - $self->{logger}->writeLogDebug("7: securityEngineID (not use)"); - $self->{logger}->writeLogDebug("8: securityName (not use)"); - $self->{logger}->writeLogDebug("9: contextEngineID (not use)"); - $self->{logger}->writeLogDebug("10: contextName (not)"); - $self->{logger}->writeLogDebug("0+: passed variables"); + $args{logger}->writeLogDebug("Trap received from $tempvar[0]: $tempvar[5]"); + + if ($args{logger}->isDebug()) { + $args{logger}->writeLogDebug("0: hostname"); + $args{logger}->writeLogDebug("1: ip address"); + $args{logger}->writeLogDebug("2: uptime"); + $args{logger}->writeLogDebug("3: trapname / OID"); + $args{logger}->writeLogDebug("4: ip address from trap agent"); + $args{logger}->writeLogDebug("5: trap community string"); + $args{logger}->writeLogDebug("6: enterprise"); + $args{logger}->writeLogDebug("7: securityEngineID (not use)"); + $args{logger}->writeLogDebug("8: securityName (not use)"); + $args{logger}->writeLogDebug("9: contextEngineID (not use)"); + $args{logger}->writeLogDebug("10: contextName (not)"); + $args{logger}->writeLogDebug("0+: passed variables"); #print out all standard variables - for (my $i=0;$i <= $#var;$i++) { - $self->{logger}->writeLogDebug("Value $i: $var[$i]"); + for (my $i=0;$i <= $#{$args{var}};$i++) { + $args{logger}->writeLogDebug("Value $i: " . ${$args{var}}[$i]); } - $self->{logger}->writeLogDebug("Agent dns name: $agent_dns_name"); + $args{logger}->writeLogDebug("Agent dns name: " . ${$args{agent_dns_name}}); #print out all enterprise specific variables - for (my $i=0;$i <= $#entvar;$i++) { - $self->{logger}->writeLogDebug("Ent Value $i (\$" . ($i+1) . "): $entvarname[$i]=$entvar[$i]"); + for (my $i=0;$i <= $#{args{entvar}};$i++) { + $args{logger}->writeLogDebug("Ent Value $i (\$" . ($i+1) . "): " . ${$args{entvarname}}[$i] . "=" . ${$args{entvar}}[$i]); } } # Generate hash of trap and detect duplicates - if ($centrapmanager_duplicate_trap_window) { + if ($args{config}->{duplicate_trap_window}) { my $md5 = Digest::MD5->new; # All variables except for uptime. - $md5->add($var[0],$var[1].$var[3].$var[4].$var[5].$var[6].$var[7].$var[8].$var[9].$var[10]."@entvar"); + $md5->add(${$args{var}}[0],${$args{var}}[1].${$args{var}}[3].${$args{var}}[4].${$args{var}}[5].${$args{var}}[6].${$args{var}}[7].${$args{var}}[8].${$args{var}}[9].${$args{var}}[10]."@{$args{entvar}}"); my $trap_digest = $md5->hexdigest; - $self->{logger}->writeLogDebug("Trap digest: $trap_digest"); + $args{logger}->writeLogDebug("Trap digest: $trap_digest"); - if ($duplicate_traps{$trap_digest}) { + if ($args{duplicate_traps}->{$trap_digest}) { # Duplicate trap detected. Skipping trap... return -1; } - $duplicate_traps{$trap_digest} = time(); + $args{duplicate_traps}->{$trap_digest} = time(); } return 1; @@ -623,31 +649,25 @@ sub readtrap { sub translate_symbolic_to_oid { my $temp = shift; + my $logger = shift; + my $config = shift; # Check to see if OID passed from snmptrapd is fully numeric. If not, try to translate if (! ($temp =~ /^(\.\d+)+$/)) { # Not numeric # Try to convert to numerical - if ($centrapmanager_log_debug >= 2) { - logit("Symbolic trap variable name detected ($temp). Will attempt to translate to a numerical OID", "DD"); - } - if ($centrapmanager_net_snmp_perl_enable == 1) { + $logger->writeLogDebug("Symbolic trap variable name detected ($temp). Will attempt to translate to a numerical OID"); + if ($config->{net_snmp_perl_enable} == 1) { my $temp3 = SNMP::translateObj("$temp",0); if (defined ($temp3) ) { - if ($centrapmanager_log_debug >= 2) { - logit(" Translated to $temp3\n", "DD"); - } + $args{logger}->writeLogDebug(" Translated to $temp3"); $temp = $temp3; } else { # Could not translate default to numeric - if ($centrapmanager_log_debug >= 2) { - logit(" Could not translate - will leave as-is", "DD"); - } + $logger->writeLogDebug(" Could not translate - will leave as-is"); } } else { - if ($centrapmanager_log_debug >= 2) { - logit(" Could not translate - Net-SNMP Perl module not enabled - will leave as-is", "DD"); - } + $logger->writeLogDebug(" Could not translate - Net-SNMP Perl module not enabled - will leave as-is"); } } return $temp; @@ -657,6 +677,7 @@ sub translate_symbolic_to_oid sub strip_domain_name { my $name = shift; my $mode = shift; + my $config = shift; # If mode = 1, strip off all domain names leaving only the host if ($mode == 1 && !($name =~ /^\d+\.\d+\.\d+\.\d+$/)) { @@ -665,8 +686,8 @@ sub strip_domain_name { $name = $1; } } elsif ($mode == 2 && !($name =~ /^\d+\.\d+\.\d+\.\d+$/)) { # If mode = 2, strip off the domains as listed in strip_domain_list in .ini file - if (@centrapmanager_strip_domain_list) { - foreach my $strip_domain_list_temp (@centrapmanager_strip_domain_list) { + if (@{$config->{strip_domain_list}}) { + foreach my $strip_domain_list_temp (@{$config->{strip_domain_list}}) { if ($strip_domain_list_temp =~ /^\..*/) { # If domain from list starts with a '.' then remove it first ($strip_domain_list_temp) = $strip_domain_list_temp =~ /^\.(.*)/; } From c5fdc9c6e1f4e903a736ee30a8be2046de5bdcda Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 22 Mar 2013 14:44:54 +0100 Subject: [PATCH 020/458] Continue work on trapd --- .../lib/perl/centreon/script/centreontrapd.pm | 138 +++++++++--------- centreon/lib/perl/centreon/trapd/lib.pm | 14 +- 2 files changed, 72 insertions(+), 80 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 843ea860568..693a7aa621d 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -73,7 +73,7 @@ sub new { %{$self->{duplicate_traps}} = undef; $self->{timetoreload} = 0; $self->{timetodie} = 0; - @{self->{filenames}} = undef; + @{$self->{filenames}} = undef; $self->{oids_cache} = undef; $self->{last_cache_time} = undef; $self->{whoami} = undef; @@ -137,7 +137,7 @@ sub send_command { eval { local $SIG{ALRM} = sub { die "TIMEOUT"; }; - alarm($centrapmanager_cmd_timeout); + alarm($self->{centreontrapd_config}->{cmd_timeout}); system @_; alarm(0); }; @@ -153,66 +153,61 @@ sub send_command { ############################### ## GET HOSTNAME FROM IP ADDRESS # -sub get_hostinfos($$$) { +sub get_hostinfos($$) { my $self = shift; my %host = (); - my $sth = $_[0]->prepare("SELECT host_id, host_name FROM host WHERE host_address='$_[1]' OR host_address='$_[2]'"); - $sth->execute(); + my ($status, $sth) = $self->{cdb}->query("SELECT host_id, host_name FROM host WHERE host_address='$_[0]' OR host_address='$_[1]'"); while (my ($host_id, $host_name) = $sth->fetchrow_array()) { $host{$host_id} = $host_name; } - $sth->finish(); return %host; } ############################### ## GET host location # -sub get_hostlocation($$) { +sub get_hostlocation($) { my $self = shift; - my $sth = $_[0]->prepare("SELECT localhost FROM host, `ns_host_relation`, nagios_server WHERE host.host_id = ns_host_relation.host_host_id AND ns_host_relation.nagios_server_id = nagios_server.id AND host.host_name = '".$_[1]."'"); - $sth->execute(); + my ($status, $sth) = $self->{cdb}->query("SELECT localhost FROM host, `ns_host_relation`, nagios_server WHERE host.host_id = ns_host_relation.host_host_id AND ns_host_relation.nagios_server_id = nagios_server.id AND host.host_name = '".$_[0]."'"); if ($sth->rows()){ my $temp = $sth->fetchrow_array(); $sth->finish(); - return $temp; + return $temp; } else { - return 0; + return 0; } } ################################## ## GET nagios server id for a host # -sub get_hostNagiosServerID($$) { +sub get_hostNagiosServerID($) { my $self = shift; - my $sth = $_[0]->prepare("SELECT id FROM host, `ns_host_relation`, nagios_server WHERE host.host_id = ns_host_relation.host_host_id AND ns_host_relation.nagios_server_id = nagios_server.id AND (host.host_name = '".$_[1]."' OR host.host_address = '".$_[1]."')"); - $sth->execute(); + my ($status, $sth) = $self->{cdb}->query("SELECT id FROM host, `ns_host_relation`, nagios_server WHERE host.host_id = ns_host_relation.host_host_id AND ns_host_relation.nagios_server_id = nagios_server.id AND (host.host_name = '".$_[0]."' OR host.host_address = '".$_[0]."')"); if ($sth->rows()){ - my $temp = $sth->fetchrow_array(); - $sth->finish(); - return $temp; + my $temp = $sth->fetchrow_array(); + $sth->finish(); + return $temp; } else { - return 0; + return 0; } } ##################################################################### ## GET SERVICES FOR GIVEN HOST (GETTING SERVICES TEMPLATES IN ACCOUNT) # -sub getServicesIncludeTemplate($$$$) { +sub getServicesIncludeTemplate($$$) { my $self = shift; - my ($dbh, $sth_st, $host_id, $trap_id) = @_; + my $status; + my ($sth_st, $host_id, $trap_id) = @_; my @service; - $sth_st->execute(); while (my @temp = $sth_st->fetchrow_array()) { my $tr_query = "SELECT `traps_id` FROM `traps_service_relation` WHERE `service_id` = '".$temp[0]."' AND `traps_id` = '".$trap_id."'"; - my $sth_st3 = $dbh->prepare($tr_query); - $sth_st3->execute(); + ($status, my $sth_st3) = $self->{cdb}->query($tr_query); my @trap = $sth_st3->fetchrow_array(); if (defined($trap[0])) { $service[scalar(@service)] = $temp[1]; @@ -222,12 +217,10 @@ sub getServicesIncludeTemplate($$$$) { my $service_template = $temp[2]; while (!$found) { my $st1_query = "SELECT `service_id`, `service_template_model_stm_id`, `service_description` FROM service s WHERE `service_id` = '".$service_template."'"; - my $sth_st1 = $dbh->prepare($st1_query); - $sth_st1 -> execute(); + ($status, my $sth_st1) = $self->{cdb}->query($st1_query); my @st1_result = $sth_st1->fetchrow_array(); if (defined($st1_result[0])) { - my $sth_st2 = $dbh->prepare("SELECT `traps_id` FROM `traps_service_relation` WHERE `service_id` = '".$service_template."' AND `traps_id` = '".$trap_id."'"); - $sth_st2->execute(); + ($status, my $sth_st2) = $self->{cdb}->query("SELECT `traps_id` FROM `traps_service_relation` WHERE `service_id` = '".$service_template."' AND `traps_id` = '".$trap_id."'"); my @st2_result = $sth_st2->fetchrow_array(); if (defined($st2_result[0])) { $found = 1; @@ -239,7 +232,7 @@ sub getServicesIncludeTemplate($$$$) { $found = 0; } } - $sth_st2->finish; + $sth_st2->finish; } $sth_st1->finish; } @@ -255,10 +248,11 @@ sub getServicesIncludeTemplate($$$$) { ########################## # GET SERVICE DESCRIPTION # -sub getServiceInformations($$$) { +sub getServiceInformations($$) { my $self = shift; - my $sth = $_[0]->prepare("SELECT `traps_id`, `traps_status`, `traps_submit_result_enable`, `traps_execution_command`, `traps_reschedule_svc_enable`, `traps_execution_command_enable`, `traps_advanced_treatment`, `traps_args` FROM `traps` WHERE `traps_oid` = '$_[1]'"); - $sth->execute(); + my $status; + + ($status, my $sth) = $self->{cdb}->query("SELECT `traps_id`, `traps_status`, `traps_submit_result_enable`, `traps_execution_command`, `traps_reschedule_svc_enable`, `traps_execution_command_enable`, `traps_advanced_treatment`, `traps_args` FROM `traps` WHERE `traps_oid` = '$_[0]'"); my ($trap_id, $trap_status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output) = $sth->fetchrow_array(); return(undef) if (!defined $trap_id); $sth->finish(); @@ -266,19 +260,18 @@ sub getServiceInformations($$$) { ###################################################### # getting all "services by host" for given host my $st_query = "SELECT s.service_id, service_description, service_template_model_stm_id FROM service s, host_service_relation h"; - $st_query .= " where s.service_id = h.service_service_id and h.host_host_id='$_[2]'"; - my $sth_st = $_[0]->prepare($st_query); - my @service = $self->getServicesIncludeTemplate($_[0], $sth_st, $_[2], $trap_id); + $st_query .= " where s.service_id = h.service_service_id and h.host_host_id='$_[1]'"; + ($status, my $sth_st) = $self->{cdb}->query($st_query); + my @service = $self->getServicesIncludeTemplate($sth_st, $_[1], $trap_id); $sth_st->finish; ###################################################### # getting all "services by hostgroup" for given host my $query_hostgroup_services = "SELECT s.service_id, service_description, service_template_model_stm_id FROM hostgroup_relation hgr, service s, host_service_relation hsr"; - $query_hostgroup_services .= " WHERE hgr.host_host_id = '".$_[2]."' AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id"; + $query_hostgroup_services .= " WHERE hgr.host_host_id = '".$_[1]."' AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id"; $query_hostgroup_services .= " AND s.service_id = hsr.service_service_id"; - $sth_st = $_[0]->prepare($query_hostgroup_services); - $sth_st->execute(); - @service = (@service, $self->getServicesIncludeTemplate($_[0], $sth_st, $_[2], $trap_id)); + ($status, $sth_st) = $self->{cdb}->query($query_hostgroup_services); + @service = (@service, $self->getServicesIncludeTemplate($sth_st, $_[1], $trap_id)); $sth_st->finish; return $trap_id, $trap_status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, \@service; @@ -287,22 +280,22 @@ sub getServiceInformations($$$) { ###################################### ## Force a new check for selected services # -sub forceCheck($$$$) { +sub forceCheck($$$) { my $self = shift; - my ($dbh, $this_host, $this_service, $datetime) = @_; + my ($this_host, $this_service, $datetime) = @_; my $result; - my $id = $self->get_hostNagiosServerID($dbh, $this_host); + my $id = $self->get_hostNagiosServerID($this_host); if (defined($id) && $id != 0) { my $submit; - if ($whoami eq $CENTREON_USER) { - $submit = "/bin/echo \"EXTERNALCMD:$id:[$datetime] SCHEDULE_FORCED_SVC_CHECK;$this_host;$this_service;$datetime\" >> $cmdFile"; + if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { + $submit = "/bin/echo \"EXTERNALCMD:$id:[$datetime] SCHEDULE_FORCED_SVC_CHECK;$this_host;$this_service;$datetime\" >> " . $self->{centreontrapd_config}->{cmdFile}; } else { - $submit = "su -l $CENTREON_USER -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] SCHEDULE_FORCED_SVC_CHECK;$this_host;$this_service;$datetime\" >> $cmdFile'"; + $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] SCHEDULE_FORCED_SVC_CHECK;$this_host;$this_service;$datetime\" >> " . $self->{centreontrapd_config}->{cmdFile} . "'"; } $result = $self->send_command($submit); - + $self->{logger}->writeLogInfo("FORCE: Reschedule linked service"); $self->{logger}->writeLogInfo("FORCE: Launched command: $submit"); } @@ -312,27 +305,27 @@ sub forceCheck($$$$) { ####################################### ## Submit result via external command # -sub submitResult($$$$$$) { +sub submitResult($$$$$) { my $self = shift; - my ($dbh, $this_host, $this_service, $datetime, $status, $traps_output) = @_; + my ($this_host, $this_service, $datetime, $status, $traps_output) = @_; my $result; # No matching rules - my $id = $self->get_hostNagiosServerID($dbh, $this_host); + my $id = $self->get_hostNagiosServerID($this_host); if (defined($id) && $id != 0) { my $str = "PROCESS_SERVICE_CHECK_RESULT;$this_host;$this_service;$status;$traps_output"; my $submit; - if ($whoami eq $CENTREON_USER) { + if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { $str =~ s/"/\\"/g; - $submit = "/bin/echo \"EXTERNALCMD:$id:[$datetime] $str\" >> $cmdFile"; + $submit = "/bin/echo \"EXTERNALCMD:$id:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile}; } else { $str =~ s/'/'\\''/g; $str =~ s/"/\\"/g; - $submit = "su -l $CENTREON_USER -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] $str\" >> $cmdFile'"; + $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile} . "'"; } $result = $self->send_command($submit); - + $self->{logger}->writeLogInfo("SUBMIT: Force service status via passive check update"); $self->{logger}->writeLogInfo("SUBMIT: Launched command: $submit"); } @@ -349,8 +342,8 @@ sub substitute_string { # Substitute @{oid_value} and $1, $2,... for (my $i=0; $i <= $#{$self->{entvar}}; $i++) { my $x = $i + 1; - $str =~ s/\@\{${$self->{entvarname}}[$i]\}/${self->{entvar}}[$i]/g; - $str =~ s/\$$x(\s|$)/${self->{entvar}}[$i]/g; + $str =~ s/\@\{${$self->{entvarname}}[$i]\}/${$self->{entvar}}[$i]/g; + $str =~ s/\$$x(\s|$)/${$self->{entvar}}[$i]/g; } # Substitute $* @@ -367,11 +360,10 @@ sub substitute_string { # sub checkMatchingRules($$$$$$$$$) { my $self = shift; - my ($dbh, $trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status) = @_; + my ($trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status) = @_; # Check matching options - my $sth = $dbh->prepare("SELECT tmo_regexp, tmo_status, tmo_string FROM traps_matching_properties WHERE trap_id = '".$trap_id."' ORDER BY tmo_order"); - $sth->execute(); + my ($status, $sth) = $self->{cdb}->query("SELECT tmo_regexp, tmo_status, tmo_string FROM traps_matching_properties WHERE trap_id = '".$trap_id."' ORDER BY tmo_order"); while (my ($regexp, $tmoStatus, $tmoString) = $sth->fetchrow_array()) { $self->{logger}->writeLogDebug("[$tmoString][$regexp] => $tmoStatus"); @@ -394,7 +386,7 @@ sub checkMatchingRules($$$$$$$$$) { ########################## # REPLACE special Chars - if ($htmlentities == 1) { + if ($self->{htmlentities} == 1) { $tmoString = decode_entities($tmoString); } else { $tmoString =~ s/\"\;/\"/g; @@ -408,7 +400,7 @@ sub checkMatchingRules($$$$$$$$$) { $tmoString =~ s/\@OUTPUT\@/$traps_output/g; $tmoString =~ s/\@TIME\@/$datetime/g; - # Integrate OID Matching + # Integrate OID Matching if (defined($tmoString) && $tmoString =~ m/$regexp/g) { $status = $tmoStatus; $self->{logger}->writeLogInfo("Regexp: String:$tmoString => REGEXP:$regexp"); @@ -430,7 +422,7 @@ sub executeCommand($$$$$$$$) { ########################## # REPLACE MACROS - if ($htmlentities == 1) { + if ($self->{htmlentities} == 1) { $traps_execution_command = decode_entities($traps_execution_command); } else { $traps_execution_command =~ s/\"\;/\"/g; @@ -451,7 +443,7 @@ sub executeCommand($$$$$$$$) { if ($traps_execution_command) { $self->{logger}->writeLogInfo("EXEC: Launch specific command"); $self->{logger}->writeLogInfo("EXEC: Launched command: $traps_execution_command"); - + my $output = `$traps_execution_command`; if ($?) { $self->{logger}->writeLogError("EXEC: Execution error: $!"); @@ -474,15 +466,15 @@ sub getTrapsInfos($$$) { my $status; - my %host = $self->get_hostinfos($dbh, $ip, $hostname); + my %host = $self->get_hostinfos($ip, $hostname); foreach my $host_id (keys %host) { my $this_host = $host{$host_id}; - my ($trap_id, $status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, $ref_servicename) = getServiceInformations($dbh, $oid, $host_id); + my ($trap_id, $status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, $ref_servicename) = getServiceInformations($oid, $host_id); if (!defined($trap_id)) { return ; } my @servicename = @{$ref_servicename}; - + foreach (@servicename) { my $this_service = $_; @@ -496,21 +488,21 @@ sub getTrapsInfos($$$) { ###################################################################### # Advanced matching rules if (defined($traps_advanced_treatment) && $traps_advanced_treatment eq 1) { - $status = $self->checkMatchingRules($dbh, $trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status); + $status = $self->checkMatchingRules($trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status); } ##################################################################### # Submit value to passive service if (defined($traps_submit_result_enable) && $traps_submit_result_enable eq 1) { - $self->submitResult($dbh, $this_host, $this_service, $datetime, $status, $traps_output); + $self->submitResult($this_host, $this_service, $datetime, $status, $traps_output); } ###################################################################### # Force service execution with external command if (defined($traps_reschedule_svc_enable) && $traps_reschedule_svc_enable eq 1) { - $self->forceCheck($dbh, $this_host, $this_service, $datetime); + $self->forceCheck($this_host, $this_service, $datetime); } - + ###################################################################### # Execute special command if (defined($traps_execution_command_enable) && $traps_execution_command_enable) { @@ -578,11 +570,11 @@ sub run { if ($readtrap_result == 1) { if (centreon::trapd::lib::check_known_trap(logger => $self->{logger}, config => $self->{centreontrapd_config}, - oid2verif => $var[3], + oid2verif => ${$self->{var}}[3], cdb => $self->{cdb}, last_cache_time => \$self->{last_cache_time}, oids_cache => \$self->{oids_cache}) == 1) { - $self->getTrapsInfos($var[1], $var[2], $var[3]); + $self->getTrapsInfos(${$self->{var}}[1], ${$self->{var}}[2], ${$self->{var}}[3]); } } elsif ($readtrap_result == 0) { $self->{logger}->writeLogDebug("Error processing trap file $file. Skipping..."); @@ -600,7 +592,7 @@ sub run { } } - $self->{logger}->writeLogDebug("Sleeping for $centrapmanager_sleep seconds"); + $self->{logger}->writeLogDebug("Sleeping for " . $self->{centreontrapd_config}->{sleep} . " seconds"); sleep $self->{centreontrapd_config}->{sleep}; if ($self->{timetoreload} == 1) { @@ -630,11 +622,11 @@ sub run { if ($readtrap_result == 1) { if (centreon::trapd::lib::check_known_trap(logger => $self->{logger}, config => $self->{centreontrapd_config}, - oid2verif => $var[3], + oid2verif => ${$self->{var}}[3], cdb => $self->{cdb}, last_cache_time => \$self->{last_cache_time}, oids_cache => \$self->{oids_cache}) == 1) { - $self->getTrapsInfos($var[1], $var[2], $var[3]); + $self->getTrapsInfos(${$self->{var}}[1], ${$self->{var}}[2], ${$self->{var}}[3]); } } elsif ($readtrap_result == 0) { $self->{logger}->writeLogDebug("Error processing trap file. Skipping..."); diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 417b4d360d4..4eb15c1ccbb 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -114,7 +114,7 @@ sub write_cache_file { $args{logger}->writeLogError("Go to DB to get info"); return 1; } - my $oids_value = join("\n", keys %{$args->{oids_cache}}); + my $oids_value = join("\n", keys %{$args{oids_cache}}); print FILECACHE $oids_value; close FILECACHE; $args{logger}->writeLogInfo("Cache file refreshed"); @@ -142,7 +142,7 @@ sub check_known_trap { !($db_mode = get_cache_oids(cdb => $args{cdb}, oids_cache => $args{oids_cache}, last_cache_time => $args{last_cache_time})) && ($db_mode = write_cache_file(logger => $args{logger}, config => $args{config}, oids_cache => $args{oids_cache})); } } else { - $args{logger}->writeLogError("Can't stat file $centrapmanager_cache_unknown_traps_file: $!"); + $args{logger}->writeLogError("Can't stat file " . $args{config}->{cache_unknown_traps_file} . ": $!"); $args{logger}->writeLogError("Go to DB to get info"); $db_mode = 1; } @@ -166,7 +166,7 @@ sub check_known_trap { } } else { if (!open FILECACHE, $args{config}->{cache_unknown_traps_file}) { - $args{logger}->writeLogError("Can't read file $centrapmanager_cache_unknown_traps_file: $!"); + $args{logger}->writeLogError("Can't read file " . $args{config}->{cache_unknown_traps_file} . ": $!"); $db_mode = 1; } else { while () { @@ -225,7 +225,7 @@ sub get_trap { @{$args{filenames}} = sort (@{$args{filenames}}); } - while (($file = shift @{$args{filenames}})) { + while ((my $file = shift @{$args{filenames}})) { next if ($file eq "."); next if ($file eq ".."); return $file; @@ -244,7 +244,7 @@ sub purge_duplicate_trap { foreach my $key (sort keys %{$args{duplicate_traps}}) { if (${args{duplicate_traps}}{$key} < $duplicate_traps_current_time - $args{config}->{duplicate_trap_window}) { # Purge the record - delete $duplicate_traps{$key}; + delete ${args{duplicate_traps}}{$key}; } } } @@ -593,7 +593,7 @@ sub readtrap { $args{logger}->writeLogDebug("Agent dns name: " . ${$args{agent_dns_name}}); #print out all enterprise specific variables - for (my $i=0;$i <= $#{args{entvar}};$i++) { + for (my $i=0;$i <= $#{$args{entvar}};$i++) { $args{logger}->writeLogDebug("Ent Value $i (\$" . ($i+1) . "): " . ${$args{entvarname}}[$i] . "=" . ${$args{entvar}}[$i]); } } @@ -660,7 +660,7 @@ sub translate_symbolic_to_oid if ($config->{net_snmp_perl_enable} == 1) { my $temp3 = SNMP::translateObj("$temp",0); if (defined ($temp3) ) { - $args{logger}->writeLogDebug(" Translated to $temp3"); + $logger->writeLogDebug(" Translated to $temp3"); $temp = $temp3; } else { # Could not translate default to numeric From 3565ab314c2ab29e87e6abcdf2e1171f1a50544a Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 22 Mar 2013 17:03:03 +0100 Subject: [PATCH 021/458] Finish first check --- .../lib/perl/centreon/script/centreontrapd.pm | 35 ++++++++++--------- centreon/lib/perl/centreon/trapd/lib.pm | 16 ++++----- 2 files changed, 27 insertions(+), 24 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 693a7aa621d..02790447be2 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -1,5 +1,5 @@ -package centreon::script::trapd; +package centreon::script::centreontrapd; use strict; use warnings; @@ -36,7 +36,7 @@ sub new { dns_enable => 0, separator => ' ', strip_domain => 0, - strip_domain_list => (), + strip_domain_list => [], duplicate_trap_window => 1, date_format => "", time_format => "", @@ -70,7 +70,7 @@ sub new { $self->{trap_time} = undef; $self->{trap_date_time} = undef; $self->{trap_date_time_epoch} = undef; - %{$self->{duplicate_traps}} = undef; + %{$self->{duplicate_traps}} = (); $self->{timetoreload} = 0; $self->{timetodie} = 0; @{$self->{filenames}} = undef; @@ -80,8 +80,10 @@ sub new { $self->{cmdFile} = undef; + # redefine to avoid out when we try modules + $SIG{__DIE__} = undef; # Daemon Only - if ($self->{centreontrapd_config}->{daemon} == 0) { + if ($self->{centreontrapd_config}->{daemon} == 1) { $self->set_signal_handlers; } return $self; @@ -90,6 +92,7 @@ sub new { sub set_signal_handlers { my $self = shift; + $SIG{TERM} = \&class_handle_TERM; $handlers{TERM}->{$self} = sub { $self->handle_TERM() }; $SIG{HUP} = \&class_handle_HUP; @@ -363,7 +366,7 @@ sub checkMatchingRules($$$$$$$$$) { my ($trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status) = @_; # Check matching options - my ($status, $sth) = $self->{cdb}->query("SELECT tmo_regexp, tmo_status, tmo_string FROM traps_matching_properties WHERE trap_id = '".$trap_id."' ORDER BY tmo_order"); + my ($dstatus, $sth) = $self->{cdb}->query("SELECT tmo_regexp, tmo_status, tmo_string FROM traps_matching_properties WHERE trap_id = '".$trap_id."' ORDER BY tmo_order"); while (my ($regexp, $tmoStatus, $tmoString) = $sth->fetchrow_array()) { $self->{logger}->writeLogDebug("[$tmoString][$regexp] => $tmoStatus"); @@ -469,7 +472,7 @@ sub getTrapsInfos($$$) { my %host = $self->get_hostinfos($ip, $hostname); foreach my $host_id (keys %host) { my $this_host = $host{$host_id}; - my ($trap_id, $status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, $ref_servicename) = getServiceInformations($oid, $host_id); + my ($trap_id, $status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, $ref_servicename) = $self->getServiceInformations($oid, $host_id); if (!defined($trap_id)) { return ; } @@ -523,7 +526,7 @@ sub run { $self->{centreontrapd_config}->{time_format}); centreon::trapd::lib::init_modules(logger => $self->{logger}, config => $self->{centreontrapd_config}, htmlentities => \$self->{htmlentities}); - $self->{logger}->writeLogDebug("centrapmaanger launched...."); + $self->{logger}->writeLogDebug("centreontrapd launched...."); $self->{logger}->writeLogDebug("PID: $$"); $self->{cdb} = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, @@ -533,7 +536,7 @@ sub run { password => $self->{centreon_config}->{db_passwd}, force => 0, logger => $self->{logger}); - if ($self->{centreon_config}->{mode} == 0) { + if ($self->{centreontrapd_config}->{mode} == 0) { $self->{cmdFile} = $self->{centreon_config}->{cmdFile}; } else { # Dirty!!! Need to know the poller @@ -552,11 +555,11 @@ sub run { filenames => \@{$self->{filenames}}))) { $self->{logger}->writeLogDebug("Processing file: $file"); - if (open FILE, $self->{spool_directory} . $file) { + if (open FILE, $self->{centreontrapd_config}->{spool_directory} . $file) { my $trap_is_a_duplicate = 0; my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, config => $self->{centreontrapd_config}, - handle => 'FILE', + handle => \*FILE, agent_dns => \$self->{agent_dns}, trap_date => \$self->{trap_date}, trap_time => \$self->{trap_time}, @@ -564,8 +567,8 @@ sub run { trap_date_time_epoch => \$self->{trap_date_time_epoch}, duplicate_traps => \%{$self->{duplicate_traps}}, var => \@{$self->{var}}, - entvar => \%{$self->{entvar}}, - entvarname => \%{$self->{entvarname}}); + entvar => \@{$self->{entvar}}, + entvarname => \@{$self->{entvarname}}); if ($readtrap_result == 1) { if (centreon::trapd::lib::check_known_trap(logger => $self->{logger}, @@ -588,7 +591,7 @@ sub run { $self->{logger}->writeLogError("Unable to delete trap file $file from spool dir:$!"); } } else { - $self->{logger}->writeLogError("Could not open trap file $spool_directory$file: ($!)"); + $self->{logger}->writeLogError("Could not open trap file " . $self->{centreontrapd_config}->{spool_directory} . "$file: ($!)"); } } @@ -609,7 +612,7 @@ sub run { } else { my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, config => $self->{centreontrapd_config}, - handle => 'STDIN', + handle => \*STDIN, agent_dns => \$self->{agent_dns}, trap_date => \$self->{trap_date}, trap_time => \$self->{trap_time}, @@ -617,8 +620,8 @@ sub run { trap_date_time_epoch => \$self->{trap_date_time_epoch}, duplicate_traps => \%{$self->{duplicate_traps}}, var => \@{$self->{var}}, - entvar => \%{$self->{entvar}}, - entvarname => \%{$self->{entvarname}}); + entvar => \@{$self->{entvar}}, + entvarname => \@{$self->{entvarname}}); if ($readtrap_result == 1) { if (centreon::trapd::lib::check_known_trap(logger => $self->{logger}, config => $self->{centreontrapd_config}, diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 4eb15c1ccbb..aa75f53a326 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -114,7 +114,7 @@ sub write_cache_file { $args{logger}->writeLogError("Go to DB to get info"); return 1; } - my $oids_value = join("\n", keys %{$args{oids_cache}}); + my $oids_value = join("\n", keys %{${$args{oids_cache}}}); print FILECACHE $oids_value; close FILECACHE; $args{logger}->writeLogInfo("Cache file refreshed"); @@ -242,9 +242,9 @@ sub purge_duplicate_trap { # Purge traps older than duplicate_trap_window in %duplicate_traps my $duplicate_traps_current_time = time(); foreach my $key (sort keys %{$args{duplicate_traps}}) { - if (${args{duplicate_traps}}{$key} < $duplicate_traps_current_time - $args{config}->{duplicate_trap_window}) { + if ($args{duplicate_traps}->{$key} < $duplicate_traps_current_time - $args{config}->{duplicate_trap_window}) { # Purge the record - delete ${args{duplicate_traps}}{$key}; + delete $args{duplicate_traps}->{$key}; } } } @@ -280,7 +280,7 @@ sub readtrap { chomp(${$args{trap_date_time_epoch}} = (<$input>)); # Pull time trap was spooled push(@rawtrap, ${$args{trap_date_time_epoch}}); if (${$args{trap_date_time_epoch}} eq "") { - if ($args{logger}->isDebug()) { + if ($args{logger}->is_debug()) { $args{logger}->writeLogDebug(" Invalid trap file. Expected a serial time on the first line but got nothing"); return 0; } @@ -317,7 +317,7 @@ sub readtrap { push(@rawtrap, $tempvar[0]); $tempvar[0] =~ s(`)(')g; #` Replace any back ticks with regular single quote if ($tempvar[0] eq "") { - if ($args{logger}->isDebug()) { + if ($args{logger}->is_debug()) { $args{logger}->writeLogDebug(" Invalid trap file. Expected a hostname on line 2 but got nothing"); return 0; } @@ -327,7 +327,7 @@ sub readtrap { push(@rawtrap, $tempvar[1]); $tempvar[1] =~ s(`)(')g; #` Replace any back ticks with regular single quote if ($tempvar[1] eq "") { - if ($args{logger}->isDebug()) { + if ($args{logger}->is_debug()) { $args{logger}->writeLogDebug(" Invalid trap file. Expected an IP address on line 3 but got nothing"); return 0; } @@ -462,7 +462,7 @@ sub readtrap { $linenum++; } - if ($args{logger}->isDebug()) { + if ($args{logger}->is_debug()) { # Print out raw trap passed from snmptrapd $args{logger}->writeLogDebug("Raw trap passed from snmptrapd:"); for (my $i=0;$i <= $#rawtrap;$i++) { @@ -571,7 +571,7 @@ sub readtrap { $args{logger}->writeLogDebug("Trap received from $tempvar[0]: $tempvar[5]"); - if ($args{logger}->isDebug()) { + if ($args{logger}->is_debug()) { $args{logger}->writeLogDebug("0: hostname"); $args{logger}->writeLogDebug("1: ip address"); $args{logger}->writeLogDebug("2: uptime"); From 174bdcb075fd88e9aad363b076b3822854ac897d Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 25 Mar 2013 17:48:14 +0100 Subject: [PATCH 022/458] Add a command to test traps --- .../centreon/script/centreon_trap_send.pm | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 centreon/lib/perl/centreon/script/centreon_trap_send.pm diff --git a/centreon/lib/perl/centreon/script/centreon_trap_send.pm b/centreon/lib/perl/centreon/script/centreon_trap_send.pm new file mode 100644 index 00000000000..7aeec6a0255 --- /dev/null +++ b/centreon/lib/perl/centreon/script/centreon_trap_send.pm @@ -0,0 +1,71 @@ +package centreon::script::centreon_trap_send; + +use strict; +use warnings; +use Net::SNMP; +use centreon::script; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("centreon_trap_send", + centreon_db_conn => 0, + centstorage_db_conn => 0 + ); + + bless $self, $class; + $self->{opt_d} = 'localhost'; + $self->{opt_snmpcommunity} = 'public'; + $self->{opt_snmpversion} = 'snmpv2c'; + $self->{opt_snmpport} = 162; + $self->{opt_oidtrap} = '.1.3.6.1.4.1.12182.1'; + @{$self->{opt_args}} = ('.1.3.6.1.4.1.12182.2.1:OCTET_STRING:Test "20"', '.1.3.6.1.4.1.12182.2.1:INTEGER:10', '.1.3.6.1.4.1.12182.2.1:COUNTER:100'); + $self->add_options( + "d=s" => \$self->{opt_d}, "destination=s" => \$self->{opt_d}, + "c=s" => \$self->{opt_snmpcommunity}, "community=s" => \$self->{opt_snmpcommunity}, + "o=s" => \$self->{opt_oidtrap}, "oid=s" => \$self->{opt_oidtrap}, + "snmpport=i" => \$self->{opt_snmpport}, + "snmpversion=s" => \$self->{opt_snmpversion}, + "a=s" => \@{$self->{opt_args}}, "arg=s" => \@{$self->{opt_args}} + ); + $self->{timestamp} = time(); + return $self; +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + my ($snmp_session, $error) = Net::SNMP->session(-hostname => $self->{opt_d}, + -community => $self->{opt_snmpcommunity}, + -port => $self->{opt_snmpport}, + -version => $self->{opt_snmpversion}); + if (!defined($snmp_session)) { + $self->{logger}->writeLogError("UNKNOWN: SNMP Session : $error"); + die("Quit"); + } + + my @oid_value = (); + foreach (@{$self->{opt_args}}) { + my ($oid, $type, $value) = split /:/, $_; + my $result; + my $ltmp = "\$result = Net::SNMP::$type;"; + eval $ltmp; + push @oid_value,($oid, $result, $value); + } + unshift @oid_value,('1.3.6.1.6.3.1.1.4.1.0', OBJECT_IDENTIFIER, $self->{opt_oidtrap}); + unshift @oid_value,('1.3.6.1.2.1.1.3.0', TIMETICKS, $self->{timestamp}); + $snmp_session->snmpv2_trap(-varbindlist => \@oid_value); + $snmp_session->close(); +} + +1; + +__END__ + +=head1 NAME + + sample - Using GetOpt::Long and Pod::Usage + +=cut From 3cf79d35b2ec05c17a582402f03f7609501da82c Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 31 May 2013 17:13:43 +0200 Subject: [PATCH 023/458] Improved lock system. We now store the PID of each process to check for dead operations. Conflicts: www/install/sql/centreon/Update-DB-2.4.x_to_2.5.x.sql --- centreon/lib/perl/centreon/common/lock.pm | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/centreon/lib/perl/centreon/common/lock.pm b/centreon/lib/perl/centreon/common/lock.pm index c5b8a3595ac..86a7a804fdd 100644 --- a/centreon/lib/perl/centreon/common/lock.pm +++ b/centreon/lib/perl/centreon/common/lock.pm @@ -4,8 +4,8 @@ use strict; use warnings; sub new { - my ($class, $name, %options) = @_; - my %defaults = (name => $name, timeout => 10); + my ($class, $name, $pid, %options) = @_; + my %defaults = (name => $name, pid => $pid, timeout => 10); my $self = {%defaults, %options}; bless $self, $class; @@ -33,7 +33,7 @@ sub new { my $class = shift; my $self = $class->SUPER::new(@_); - if (!defined $self->{pid} || !defined $self->{storagedir}) { + if (!defined $self->{storagedir}) { die "Can't build lock, required arguments not provided"; } bless $self, $class; @@ -81,7 +81,7 @@ sub new { sub is_set { my $self = shift; my ($status, $sth) = $self->{dbc}->query( - "SELECT id,running,time_launch FROM cron_operation WHERE name LIKE '$self->{name}'" + "SELECT id,running,pid,time_launch FROM cron_operation WHERE name LIKE '$self->{name}'" ); my $data = $sth->fetchrow_hashref(); @@ -91,8 +91,11 @@ sub is_set { return 0; } $self->{id} = $data->{id}; + $self->{pid} = $data->{pid}; $self->{previous_launch_time} = $data->{time_launch}; if (defined $data->{running} && $data->{running} == 1) { + my $line = `ps -ef | grep -v grep | grep $self->{pid} | grep $self->{name}`; + return 0 if !length $line; return 1; } return 0; @@ -115,7 +118,7 @@ EOQ } $status = $self->{dbc}->do(<<"EOQ"); UPDATE cron_operation -SET running = '1', time_launch = '$self->{launch_time}' +SET running = '1', time_launch = '$self->{launch_time}', pid = '$self->{pid}' WHERE id = '$self->{id}' EOQ goto error if $status == -1; @@ -132,7 +135,7 @@ sub DESTROY { my $exectime = time() - $self->{launch_time}; $self->{dbc}->do(<<"EOQ"); UPDATE cron_operation -SET running = '0', last_execution_time = '$exectime' +SET running = '0', last_execution_time = '$exectime', pid = '-1' WHERE id = '$self->{id}' EOQ } From db4f6269cf1f1622979cb9a3cb42268e99f69124 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 28 Mar 2013 13:56:11 +0100 Subject: [PATCH 024/458] Add noconfig --- centreon/lib/perl/centreon/script.pm | 9 ++++++--- centreon/lib/perl/centreon/script/centreon_trap_send.pm | 3 ++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/centreon/script.pm b/centreon/lib/perl/centreon/script.pm index 31d068ebe5f..60460178d5b 100644 --- a/centreon/lib/perl/centreon/script.pm +++ b/centreon/lib/perl/centreon/script.pm @@ -25,7 +25,8 @@ sub new { log_file => undef, centreon_db_conn => 0, centstorage_db_conn => 0, - severity => "info" + severity => "info", + noconfig => 0 ); my $self = {%defaults, %options}; @@ -92,8 +93,10 @@ sub parse_options { Getopt::Long::Configure('bundling'); die "Command line error" if !GetOptions(%{$self->{options}}); pod2usage(-exitval => 1, -input => $FindBin::Bin . "/" . $FindBin::Script) if $self->{help}; - require $self->{config_file}; - $self->{centreon_config} = $centreon_config; + if ($self->{noconfig} == 0) ( + require $self->{config_file}; + $self->{centreon_config} = $centreon_config; + } } sub run { diff --git a/centreon/lib/perl/centreon/script/centreon_trap_send.pm b/centreon/lib/perl/centreon/script/centreon_trap_send.pm index 7aeec6a0255..65f5d29bda5 100644 --- a/centreon/lib/perl/centreon/script/centreon_trap_send.pm +++ b/centreon/lib/perl/centreon/script/centreon_trap_send.pm @@ -11,7 +11,8 @@ sub new { my $class = shift; my $self = $class->SUPER::new("centreon_trap_send", centreon_db_conn => 0, - centstorage_db_conn => 0 + centstorage_db_conn => 0, + noconfig => 1 ); bless $self, $class; From a7f78b6e4511f352d6b9495f3c46322026dd285b Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 28 Mar 2013 14:03:51 +0100 Subject: [PATCH 025/458] Fix typo error --- centreon/lib/perl/centreon/script.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script.pm b/centreon/lib/perl/centreon/script.pm index 60460178d5b..ab584bb9a73 100644 --- a/centreon/lib/perl/centreon/script.pm +++ b/centreon/lib/perl/centreon/script.pm @@ -93,7 +93,7 @@ sub parse_options { Getopt::Long::Configure('bundling'); die "Command line error" if !GetOptions(%{$self->{options}}); pod2usage(-exitval => 1, -input => $FindBin::Bin . "/" . $FindBin::Script) if $self->{help}; - if ($self->{noconfig} == 0) ( + if ($self->{noconfig} == 0) { require $self->{config_file}; $self->{centreon_config} = $centreon_config; } From 1d2827a1435f70e1742fbbc69ba68a5c024dd5a8 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 28 Mar 2013 16:20:28 +0100 Subject: [PATCH 026/458] Add script to check perfdata --- .../centreon/centstorage/CentstoragePool.pm | 8 +- .../script/centreon_check_perfdata.pm | 81 +++++++++++++++++++ 2 files changed, 85 insertions(+), 4 deletions(-) create mode 100644 centreon/lib/perl/centreon/script/centreon_check_perfdata.pm diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index 136e6d9540c..bc1b3e083bd 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -545,14 +545,14 @@ sub get_perfdata { $perf_label = $self->parse_label(); if (!defined($perf_label) || $perf_label eq '') { $self->{"logger"}->writeLogError("Wrong perfdata format: " . $self->{'service_perfdata'}); - return 0 if ($self->{'perfdata_parser_stop'} == 1); + return -1 if ($self->{'perfdata_parser_stop'} == 1); return 1; } $perf_value = $self->parse_value(); if (!defined($perf_value) || $perf_value eq '') { $self->{"logger"}->writeLogError("Wrong perfdata format: " . $self->{'service_perfdata'}); - return 0 if ($self->{'perfdata_parser_stop'} == 1); + return -1 if ($self->{'perfdata_parser_stop'} == 1); return 1; } @@ -570,7 +570,7 @@ sub get_perfdata { $perf_label = $2; if (!defined($perf_label) || $perf_label eq '') { $self->{"logger"}->writeLogError("Wrong perfdata format: " . $self->{'service_perfdata'}); - return 0 if ($self->{'perfdata_parser_stop'} == 1); + return -1 if ($self->{'perfdata_parser_stop'} == 1); return 1; } } @@ -807,7 +807,7 @@ sub update { } $self->init_perfdata(); - while (($self->get_perfdata())) { + while (($self->get_perfdata()) > 0) { if (!defined($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}})) { # Need to identify metrics # if failed, we go 'next' diff --git a/centreon/lib/perl/centreon/script/centreon_check_perfdata.pm b/centreon/lib/perl/centreon/script/centreon_check_perfdata.pm new file mode 100644 index 00000000000..82ff19607e3 --- /dev/null +++ b/centreon/lib/perl/centreon/script/centreon_check_perfdata.pm @@ -0,0 +1,81 @@ +package centreon::script::centreon_check_perfdata; + +use strict; +use warnings; +use centreon::common::db; +use centreon::centstorage::CentstoragePool; +use centreon::script; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("centreon_check_perfdata", + centreon_db_conn => 0, + centstorage_db_conn => 0, + noconfig => 0 + ); + + bless $self, $class; + return $self; +} + +sub run { + my $self = shift; + my ($status, $sth, $row); + + $self->SUPER::run(); + my $centreon_db_centreon = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 0, + logger => $self->{logger}); + $status = $centreon_db_centreon->connect(); + die("Quit. Can't connect") if ($status == 1); + ($status, $sth, $row) = $centreon_db_centreon->query("SELECT db_name, db_host, db_port, db_user, db_pass FROM cfg_ndo2db WHERE activate = '1' LIMIT 1"); + die("Quit") if ($status == -1); + if (!($row = $sth->fetchrow_hashref())) { + $self->{logger}->writeLogError("Can't get ndo connection information (maybe you are using centreon-broker)"); + die("Quit"); + } + my $centstatus = centreon::common::db->new(db => $row->{db_name}, + host => $row->{db_host}, + port => $row->{db_port}, + user => $row->{db_user}, + password => $row->{db_pass}, + force => 0, + logger => $self->{logger}); + $status = $centstatus->connect(); + die("Quit. Can't connect to centreon_status database") if ($status == 1); + ($status, $sth, $row) = $centstatus->query("SELECT no.name1, no.name2, ns.perfdata FROM nagios_objects no, nagios_servicestatus ns WHERE no.is_active = 1 AND no.name2 IS NOT NULL AND no.object_id = ns.service_object_id"); + die("Quit") if ($status == -1); + my $centstorage_pool = centreon::centstorage::CentstoragePool->new($self->{logger}); + $centstorage_pool->{'perfdata_parser_stop'} = 1; + while (($row = $sth->fetchrow_hashref())) { + $centstorage_pool->{'service_perfdata'} = $row->{'perfdata'}; + $centstorage_pool->init_perfdata(); + my $space_in_name = 0; + + while (($status = $centstorage_pool->get_perfdata()) > 0) { + $space_in_name = 1 if ($centstorage_pool->{"metric_name"} =~ /\s/); + } + if ($status == -1) { + $self->{logger}->writeLogError("Check service " . $row->{name1} . "/" . $row->{name2}); + } + if ($space_in_name == 1) { + $self->{logger}->writeLogInfo("You have metric name with space: " . $row->{name1} . "/" . $row->{name2} . ". You have to delete character quote in 'Illegal Macro Output Characters' attribute."); + } + } +} + +1; + +__END__ + +=head1 NAME + + sample - Using GetOpt::Long and Pod::Usage + +=cut From 41eb5bd1648440ed56d11f22812d9f79b96fb8d2 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 28 Mar 2013 16:36:10 +0100 Subject: [PATCH 027/458] Fix meta_service/bam create in index_data --- .../lib/perl/centreon/centstorage/CentstoragePool.pm | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index bc1b3e083bd..487293d9dab 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -634,10 +634,12 @@ sub get_host_service_ids { my ($host_id, $service_id); my ($status, $stmt, $data); my $host_register = 1; + my $service_register = "'1', '3'"; # For Modules if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { $host_register = 2; + $service_register = "'2'"; } # Get Host_Id ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT `host_id` FROM `host` WHERE `host_name` = " . $self->{'dbcentreon'}->quote($host_name) . " AND `host_register` = '$host_register' LIMIT 1"); @@ -649,18 +651,13 @@ sub get_host_service_ids { } $host_id = $data->{'host_id'}; - # For 'BAM' module: in 'host' and 'service' table but there is no relations - # For 'meta' module: in 'host' and 'meta_service_relation' (we can't purge) - if ($host_register == 2) { - return (0, $host_id, undef); - } - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM service, host_service_relation hsr WHERE hsr.host_host_id = '" . $host_id . "' AND hsr.service_service_id = service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN ('1', '3') LIMIT 1"); + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM service, host_service_relation hsr WHERE hsr.host_host_id = '" . $host_id . "' AND hsr.service_service_id = service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN (" . $service_register . ") LIMIT 1"); return -1 if ($status == -1); $data = $stmt->fetchrow_hashref(); if (!defined($data)) { # Search in service By hostgroup - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM hostgroup_relation hgr, service, host_service_relation hsr WHERE hgr.host_host_id = '" . $host_id . "' AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id AND service_id = hsr.service_service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN ('1', '3') LIMIT 1"); + ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM hostgroup_relation hgr, service, host_service_relation hsr WHERE hgr.host_host_id = '" . $host_id . "' AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id AND service_id = hsr.service_service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN (" . $service_register . ") LIMIT 1"); return -1 if ($status == -1); $data = $stmt->fetchrow_hashref(); } From a34f74c43eeee7c6a24817a2ed3acf0671c2ea00 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 2 Apr 2013 16:04:33 +0200 Subject: [PATCH 028/458] Migrate nagiosPerfTrace --- .../centreon/centstorage/CentstoragePool.pm | 24 +- .../perl/centreon/script/nagiosPerfTrace.pm | 394 ++++++++++++++++++ 2 files changed, 409 insertions(+), 9 deletions(-) create mode 100644 centreon/lib/perl/centreon/script/nagiosPerfTrace.pm diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index 487293d9dab..129bbcd0533 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -19,6 +19,9 @@ sub new { $self->{"dbcentreon"} = undef; $self->{"dbcentstorage"} = undef; + # skip if we don't find IDS in config + $self->{"skip_if_no_ids"} = 1; + $self->{"len_storage_rrd"} = undef; $self->{"rrd_metrics_path"} = undef; $self->{"rrd_status_path"} = undef; @@ -188,16 +191,16 @@ sub handle_CHLD { if ($self->{"rename_rebuild_wait"} == 1) { my ($new_host_name, $new_service_description) = split(';', $self->{"rename_old_new"}->{$self->{"rebuild_key"}}); $self->force_flush_rrd($self->{"rebuild_key"}); - delete $self->{"cache_service"}->{$self->{"rebuild_key"}}; - delete $self->{"cache_services_failed"}->{$self->{"rebuild_key"}}; + delete $self->{"cache_service"}->{$self->{"rebuild_key"}}; + delete $self->{"cache_services_failed"}->{$self->{"rebuild_key"}}; delete $self->{"rename_old_new"}->{$self->{"rebuild_key"}}; - $self->send_rename_finish($new_host_name, $new_service_description); + $self->send_rename_finish($new_host_name, $new_service_description); } $self->rebuild_finish(); - while (($child_pid = waitpid(-1, &POSIX::WNOHANG)) > 0) { - $exit_code = $? >> 8; - } - $SIG{CHLD} = \&class_handle_CHLD; + while (($child_pid = waitpid(-1, &POSIX::WNOHANG)) > 0) { + $exit_code = $? >> 8; + } + $SIG{CHLD} = \&class_handle_CHLD; } sub class_handle_TERM { @@ -647,7 +650,7 @@ sub get_host_service_ids { $data = $stmt->fetchrow_hashref(); if (!defined($data)) { $self->{'logger'}->writeLogError("Can't find 'host_id' $host_name"); - return -1; + return -2; } $host_id = $data->{'host_id'}; @@ -664,7 +667,7 @@ sub get_host_service_ids { if (!defined($data)) { $self->{'logger'}->writeLogError("Can't find 'service_id' for $host_name/$service_description"); - return -1; + return -2; } $service_id = $data->{'service_id'}; @@ -739,6 +742,9 @@ sub get_information_service { # Need to identify it my ($status, $host_id, $service_id) = $self->get_host_service_ids($host_name, $service_description); if ($status != 0) { + if ($status == -2 && $self->{"skip_if_no_ids"} == 1) { + return 1; + } if (!defined($no_cache) || $no_cache == 0) { push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; } diff --git a/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm b/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm new file mode 100644 index 00000000000..47889b2de29 --- /dev/null +++ b/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm @@ -0,0 +1,394 @@ + +package centreon::script::NagiosPerfTrace; + +use strict; +use warnings; +use RRDs; +use File::Path qw(mkpath); +use centreon::script; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("logAnalyser", + centreon_db_conn => 1, + centstorage_db_conn => 1 + ); + + bless $self, $class; + $self->{sshOptions} = "-o ConnectTimeout=5 -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; + $self->{interval} = 300; + $self->{heartbeatFactor} = 10; + $self->{heartbeat} = $self->{interval} * $self->{heartbeatFactor}; + $self->{number} = undef; + + $self->{global_cmd_buffer} = undef; + $self->{global_active_service_latency} = undef; + $self->{global_active_service_execution} = undef; + $self->{global_active_service_last} = undef; + $self->{global_services_states} = undef; + $self->{global_active_host_latency} = undef; + $self->{global_active_host_execution} = undef; + $self->{global_active_host_last} = undef; + $self->{global_hosts_states} = undef; + return $self; +} + +sub trim($) { + my $string = shift; + $string =~ s/^\s+//; + $string =~ s/\s+$//; + return $string; +} + +sub rrd_process { + my $self = shift; + my($str, $is_localhost, $must_update_ds, $ns_id) = @_; + my @tab; + my $match; + my $j; + my $error; + my $query_str; + + $str =~ s/\n/:/g; + @tab = split(/:/, $str); + #chomp(@tab); + $j = 0; + + $query_str = ""; + foreach $match (@tab) { + if ($match =~ /Used\/High\/Total Command Buffers/) { + $tab[$j+1] = trim($tab[$j+1]); + $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)/; + + if (!-e $self->{global_cmd_buffer}) { + RRDs::create($self->{global_cmd_buffer}, "-s $self->{interval}", "DS:In_Use:GAUGE:$self->{interval}:0:U", "DS:Max_Used:GAUGE:$self->{interval}:0:U", "DS:Total_Available:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$self->{number}, "RRA:AVERAGE:0.5:12:".$self->{number}); + RRDs::tune($self->{global_cmd_buffer}, "-h", "In_Use:$self->{heartbeat}"); + RRDs::tune($self->{global_cmd_buffer}, "-h", "Max_Used:$self->{heartbeat}"); + RRDs::tune($self->{global_cmd_buffer}, "-h", "Total_Available:$self->{heartbeat}"); + } + RRDs::update ($self->{global_cmd_buffer}, "--template", "In_Use:Max_Used:Total_Available", "N:".$1.":".$2.":".$3); + if (RRDs::error()) { + $error = RRDs::error() + $self->{logger}->writeLogError($error); + } + + if ($query_str ne "") { + $query_str .= ", "; + } + $query_str .= "('$ns_id', 'Buffer Usage', 'In_Use', '$1'), "; + $query_str .= "('$ns_id', 'Buffer Usage', 'Max_Used', '$2'), "; + $query_str .= "('$ns_id', 'Buffer Usage', 'Total_Available', '$3') "; + } elsif ($match =~ /Active Service Latency/) { + $tab[$j+1] = trim($tab[$j+1]); + $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ [sec|%]/; + if (!-e $self->{global_active_service_latency}) { + RRDs::create ($self->{global_active_service_latency}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::tune($self->{global_active_service_latency}, "-h", "Min:$self->{heartbeat}"); + RRDs::tune($self->{global_active_service_latency}, "-h", "Max:$self->{heartbeat}"); + RRDs::tune($self->{global_active_service_latency}, "-h", "Average:$self->{heartbeat}"); + } + RRDs::update ($self->{global_active_service_latency}, "--template", "Min:Max:Average", "N:".$1.":".$2.":".$3); + if (RRDs::error()) { + $error = RRDs::error() + $self->{logger}->writeLogError($error); + } + + if ($query_str ne "") { + $query_str .= ", "; + } + $query_str .= "('$ns_id', 'Service Check Latency', 'Min', '$1'), "; + $query_str .= "('$ns_id', 'Service Check Latency', 'Max', '$2'), "; + $query_str .= "('$ns_id', 'Service Check Latency', 'Average', '$3') "; + } elsif ($match =~ /Active Service Execution Time/){ + $tab[$j+1] = trim($tab[$j+1]); + $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ sec/; + if (! -e $self->{global_active_service_execution}) { + RRDs::create ($self->{global_active_service_execution}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::tune($self->{global_active_service_execution}, "-h", "Min:$self->{heartbeat}"); + RRDs::tune($self->{global_active_service_execution}, "-h", "Max:$self->{heartbeat}"); + RRDs::tune($self->{global_active_service_execution}, "-h", "Average:$self->{heartbeat}"); + } + RRDs::update ($self->{global_active_service_execution}, "--template", "Min:Max:Average", "N:".$1.":".$2.":".$3); + if (RRDs::error()) { + $error = RRDs::error() + $self->{logger}->writeLogError($error); + } + + if ($query_str ne "") { + $query_str .= ", "; + } + $query_str .= "('$ns_id', 'Service Check Execution Time', 'Min', '$1'), "; + $query_str .= "('$ns_id', 'Service Check Execution Time', 'Max', '$2'), "; + $query_str .= "('$ns_id', 'Service Check Execution Time', 'Average', '$3') "; + + } elsif ($match =~ /Active Services Last 1\/5\/15\/60 min/){ + $tab[$j+1] = trim($tab[$j+1]); + $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)/; + if (!-e $self->{global_active_service_last}) { + RRDs::create ($self->{global_active_service_last}, "-s $self->{interval}", "DS:Last_Min:GAUGE:$self->{interval}:0:U", "DS:Last_5_Min:GAUGE:$self->{interval}:0:U", "DS:Last_15_Min:GAUGE:$self->{interval}:0:U", "DS:Last_Hour:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::tune($self->{global_active_service_last}, "-h", "Last_Min:$self->{heartbeat}"); + RRDs::tune($self->{global_active_service_last}, "-h", "Last_5_Min:$self->{heartbeat}"); + RRDs::tune($self->{global_active_service_last}, "-h", "Last_15_Min:$self->{heartbeat}"); + RRDs::tune($self->{global_active_service_last}, "-h", "Last_Hour:$self->{heartbeat}"); + } + RRDs::update ($self->{global_active_service_last}, "--template", "Last_Min:Last_5_Min:Last_15_Min:Last_Hour", "N:".$1.":".$2.":".$3.":".$4); + if (RRDs::error()) { + $error = RRDs::error() + $self->{logger}->writeLogError($error); + } + + if ($query_str ne "") { + $query_str .= ", "; + } + $query_str .= "('$ns_id', 'Service Actively Checked', 'Last_minute', '$1'), "; + $query_str .= "('$ns_id', 'Service Actively Checked', 'Last_5_minutes', '$2'), "; + $query_str .= "('$ns_id', 'Service Actively Checked', 'Last_15_minutes', '$3'), "; + $query_str .= "('$ns_id', 'Service Actively Checked', 'Last_hour', '$4')"; + + } elsif ($match =~ /Services Ok\/Warn\/Unk\/Crit/) { + $tab[$j+1] = trim($tab[$j+1]); + $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)/; + if (! -e $self->{global_services_states) { + RRDs::create ($self->{global_services_states}, "-s $self->{interval}", "DS:Ok:GAUGE:$self->{interval}:0:U", "DS:Warn:GAUGE:$self->{interval}:0:U", "DS:Unk:GAUGE:$self->{interval}:0:U", "DS:Crit:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::tune($self->{global_services_states}, "-h", "Ok:$self->{heartbeat}"); + RRDs::tune($self->{global_services_states}, "-h", "Warn:$self->{heartbeat}"); + RRDs::tune($self->{global_services_states}, "-h", "Unk:$self->{heartbeat}"); + RRDs::tune($self->{global_services_states}, "-h", "Crit:$self->{heartbeat}"); + } + RRDs::update ($self->{global_services_states}, "--template", "Ok:Warn:Unk:Crit", "N:".$1.":".$2.":".$3.":".$4); + if (RRDs::error()) { + $error = RRDs::error() + $self->{logger}->writeLogError($error); + } + + if ($query_str ne "") { + $query_str .= ", "; + } + $query_str .= "('$ns_id', 'Services Status', 'OK', '$1'), "; + $query_str .= "('$ns_id', 'Services Status', 'Warning', '$2'), "; + $query_str .= "('$ns_id', 'Services Status', 'Unknown', '$3'), "; + $query_str .= "('$ns_id', 'Services Status', 'Critical', '$4')"; + + } elsif($match =~ /Active Host Latency/){ + $tab[$j+1] = trim($tab[$j+1]); + $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ [sec|%]/; + if (! -e $self->{global_active_host_latency}) { + RRDs::create ($self->{global_active_host_latency}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::tune($self->{global_active_host_latency}, "-h", "Min:$self->{heartbeat}"); + RRDs::tune($self->{global_active_host_latency}, "-h", "Max:$self->{heartbeat}"); + RRDs::tune($self->{global_active_host_latency}, "-h", "Average:$self->{heartbeat}"); + } + RRDs::update ($self->{global_active_host_latency}, "--template", "Min:Max:Average", "N:".$1.":".$2.":".$3); + if (RRDs::error()) { + $error = RRDs::error() + $self->{logger}->writeLogError($error); + } + + if ($query_str ne "") { + $query_str .= ", "; + } + $query_str .= "('$ns_id', 'Host Check Latency', 'Min', '$1'), "; + $query_str .= "('$ns_id', 'Host Check Latency', 'Max', '$2'), "; + $query_str .= "('$ns_id', 'Host Check Latency', 'Average', '$3')"; + + } elsif ($match =~ /Active Host Execution Time/){ + $tab[$j+1] = trim($tab[$j+1]); + $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ sec/; + if (! -e $self->{global_active_host_execution}) { + RRDs::create ($self->{global_active_host_execution}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::tune($self->{global_active_host_execution}, "-h", "Min:$self->{heartbeat}"); + RRDs::tune($self->{global_active_host_execution}, "-h", "Max:$self->{heartbeat}"); + RRDs::tune($self->{global_active_host_execution}, "-h", "Average:$self->{heartbeat}"); + } + RRDs::update ($self->{global_active_host_execution}, "--template", "Min:Max:Average", "N:".$1.":".$2.":".$3); + if (RRDs::error()) { + $error = RRDs::error() + $self->{logger}->writeLogError($error); + } + + if ($query_str ne "") { + $query_str .= ", "; + } + $query_str .= "('$ns_id', 'Host Check Execution Time', 'Min', '$1'), "; + $query_str .= "('$ns_id', 'Host Check Execution Time', 'Max', '$2'), "; + $query_str .= "('$ns_id', 'Host Check Execution Time', 'Average', '$3')"; + + } elsif($match =~ /Active Hosts Last 1\/5\/15\/60 min/){ + $tab[$j+1] = trim($tab[$j+1]); + $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)/; + if (!-e $self->{global_active_host_last}) { + RRDs::create ($self->{global_active_host_last}, "-s $self->{interval}", "DS:Last_Min:GAUGE:$self->{interval}:0:U", "DS:Last_5_Min:GAUGE:$self->{interval}:0:U", "DS:Last_15_Min:GAUGE:$self->{interval}:0:U", "DS:Last_Hour:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::tune($self->{global_active_host_last}, "-h", "Last_Min:$self->{heartbeat}"); + RRDs::tune($self->{global_active_host_last}, "-h", "Last_5_Min:$self->{heartbeat}"); + RRDs::tune($self->{global_active_host_last}, "-h", "Last_15_Min:$self->{heartbeat}"); + RRDs::tune($self->{global_active_host_last}, "-h", "Last_Hour:$self->{heartbeat}"); + } + RRDs::update ($self->{global_active_host_last}, "--template", "Last_Min:Last_5_Min:Last_15_Min:Last_Hour", "N:".$1.":".$2.":".$3.":".$4); + if (RRDs::error()) { + $error = RRDs::error() + $self->{logger}->writeLogError($error); + } + + if ($query_str ne "") { + $query_str .= ", "; + } + $query_str .= "('$ns_id', 'Host Actively Checked', 'Last_minute', '$1'), "; + $query_str .= "('$ns_id', 'Host Actively Checked', 'Last_5_minutes', '$2'), "; + $query_str .= "('$ns_id', 'Host Actively Checked', 'Last_15_minutes', '$3'), "; + $query_str .= "('$ns_id', 'Host Actively Checked', 'Last_hour', '$4')"; + } elsif ($match =~ /Hosts Up\/Down\/Unreach/){ + $tab[$j+1] = trim($tab[$j+1]); + $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)/; + if (!-e $self->{global_hosts_states}) { + RRDs::create($self->{global_hosts_states}, "-s $self->{interval}", "DS:Up:GAUGE:$self->{interval}:0:U", "DS:Down:GAUGE:$self->{interval}:0:U", "DS:Unreach:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::tune($self->{global_hosts_states}, "-h", "Up:$self->{heartbeat}"); + RRDs::tune($self->{global_hosts_states}, "-h", "Down:$self->{heartbeat}"); + RRDs::tune($self->{global_hosts_states}, "-h", "Unreach:$self->{heartbeat}"); + } + RRDs::update ($self->{global_hosts_states}, "--template", "Up:Down:Unreach", "N:".$1.":".$2.":".$3); + if (RRDs::error()) { + $error = RRDs::error() + $self->{logger}->writeLogError($error); + } + + if ($query_str ne "") { + $query_str .= ", "; + } + $query_str .= "('$ns_id', 'Hosts Status', 'Up', '$1'), "; + $query_str .= "('$ns_id', 'Hosts Status', 'Down', '$2'), "; + $query_str .= "('$ns_id', 'Hosts Status', 'Unreachable', '$3')"; + } + $j++; + } + if (!$error && ($query_str ne "")) { + my ($status, $sth) = $self->{csdb}->query("DELETE FROM `nagios_stats` WHERE instance_id = '" . $ns_id . "'") + ($status, $sth) = $self->{csdb}->query("INSERT INTO `nagios_stats` (instance_id, stat_label, stat_key, stat_value) VALUES " . $query_str); + } +} + +sub check_dir { + my $self = shift; + my ($nagios_id) = @_; + + if (! -d $self->{global_prefix} . "perfmon-" . $nagios_id) { + if (mkpath($self->{global_prefix} . "perfmon-" . $nagios_id) == 0) { + $self->{logger}->writeLogError("Can't create directory '" . $self->{global_prefix} . "perfmon-" . $nagios_id . "': $!") + return 0; + } + } + + my $tmp_prefix = $self->{global_prefix} . "perfmon-" . $nagios_id; + $self->{global_cmd_buffer} = $tmp_prefix . "/nagios_cmd_buffer.rrd"; + $self->{global_active_service_latency} = $tmp_prefix . "/nagios_active_service_latency.rrd"; + $self->{global_active_service_execution} = $tmp_prefix . "/nagios_active_service_execution.rrd"; + $self->{global_active_service_last} = $tmp_prefix . "/nagios_active_service_last.rrd"; + $self->{global_services_states} = $tmp_prefix . "/nagios_services_states.rrd"; + $self->{global_active_host_latency} = $tmp_prefix . "/nagios_active_host_latency.rrd"; + $self->{global_active_host_execution} = $tmp_prefix . "/nagios_active_host_execution.rrd"; + $self->{global_active_host_last} = $tmp_prefix . "/nagios_active_host_last.rrd"; + $self->{global_hosts_states} = $tmp_prefix . "/nagios_hosts_states.rrd"; + return 1; +} + +sub get_poller { + my $self = shift; + my $id; + my $ip; + my $ssh_port; + my $is_localhost; + my $cfg_item; + my $cfg_result; + my $cfg_dir; + my $nagiostats; + my $must_update_ds; + my $dataDir = $self->{centreon_config}->{VarLib} . "/log/"; + + my ($status, $sth) = $self->{cdb}->query("SELECT id, ssh_port, ns_ip_address, localhost, nagiostats_bin FROM nagios_server WHERE ns_activate = 1"); + die("Quit") if ($status == -1); + while (($id, $ssh_port, $ip, $is_localhost, $nagiostats_bin) = $sth->fetchrow_array()) { + $must_update_ds = 0; + my ($status2, $sth2) = $self->{cdb}->query("SELECT cfg_dir, cfg_file FROM cfg_nagios WHERE nagios_server_id = " . $id . " AND nagios_activate = '1' LIMIT 1"); + die("Quit") if ($status2 == -1); + $cfg_result = $sth2->fetchrow_hashref(); + if (!defined($cfg_result->{cfg_dir})) { + $self->{logger}->writeLogError("Missing monitoring engine configuration file, skipping poller."); + next; + } + $cfg_dir = $cfg_result->{'cfg_dir'}; + $cfg_dir =~ s!/\$!!g; + if ($cfg_dir eq '') { + $self->{logger}->writeLogError("The Monitoring engine configuration dir is empty."); + next; + } elsif ($cfg_result->{'cfg_file'} eq '') { + $self->{logger}->writeLogError("The Monitoring engine configuration filename is empty."); + next; + } + + my $nagiostats_bin = ''; + + if ($is_localhost){ + $nagiostats = `$nagiostats_bin -c $cfg_dir/$cfg_result->{'cfg_file'}`; + } else { + if (-e $dataDir . "$id/nagiostats.trace.txt") { + if (!open(FILE, $dataDir . "$id/nagiostats.trace.txt")) { + $self->{logger}->writeLogError("Can't read '" . $dataDir . "$id/nagiostats.trace.txt' file: $!"); + next; + } + while () { + $nagiostats .= $_."\n"; + } + close(FILE); + unlink($dataDir . "$id/nagiostats.trace.txt"); + } else { + if (!defined($ssh_port) || !$ssh_port) { + $ssh_port = "22"; + } + $nagiostats = `ssh $self->{sshOptions} -p $ssh_port $ip $nagiostats_bin -c $cfg_dir/$cfg_result->{'cfg_file'}`; + } + } + if ($nagiosstats eq '' || $nagiostats =~ m/Error reading status file/ ) { + next; + } + if ($self->check_dir($id) == 1) { + # Update Database + $self->rrd_process($nagiostats, $is_localhost, $must_update_ds, $id); + } + } +} + +sub get_interval { + my $self = shift; + + my ($status, $sth) = $self->{csdb}->query("SELECT len_storage_rrd FROM config LIMIT 1"); + die("Quit") if ($status == -1); + my $data = $sth->fetchrow_hashref(); + if (defined($data->{'len_storage_rrd'})) { + $self->{number} = $data->{'len_storage_rrd'} * 24 * 60 * 60 / $self->{interval}; + } else { + $self->{number} = 365 * 24 * 60 * 60 / $self->{interval}; + } +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + $self->{global_prefix} = $self->{centreon_config}->{VarLib} . "/nagios-perf/"; + $self->get_interval(); + + if (! -d $self->{global_prefix}){ + die("Can't create directory '$self->{global_prefix}': $!") if (mkpath($self->{global_prefix}) == 0); + } + + $self->get_poller(); +} + +__END__ + +=head1 NAME + + sample - Using GetOpt::Long and Pod::Usage + +=cut From 176e27e7158402200c3cdd4d0e30c1c44c49dd25 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 2 Apr 2013 16:17:13 +0200 Subject: [PATCH 029/458] Fix typo errors --- .../perl/centreon/script/nagiosPerfTrace.pm | 50 ++++++++++--------- 1 file changed, 27 insertions(+), 23 deletions(-) diff --git a/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm b/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm index 47889b2de29..a0fba390f2f 100644 --- a/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm +++ b/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm @@ -70,7 +70,7 @@ sub rrd_process { } RRDs::update ($self->{global_cmd_buffer}, "--template", "In_Use:Max_Used:Total_Available", "N:".$1.":".$2.":".$3); if (RRDs::error()) { - $error = RRDs::error() + $error = RRDs::error(); $self->{logger}->writeLogError($error); } @@ -84,14 +84,14 @@ sub rrd_process { $tab[$j+1] = trim($tab[$j+1]); $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ [sec|%]/; if (!-e $self->{global_active_service_latency}) { - RRDs::create ($self->{global_active_service_latency}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::create ($self->{global_active_service_latency}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$self->{number}, "RRA:AVERAGE:0.5:12:".$self->{number}); RRDs::tune($self->{global_active_service_latency}, "-h", "Min:$self->{heartbeat}"); RRDs::tune($self->{global_active_service_latency}, "-h", "Max:$self->{heartbeat}"); RRDs::tune($self->{global_active_service_latency}, "-h", "Average:$self->{heartbeat}"); } RRDs::update ($self->{global_active_service_latency}, "--template", "Min:Max:Average", "N:".$1.":".$2.":".$3); if (RRDs::error()) { - $error = RRDs::error() + $error = RRDs::error(); $self->{logger}->writeLogError($error); } @@ -105,14 +105,14 @@ sub rrd_process { $tab[$j+1] = trim($tab[$j+1]); $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ sec/; if (! -e $self->{global_active_service_execution}) { - RRDs::create ($self->{global_active_service_execution}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::create ($self->{global_active_service_execution}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$self->{number}, "RRA:AVERAGE:0.5:12:".$self->{number}); RRDs::tune($self->{global_active_service_execution}, "-h", "Min:$self->{heartbeat}"); RRDs::tune($self->{global_active_service_execution}, "-h", "Max:$self->{heartbeat}"); RRDs::tune($self->{global_active_service_execution}, "-h", "Average:$self->{heartbeat}"); } RRDs::update ($self->{global_active_service_execution}, "--template", "Min:Max:Average", "N:".$1.":".$2.":".$3); if (RRDs::error()) { - $error = RRDs::error() + $error = RRDs::error(); $self->{logger}->writeLogError($error); } @@ -127,7 +127,7 @@ sub rrd_process { $tab[$j+1] = trim($tab[$j+1]); $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)/; if (!-e $self->{global_active_service_last}) { - RRDs::create ($self->{global_active_service_last}, "-s $self->{interval}", "DS:Last_Min:GAUGE:$self->{interval}:0:U", "DS:Last_5_Min:GAUGE:$self->{interval}:0:U", "DS:Last_15_Min:GAUGE:$self->{interval}:0:U", "DS:Last_Hour:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::create ($self->{global_active_service_last}, "-s $self->{interval}", "DS:Last_Min:GAUGE:$self->{interval}:0:U", "DS:Last_5_Min:GAUGE:$self->{interval}:0:U", "DS:Last_15_Min:GAUGE:$self->{interval}:0:U", "DS:Last_Hour:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$self->{number}, "RRA:AVERAGE:0.5:12:".$self->{number}); RRDs::tune($self->{global_active_service_last}, "-h", "Last_Min:$self->{heartbeat}"); RRDs::tune($self->{global_active_service_last}, "-h", "Last_5_Min:$self->{heartbeat}"); RRDs::tune($self->{global_active_service_last}, "-h", "Last_15_Min:$self->{heartbeat}"); @@ -135,7 +135,7 @@ sub rrd_process { } RRDs::update ($self->{global_active_service_last}, "--template", "Last_Min:Last_5_Min:Last_15_Min:Last_Hour", "N:".$1.":".$2.":".$3.":".$4); if (RRDs::error()) { - $error = RRDs::error() + $error = RRDs::error(); $self->{logger}->writeLogError($error); } @@ -150,8 +150,8 @@ sub rrd_process { } elsif ($match =~ /Services Ok\/Warn\/Unk\/Crit/) { $tab[$j+1] = trim($tab[$j+1]); $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)/; - if (! -e $self->{global_services_states) { - RRDs::create ($self->{global_services_states}, "-s $self->{interval}", "DS:Ok:GAUGE:$self->{interval}:0:U", "DS:Warn:GAUGE:$self->{interval}:0:U", "DS:Unk:GAUGE:$self->{interval}:0:U", "DS:Crit:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + if (! -e $self->{global_services_states}) { + RRDs::create ($self->{global_services_states}, "-s $self->{interval}", "DS:Ok:GAUGE:$self->{interval}:0:U", "DS:Warn:GAUGE:$self->{interval}:0:U", "DS:Unk:GAUGE:$self->{interval}:0:U", "DS:Crit:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$self->{number}, "RRA:AVERAGE:0.5:12:".$self->{number}); RRDs::tune($self->{global_services_states}, "-h", "Ok:$self->{heartbeat}"); RRDs::tune($self->{global_services_states}, "-h", "Warn:$self->{heartbeat}"); RRDs::tune($self->{global_services_states}, "-h", "Unk:$self->{heartbeat}"); @@ -159,7 +159,7 @@ sub rrd_process { } RRDs::update ($self->{global_services_states}, "--template", "Ok:Warn:Unk:Crit", "N:".$1.":".$2.":".$3.":".$4); if (RRDs::error()) { - $error = RRDs::error() + $error = RRDs::error(); $self->{logger}->writeLogError($error); } @@ -175,14 +175,14 @@ sub rrd_process { $tab[$j+1] = trim($tab[$j+1]); $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ [sec|%]/; if (! -e $self->{global_active_host_latency}) { - RRDs::create ($self->{global_active_host_latency}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::create ($self->{global_active_host_latency}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$self->{number}, "RRA:AVERAGE:0.5:12:".$self->{number}); RRDs::tune($self->{global_active_host_latency}, "-h", "Min:$self->{heartbeat}"); RRDs::tune($self->{global_active_host_latency}, "-h", "Max:$self->{heartbeat}"); RRDs::tune($self->{global_active_host_latency}, "-h", "Average:$self->{heartbeat}"); } RRDs::update ($self->{global_active_host_latency}, "--template", "Min:Max:Average", "N:".$1.":".$2.":".$3); if (RRDs::error()) { - $error = RRDs::error() + $error = RRDs::error(); $self->{logger}->writeLogError($error); } @@ -197,14 +197,14 @@ sub rrd_process { $tab[$j+1] = trim($tab[$j+1]); $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ sec/; if (! -e $self->{global_active_host_execution}) { - RRDs::create ($self->{global_active_host_execution}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::create ($self->{global_active_host_execution}, "-s $self->{interval}", "DS:Min:GAUGE:$self->{interval}:0:U", "DS:Max:GAUGE:$self->{interval}:0:U", "DS:Average:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$self->{number}, "RRA:AVERAGE:0.5:12:".$self->{number}); RRDs::tune($self->{global_active_host_execution}, "-h", "Min:$self->{heartbeat}"); RRDs::tune($self->{global_active_host_execution}, "-h", "Max:$self->{heartbeat}"); RRDs::tune($self->{global_active_host_execution}, "-h", "Average:$self->{heartbeat}"); } RRDs::update ($self->{global_active_host_execution}, "--template", "Min:Max:Average", "N:".$1.":".$2.":".$3); if (RRDs::error()) { - $error = RRDs::error() + $error = RRDs::error(); $self->{logger}->writeLogError($error); } @@ -219,7 +219,7 @@ sub rrd_process { $tab[$j+1] = trim($tab[$j+1]); $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)/; if (!-e $self->{global_active_host_last}) { - RRDs::create ($self->{global_active_host_last}, "-s $self->{interval}", "DS:Last_Min:GAUGE:$self->{interval}:0:U", "DS:Last_5_Min:GAUGE:$self->{interval}:0:U", "DS:Last_15_Min:GAUGE:$self->{interval}:0:U", "DS:Last_Hour:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::create ($self->{global_active_host_last}, "-s $self->{interval}", "DS:Last_Min:GAUGE:$self->{interval}:0:U", "DS:Last_5_Min:GAUGE:$self->{interval}:0:U", "DS:Last_15_Min:GAUGE:$self->{interval}:0:U", "DS:Last_Hour:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$self->{number}, "RRA:AVERAGE:0.5:12:".$self->{number}); RRDs::tune($self->{global_active_host_last}, "-h", "Last_Min:$self->{heartbeat}"); RRDs::tune($self->{global_active_host_last}, "-h", "Last_5_Min:$self->{heartbeat}"); RRDs::tune($self->{global_active_host_last}, "-h", "Last_15_Min:$self->{heartbeat}"); @@ -227,7 +227,7 @@ sub rrd_process { } RRDs::update ($self->{global_active_host_last}, "--template", "Last_Min:Last_5_Min:Last_15_Min:Last_Hour", "N:".$1.":".$2.":".$3.":".$4); if (RRDs::error()) { - $error = RRDs::error() + $error = RRDs::error(); $self->{logger}->writeLogError($error); } @@ -242,14 +242,14 @@ sub rrd_process { $tab[$j+1] = trim($tab[$j+1]); $tab[$j+1] =~ /([0-9\.]*)\ \/\ ([0-9\.]*)\ \/\ ([0-9\.]*)/; if (!-e $self->{global_hosts_states}) { - RRDs::create($self->{global_hosts_states}, "-s $self->{interval}", "DS:Up:GAUGE:$self->{interval}:0:U", "DS:Down:GAUGE:$self->{interval}:0:U", "DS:Unreach:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$number, "RRA:AVERAGE:0.5:12:".$number); + RRDs::create($self->{global_hosts_states}, "-s $self->{interval}", "DS:Up:GAUGE:$self->{interval}:0:U", "DS:Down:GAUGE:$self->{interval}:0:U", "DS:Unreach:GAUGE:$self->{interval}:0:U", "RRA:AVERAGE:0.5:1:".$self->{number}, "RRA:AVERAGE:0.5:12:".$self->{number}); RRDs::tune($self->{global_hosts_states}, "-h", "Up:$self->{heartbeat}"); RRDs::tune($self->{global_hosts_states}, "-h", "Down:$self->{heartbeat}"); RRDs::tune($self->{global_hosts_states}, "-h", "Unreach:$self->{heartbeat}"); } RRDs::update ($self->{global_hosts_states}, "--template", "Up:Down:Unreach", "N:".$1.":".$2.":".$3); if (RRDs::error()) { - $error = RRDs::error() + $error = RRDs::error(); $self->{logger}->writeLogError($error); } @@ -263,7 +263,7 @@ sub rrd_process { $j++; } if (!$error && ($query_str ne "")) { - my ($status, $sth) = $self->{csdb}->query("DELETE FROM `nagios_stats` WHERE instance_id = '" . $ns_id . "'") + my ($status, $sth) = $self->{csdb}->query("DELETE FROM `nagios_stats` WHERE instance_id = '" . $ns_id . "'"); ($status, $sth) = $self->{csdb}->query("INSERT INTO `nagios_stats` (instance_id, stat_label, stat_key, stat_value) VALUES " . $query_str); } } @@ -274,7 +274,7 @@ sub check_dir { if (! -d $self->{global_prefix} . "perfmon-" . $nagios_id) { if (mkpath($self->{global_prefix} . "perfmon-" . $nagios_id) == 0) { - $self->{logger}->writeLogError("Can't create directory '" . $self->{global_prefix} . "perfmon-" . $nagios_id . "': $!") + $self->{logger}->writeLogError("Can't create directory '" . $self->{global_prefix} . "perfmon-" . $nagios_id . "': $!"); return 0; } } @@ -301,7 +301,7 @@ sub get_poller { my $cfg_item; my $cfg_result; my $cfg_dir; - my $nagiostats; + my $nagiostats_bin; my $must_update_ds; my $dataDir = $self->{centreon_config}->{VarLib} . "/log/"; @@ -325,8 +325,12 @@ sub get_poller { $self->{logger}->writeLogError("The Monitoring engine configuration filename is empty."); next; } + if (!defined($nagiostats_bin) || $nagiostats_bin eq '') { + $self->{logger}->writeLogError("The monitoring engine stat binary is empty"); + next; + } - my $nagiostats_bin = ''; + my $nagiostats = ''; if ($is_localhost){ $nagiostats = `$nagiostats_bin -c $cfg_dir/$cfg_result->{'cfg_file'}`; @@ -348,7 +352,7 @@ sub get_poller { $nagiostats = `ssh $self->{sshOptions} -p $ssh_port $ip $nagiostats_bin -c $cfg_dir/$cfg_result->{'cfg_file'}`; } } - if ($nagiosstats eq '' || $nagiostats =~ m/Error reading status file/ ) { + if ($nagiostats eq '' || $nagiostats =~ m/Error reading status file/ ) { next; } if ($self->check_dir($id) == 1) { From 249e6db3ebdbac5751d87260947564298dadfa97 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 2 Apr 2013 17:08:02 +0200 Subject: [PATCH 030/458] Fix PID manage --- centreon/lib/perl/centreon/common/lock.pm | 7 +++++-- centreon/lib/perl/centreon/script/nagiosPerfTrace.pm | 6 ++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/centreon/common/lock.pm b/centreon/lib/perl/centreon/common/lock.pm index 86a7a804fdd..10d9b20170a 100644 --- a/centreon/lib/perl/centreon/common/lock.pm +++ b/centreon/lib/perl/centreon/common/lock.pm @@ -4,8 +4,8 @@ use strict; use warnings; sub new { - my ($class, $name, $pid, %options) = @_; - my %defaults = (name => $name, pid => $pid, timeout => 10); + my ($class, $name, %options) = @_; + my %defaults = (name => $name, pid => $$, timeout => 10); my $self = {%defaults, %options}; bless $self, $class; @@ -83,6 +83,8 @@ sub is_set { my ($status, $sth) = $self->{dbc}->query( "SELECT id,running,pid,time_launch FROM cron_operation WHERE name LIKE '$self->{name}'" ); + + return 1 if ($status == -1); my $data = $sth->fetchrow_hashref(); if (!defined $data->{id}) { @@ -91,6 +93,7 @@ sub is_set { return 0; } $self->{id} = $data->{id}; + $data->{pid} = -1 if (!defined($data->{pid})); $self->{pid} = $data->{pid}; $self->{previous_launch_time} = $data->{time_launch}; if (defined $data->{running} && $data->{running} == 1) { diff --git a/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm b/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm index a0fba390f2f..ca0fa30de85 100644 --- a/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm +++ b/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm @@ -1,5 +1,5 @@ -package centreon::script::NagiosPerfTrace; +package centreon::script::nagiosPerfTrace; use strict; use warnings; @@ -11,7 +11,7 @@ use base qw(centreon::script); sub new { my $class = shift; - my $self = $class->SUPER::new("logAnalyser", + my $self = $class->SUPER::new("nagiosPerfTrace", centreon_db_conn => 1, centstorage_db_conn => 1 ); @@ -389,6 +389,8 @@ sub run { $self->get_poller(); } +1; + __END__ =head1 NAME From 635d0df9fc3dd5a245254a80723c61bb41e2210d Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 2 Apr 2013 17:18:16 +0200 Subject: [PATCH 031/458] Add noroot option --- centreon/lib/perl/centreon/script.pm | 11 ++++++++++- centreon/lib/perl/centreon/script/logAnalyser.pm | 3 ++- centreon/lib/perl/centreon/script/nagiosPerfTrace.pm | 3 ++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/centreon/lib/perl/centreon/script.pm b/centreon/lib/perl/centreon/script.pm index ab584bb9a73..557c1fa33f0 100644 --- a/centreon/lib/perl/centreon/script.pm +++ b/centreon/lib/perl/centreon/script.pm @@ -26,7 +26,8 @@ sub new { centreon_db_conn => 0, centstorage_db_conn => 0, severity => "info", - noconfig => 0 + noconfig => 0, + noroot => 0 ); my $self = {%defaults, %options}; @@ -50,6 +51,14 @@ sub init { } $self->{logger}->severity($self->{severity}); + if ($self->{noroot} == 1) { + # Stop exec if root + if ($< == 0) { + $self->{logger}->writeLogError("Can't execute script as root."); + die("Quit"); + } + } + if ($self->{centreon_db_conn}) { $self->{cdb} = centreon::common::db->new (db => $self->{centreon_config}->{centreon_db}, diff --git a/centreon/lib/perl/centreon/script/logAnalyser.pm b/centreon/lib/perl/centreon/script/logAnalyser.pm index 61aa94e5799..a6278e28687 100644 --- a/centreon/lib/perl/centreon/script/logAnalyser.pm +++ b/centreon/lib/perl/centreon/script/logAnalyser.pm @@ -11,7 +11,8 @@ sub new { my $class = shift; my $self = $class->SUPER::new("logAnalyser", centreon_db_conn => 1, - centstorage_db_conn => 1 + centstorage_db_conn => 1, + noroot => 1 ); bless $self, $class; diff --git a/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm b/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm index ca0fa30de85..b835ae21a41 100644 --- a/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm +++ b/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm @@ -13,7 +13,8 @@ sub new { my $class = shift; my $self = $class->SUPER::new("nagiosPerfTrace", centreon_db_conn => 1, - centstorage_db_conn => 1 + centstorage_db_conn => 1, + noroot => 1 ); bless $self, $class; From 34e8a0cef1f0bb2d8d9c29b108fb15f5a8a9c905 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 3 Apr 2013 10:31:19 +0200 Subject: [PATCH 032/458] Working on centcore Remove findbin (put Perl vendor lib) --- centreon/lib/perl/centreon/script/centcore.pm | 999 ++++++++++++++++++ 1 file changed, 999 insertions(+) create mode 100644 centreon/lib/perl/centreon/script/centcore.pm diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm new file mode 100644 index 00000000000..a2550578314 --- /dev/null +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -0,0 +1,999 @@ + +package centreon::script::centcore; + +use strict; +use File::Copy; +use File::Path qw(mkpath); +use centreon::script; +use centreon::common::db; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("centcore", + centreon_db_conn => 0, + centstorage_db_conn => 0, + noroot => 1 + ); + + bless $self, $class; + + $installedPath = "@CENTREON_DIR@"; + $cmdFile = "@CENTREON_VARLIB@/centcore.cmd"; + $cmdDir = "@CENTREON_VARLIB@/centcore/"; + $VARLIB = "@CENTREON_VARLIB@"; + + $echo = "/bin/echo"; + $ssh = "@BIN_SSH@"; + $scp = "@BIN_SCP@"; + $rsync = "rsync"; + $rsyncWT = $rsync; + $sudo = "sudo"; + + $ssh .= " -o ConnectTimeout=$timeout -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; + $rsync .= " --timeout=$timeout "; + $scp .= " -o ConnectTimeout=$timeout -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; + + $timeout = 5; + $timeBetween2SyncPerf = 60; + $perfdataSync = 0; + $logSync = 0; + $stop = 1; + + $timeSyncPerf = 0; + $difTime = 10; + + $self->set_signal_handlers; + + return $self; +} + +use vars qw($debug $LOG %status $generalcounter $stop $method $perfdataSync $logSync $timeBetween2SyncPerf); +use vars qw($con $ssh $scp $rsync $rsyncWT $echo $sudo $installedPath $timeout); +use vars qw(%commandBuffer); + +####################################### +# Include Configuration Data + +sub init_config { + my $file = $_[0]; + my $type = $_[1]; + + unless (my $return = do $file) { + writeLogFile("couldn't parse $file: $@") if $@; + writeLogFile("couldn't do $file: $!") unless defined $return; + writeLogFile("couldn't run $file") unless $return; + if ($type == 1) { + writeLogFile("Quit program"); + exit(1); + } + } +} + +sub catch_zap { + $stop = 0; + writeLogFile("Receiving order to stop..."); +} + +sub catch_reload { + writeLogFile("Receiving order to reload..."); + init_config("@CENTREON_ETC@/conf.pm", 0); + open my $centcore_fh, '>>', $LOG; + open STDOUT, '>&', $centcore_fh; + open STDERR, '>&', $centcore_fh; +} + +########################################################### +# Init signal actions +# +$SIG{'TERM'} = \&catch_zap; +$SIG{'HUP'} = \&catch_reload; + +########################################################### +# Function to move command file on temporary file +# +sub moveCmdFile($){ + my $CMDFILE = $_[0]; + if (move($CMDFILE, $CMDFILE."_read")) { + return(1); + } else { + writeLogFile("Cannot move $CMDFILE to ".$CMDFILE."_read"); + return(0); + } +} + +########################################################### +# Function to remove temporary command file +# +sub removeTmpCmdFile($){ + my $CMDFILE = $_[0]; + if (unlink($CMDFILE."_read")){ + return(1); + } else { + writeLogFile("Can't remove temporary command file."); + return(0); + } +} + +############################################ +## Get all perfdata files +# +sub GetAllNagiosServerPerfData(){ + CheckMySQLConnexion(); + my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `localhost` = '0' AND `ns_activate` = '1'"); + if (!$sth2->execute()) { + writeLogFile("Error when getting server properties : ".$sth2->errstr); + return ; + } + while (my $data = $sth2->fetchrow_hashref()) { + if (!$stop) { + $sth2->finish(); + $con->disconnect(); + return ; + } + if ($perfdataSync == 1) { + GetPerfData($data->{'id'}); + } + if ($logSync == 1) { + GetLogFile($data->{'id'}); + } + getBrokerStats($data->{'id'}); + } + $sth2->finish(); + $con->disconnect(); + return; +} + +########################################### +## Get a instant copy of the broker stat +## fifo +# +sub getBrokerStats($) { + my ($poller_id) = @_; + my $port = ""; + my $statPipe = "/tmp/.centreon-broker-stats.dat"; + my $destFile = $VARLIB."/broker-stats"; + my $server_info; + + # Check Cache directory + if (!-d $destFile) { + writeLogFile("Create data directory for broker-stats: $destFile"); + mkpath($destFile); + } + + # Check MySQL Configuration + CheckMySQLConnexion(); + + my $sth2 = $con->prepare("SELECT cbi.config_value FROM cfg_centreonbroker_info as cbi, cfg_centreonbroker as cb WHERE cb.config_id = cbi.config_id AND cbi.config_group = 'stats' AND cbi.config_key = 'fifo' AND cb.ns_nagios_server = '".$poller_id."'"); + if (!$sth2->execute()) { + writeLogFile("Error poller broker pipe : ".$sth2->errstr); + return ; + } + while (my $data = $sth2->fetchrow_hashref()) { + + # Get poller Configuration + $server_info = getServerConfig($poller_id); + $port = checkSSHPort($server_info->{'ssh_port'}); + + # Copy the stat file into a buffer + my $stdout = `$ssh -q $server_info->{'ns_ip_address'} -p $port 'cat \"$data->{'config_value'}" > $statPipe'`; + if (defined($stdout) && $stdout){ + writeLogFile("Result : $stdout\n"); + } + + # Get the stats file + $stdout = `$scp -P $port $server_info->{'ns_ip_address'}:$statPipe $destFile/broker-stats-$poller_id.dat >> /dev/null`; + if (defined($stdout) && $stdout){ + writeLogFile("Result : $stdout\n"); + } + } + return; +} + +# ------------------- +# Functions +# ------------------- + +sub getNagiosConfigurationField($$){ + CheckMySQLConnexion(); + my $sth2 = $con->prepare("SELECT ".$_[1]." FROM `cfg_nagios` WHERE `nagios_server_id` = '".$_[0]."' AND nagios_activate = '1'"); + if (!$sth2->execute()) { + writeLogFile("Error when getting server properties : ".$sth2->errstr); + } + my $data = $sth2->fetchrow_hashref(); + $sth2->finish(); + return $data->{$_[1]}; +} + +sub getLocalOptionsField($){ + CheckMySQLConnexion(); + my $sth2 = $con->prepare("SELECT `value` FROM `options` WHERE `key` LIKE '".$_[0]."' LIMIT 1"); + if (!$sth2->execute()) { + writeLogFile("Error when getting general options properties : ".$sth2->errstr); + } + my $data = $sth2->fetchrow_hashref(); + $sth2->finish(); + return $data->{'value'}; +} + +sub getLocalServerID(){ + CheckMySQLConnexion(); + my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `localhost` = '1'"); + if (!$sth2->execute()) { + writeLogFile("Error when getting server properties : ".$sth2->errstr); + } + my $id = $sth2->fetchrow_hashref(); + $sth2->finish(); + return $id->{'id'}; +} + +sub getServerConfig($){ + CheckMySQLConnexion(); + my $sth2 = $con->prepare("SELECT * FROM `nagios_server` WHERE `id` = '".$_[0]."' AND `ns_activate` = '1'"); + if (!$sth2->execute()) { + writeLogFile("Error when getting server properties : ".$sth2->errstr."\n"); + } + my $data = $sth2->fetchrow_hashref(); + $sth2->finish(); + + # Get Nagios User + $data->{'nagios_user'} = getNagiosConfigurationField($_[0], 'nagios_user'); + return $data; +} + +##################################### +## Get perfdata file path +# +sub getPerfDataFile($$){ + my ($filename, $sth2, $data); + my ($con, $poller_id) = @_; + + # Create request + my $request = "SELECT `nagios_perfdata` FROM `nagios_server` WHERE `id` = '".$poller_id."'"; + $sth2 = $con->prepare($request); + if (!$sth2->execute()) { + writeLogFile("Error when getting perfdata file : " . $sth2->errstr . ""); + return ""; + } + $data = $sth2->fetchrow_hashref(); + $filename = $data->{'nagios_perfdata'}; + + # Free + $sth2->finish(); + return $filename; +} + +################################## +## Check SSH Port Value +# +sub checkSSHPort($) { + my ($value) = @_; + my $port; + + if (defined($value) && $value) { + $port = $value; + } else { + $port = 22; + } + return $port; +} + +################################################ +## Send an external command on a remote server. +## Param : id_remote_server, external command +# +sub sendExternalCommand($$){ + # Init Parameters + my ($id, $cmd) = @_; + my $stdout; + + # Get server informations + my $server_info = getServerConfig($id); + my $port = checkSSHPort($server_info->{'ssh_port'}); + + # Get command file + my $command_file = getNagiosConfigurationField($id, "command_file"); + + # check if ip address is defined + if (defined($server_info->{'ns_ip_address'})) { + $cmd =~ s/\\/\\\\/g; + if ($server_info->{'localhost'} == 1) { + my $result = waitPipe($command_file); + if ($result == 0) { + writeLogFile("External command on Central Server: ($id) : \"".$cmd."\""); + my $cmd = "echo \"".$cmd."\" >> ".$command_file."\n"; + $stdout = `$cmd`; + } else { + writeLogFile("Cannot write external command on central server : \"".$cmd."\""); + } + } else { + writeLogFile("External command : ".$server_info->{'ns_ip_address'}." ($id) : \"".$cmd."\""); + my $cmd = "$ssh -q ". $server_info->{'ns_ip_address'} ." -p $port 'echo \"".$cmd."\" >> ".$command_file."'\n"; + $stdout = `$cmd`; + } + + if (defined($stdout) && $stdout){ + writeLogFile("Result : $stdout\n"); + } + + } else { + writeLogFile("Ip address not defined for poller $id"); + } + + $commandBuffer{$id} = ""; +} + +####################################### +## Wait Nagios Pipe availability +# +sub waitPipe($) { + my ($pid) = @_; + my $i = 0; + while (! -p $pid) { + sleep(1); + $i++; + if ($i >= 30) { + return 1; + } + } + return 0; +} + + +####################################### +## Get perfdata on a specific poller +# +sub GetPerfData($){ + # init Values + my ($id) = @_; + + # Check MySQL Connection + CheckMySQLConnexion(); + + # Get Server Infos + my $server_info = getServerConfig($id); + my $port = checkSSHPort($server_info->{'ssh_port'});; + + my $distantconnexion = $server_info->{'ns_ip_address'}; + + # Where is perfdata file on remote poller + my $distantperffile = getPerfDataFile($con, $id); + my $distantperffile_buffer = $distantperffile . ".buff"; + + if (!defined($distantperffile_buffer) || !$distantperffile_buffer) { + writeLogFile("perfdata file not configured for poller $id ($distantconnexion)"); + return; + } + + # Build destination directory reserved for this poller + my $localbasevardir = "$VARLIB/perfdata/$id"; + + # check if directory exists + if (!-d $localbasevardir) { + mkpath $localbasevardir; + } + + my $localtmpperffile = "$localbasevardir/service-perfdata"; + my $localperffile = getPerfDataFile($con, getLocalServerID()); + my $move_cmd = "rm -f $distantperffile_buffer 2> /dev/null; cp $distantperffile $distantperffile_buffer 2> /dev/null ; echo \"# New File\" > $distantperffile"; + + # Get Perfdata file + if (!defined($distantperffile)) { + writeLogFile("Cannot get perfdata file. Unkown perfdata file on poller $id"); + } else { + # Rename perfdata file + my $cmd = "$ssh ". $server_info->{'ns_ip_address'} ." -p $port '".$move_cmd."'"; + writeLogFile($cmd) if ($debug); + my $stdout = `$cmd`; + if (defined($stdout) && $stdout){ + writeLogFile("Result : $stdout\n"); + } + + # Get Perfdata File + writeLogFile("$scp -P $port $distantconnexion:$distantperffile_buffer $localtmpperffile") if ($debug); + $stdout = `$scp -P $port $distantconnexion:$distantperffile_buffer $localtmpperffile 2>> /dev/null`; + if (defined($stdout) && $stdout){ + writeLogFile("Result : $stdout\n"); + } + + # Write data from distant poller on local file for centstorage + if (-f $localtmpperffile){ + # Concat poller perfdata to central perfdata. + writeLogFile("cat $localtmpperffile >> $localperffile") if ($debug); + `cat $localtmpperffile >> $localperffile`; + + # Remove old file + if (!unlink($localtmpperffile)) { + writeLogFile("Cannot Remove performance data file : $localtmpperffile"); + } + } + } +} + +## +# Checks if rotation occured, +# +sub checkRotation($$$$$) { + my $instanceId = $_[0]; + my $lastUpdate = $_[1]; + my $remoteConnection = $_[2]; + my $localLogFile = $_[3]; + my $port = $_[4]; + + my $archivePath = getNagiosConfigurationField($instanceId, 'log_archive_path'); + my $getLastCmd = 'echo "$(find '.$archivePath.' -type f -exec stat -c "%Z:%n" {} \; | sort | tail -1)"'; + my $check_cmd = "$ssh -p $port -q $remoteConnection '".$getLastCmd."'"; + my $result = `$check_cmd`; + $result =~ /(\d+):(.+)/; + my $updateTime = $1; + my $fileName = $2; + if (defined($updateTime) && defined($lastUpdate) && $updateTime > $lastUpdate) { + my $cmd = "$scp -P $port $remoteConnection:$fileName $localLogFile.rotate > /dev/null"; + `$cmd`; + writeLogFile("Info: copied rotated file for instance $instanceId"); + } +} + +################################## +## Get Log files on the specific +## poller +# +sub GetLogFile($){ + # Init values + my $id = $_[0]; + my $last_access; + + # Get Server informations + my $server_info = getServerConfig($id); + my $port = checkSSHPort($server_info->{'ssh_port'}); + + # Check configuration + my $distantconnexion = $server_info->{'ns_ip_address'}; + if (!defined($distantconnexion)) { + writeLogFile("IP address not defined for poller $id"); + } + + # Set local directory + my $localDir = $VARLIB."/log/$id/"; + + # Create tmp directory + mkpath $localDir if (!-d $localDir); + + # Get logs if dir exists + if (-d $localDir){ + + # Get distant log file path + my $distantlogfile = getNagiosConfigurationField($id, "log_file");; + my $locallogfile = $localDir."nagios.log"; + + # check if we can do the transfert + if (defined($distantconnexion) && defined($distantlogfile)) { + # Check if nagios.log file is up to date + my $flag; + if (-f $localDir.".nagios.log.flag") { + # Cet old flag + my $cmd = $localDir.".nagios.log.flag"; + my $value = `cat $cmd`; + $value =~ s/\n//g; + + checkRotation($id, $value, $distantconnexion, $locallogfile, $port); + + # Check update + my $check_cmd = "$ssh -p $port -q $distantconnexion 'stat -c \'STAT_RESULT=%Y\' $distantlogfile'"; + writeLogFile("Get Log Files - stat: $check_cmd") if ($debug); + $last_access = `$check_cmd`; + $last_access =~ /STAT_RESULT=(\d+)/; + $last_access = $1; + writeLogFile("Get Log File - stat: Finished") if ($debug); + + # Check buffer + if ($value !~ $last_access) { + $flag = 1; + } else { + $flag = 0; + } + + } else { + $flag = 1; + } + + if ($flag == 1) { + # Get file with rsync + my $cmd = "$scp -P $port $distantconnexion:$distantlogfile $locallogfile > /dev/null"; + `$cmd`; + writeLogFile($cmd) if ($debug); + if ($? ne 0) { + writeLogFile("Cannot get log file or log file doesn't exists on poller $id"); + } + } + + # Update or create time buffer + my $buffer_cmd = "echo '$last_access' > ".$localDir.".nagios.log.flag"; + `$buffer_cmd`; + } + } else { + writeLogFile("Unable to create $localDir. Can get nagios log file for poller $id"); + } +} + +################################################## +# Send config files to a remote server +# +sub sendConfigFile($){ + # Init Values + my $id = $_[0]; + my $debug = 0; + + my $cfg_dir = getNagiosConfigurationField($id, "cfg_dir"); + my $server_info = getServerConfig($id); + my $port = checkSSHPort($server_info->{'ssh_port'}); + + if (!defined($cfg_dir) || $cfg_dir =~ //) { + writeLogFile("Engine configuration file is empty for poller $id. Please check nagios.cfg file."); + return; + } + + my $origin = $installedPath."/filesGeneration/nagiosCFG/".$id."/*"; + my $dest = $server_info->{'ns_ip_address'}.":$cfg_dir"; + + # Send data with SCP + writeLogFile("Start: Send config files on poller $id"); + my $cmd = "$scp -P $port $origin $dest > /dev/null"; + my $stdout = `$cmd`; + if (defined($stdout) && $stdout){ + writeLogFile("Result : $stdout\n"); + } + writeLogFile("End: Send config files on poller $id"); + + # Send configuration for Centreon Broker + if ( -e $installedPath."/filesGeneration/broker/".$id) { + # Check availability of broker files. + my $count = 0; + opendir(my $dh, $installedPath."/filesGeneration/broker/".$id); + while(readdir $dh) { + $count++; + } + closedir $dh; + + if ($count > 2) { + writeLogFile("Start: Send Centreon Broker config files on poller $id") if ($debug); + + if ($server_info->{'localhost'} == 0) { + $cfg_dir = $server_info->{'centreonbroker_cfg_path'}; + $origin = $installedPath."/filesGeneration/broker/".$id."/*.xml"; + $dest = $server_info->{'ns_ip_address'}.":$cfg_dir"; + $cmd = "$scp -P $port $origin $dest 2>&1"; + my $stdout = `$cmd`; + if (defined($stdout) && $stdout) { + writeLogFile("Result : $stdout\n"); + } + } else { + my $cmd = "cp $origin $cfg_dir 2>&1"; + my $stdout = `$cmd`; + if (defined($stdout) && $stdout) { + writeLogFile("Result : $stdout\n"); + } + } + writeLogFile("End: Send Centreon Broker config files on poller $id") if ($debug); + } + } +} + +################################################## +# Function for initialize Nagios : +# Parameters : +# - start +# - restart +# - stop +# +sub initEngine($$){ + my $id = $_[0]; + my $options = $_[1]; + my ($cmd, $stdout); + + # Get configuration + my $conf = getServerConfig($id); + my $port = checkSSHPort($conf->{'ssh_port'}); + + if (!defined($conf)) { + writeLogFile("Poller $id doesn't exists..."); + writeLogFile("Cannot manage undefined poller..."); + return; + } + + if (defined($conf->{'ns_ip_address'}) && $conf->{'ns_ip_address'}) { + # Launch command + $cmd = "$ssh -p $port ". $conf->{'ns_ip_address'} ." $sudo ".$conf->{'init_script'}." ".$options; + $stdout = `$cmd`; + } else { + writeLogFile("Cannot $options Nagios for poller $id"); + } + + # Logs Actions + writeLogFile("Init Script : '$sudo ".$conf->{'init_script'}." ".$options."' On poller ".$conf->{'ns_ip_address'}." ($id)"); + my $line; + if (defined($stdout)) { + foreach $line (split(/\n/, $stdout)){ + writeLogFile("Engine : ".$line); + } + } +} + +################################################## +# Function for synchronize SNMP trap configuration +# +sub syncTraps($) { + my $id = $_[0]; + my $stdout; + + # Check MySQL Connexion + CheckMySQLConnexion(); + + if ($id != 0) { + # Get configuration + my $ns_server = getServerConfig($id); + my $port = checkSSHPort($ns_server->{'ssh_port'}); + + if ($id != 0 && $ns_server->{'localhost'} == 0) { + my $cmd = "$scp -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/"; + writeLogFile($cmd) if ($debug); + $stdout = `$cmd`; + if (defined($stdout) && $stdout){ + writeLogFile("Result : $stdout\n"); + } + + writeLogFile("ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l") if ($debug); + my $ls = `ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l`; + if ($ls > 1) { + writeLogFile("$rsync --port=$port -c /etc/snmp/centreon_traps/*.conf ". $ns_server->{'ns_ip_address'} .":/etc/snmp/centreon_traps/") if ($debug); + $stdout = `$rsync --port=$port -c /etc/snmp/centreon_traps/*.conf $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/`; + if (defined($stdout) && $stdout){ + writeLogFile("Result : $stdout\n"); + } + } + } + } else { + # synchronize Archives for all pollers + my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); + if (!$sth2->execute) { + writeLogFile("Error:" . $sth2->errstr); + return ; + } else { + while (my $server = $sth2->fetchrow_hashref()) { + # Get configuration + my $ns_server = getServerConfig($server->{'id'}); + my $port = checkSSHPort($ns_server->{'ssh_port'}); + + if ($id == 0) { + my $cmd = "$scp -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/"; + writeLogFile($cmd) if ($debug); + $stdout = `$cmd`; + if (defined($stdout) && $stdout){ + writeLogFile("Result : $stdout\n"); + } + $cmd = "ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l"; + writeLogFile($cmd) if ($debug); + my $ls = `$cmd`; + if ($ls > 1) { + $cmd = "$rsync --port=$port -c /etc/snmp/centreon_traps/*.conf $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/"; + writeLogFile($cmd) if ($debug); + $stdout = `$cmd`; + if (defined($stdout) && $stdout){ + writeLogFile("Result : $stdout\n"); + } + } + } + } + } + } +} + +################################### +## Test Engine configuration +# +sub testConfig($) { + my $id = $_[0]; + + my $cfg_dir = getNagiosConfigurationField($id, "cfg_dir"); + my $data = getServerConfig($id); + my $port = checkSSHPort($data->{'ssh_port'}); + my $distantconnexion = $data->{'ns_ip_address'}; + my $cmd = "$ssh -p ".$port." $distantconnexion $sudo ".$data->{'nagios_bin'}." -v $cfg_dir/nagios.cfg"; + my $stdout = `$cmd`; + writeLogFile("$stdout\n"); +} + +################################### +## Sync engine Logs Archives in the +## central Server +# +sub syncArchives($) { + my $id = $_[0]; + + # Check MySQL Connexion + CheckMySQLConnexion(); + + # Get configuration + my $ns_server = getServerConfig($id); + my $port = checkSSHPort($ns_server->{'ssh_port'}); + + if ($id != 0) { + # Sync Archive for one poller + if (! -d "$VARLIB/log/".$ns_server->{'id'}."/archives/") { + if (! -d "$VARLIB/log/".$ns_server->{'id'}."/archives/") { + mkpath "$VARLIB/log/".$ns_server->{'id'}."/archives/"; + } + } + my $sth = $con->prepare("SELECT `log_archive_path` FROM `cfg_nagios` WHERE `nagios_server_id` = '".$id."' AND `nagios_activate` = '1'"); + if ($sth->execute()) { + my $data = $sth->fetchrow_hashref(); + + # Archive Sync + my $cmd = "$rsync --port=$port -c ". $ns_server->{'ns_ip_address'}. ":".$data->{'log_archive_path'}."/*.log $VARLIB/log/".$ns_server->{'id'}."/archives/"; + writeLogFile($cmd) if ($debug); + `$rsyncWT --port=$port -c $ns_server->{'ns_ip_address'}:$data->{'log_archive_path'}/*.log $VARLIB/log/$ns_server->{'id'}/archives/ 2>> /dev/null`; + } else { + print "Can't get archive path for poller ".$ns_server->{'id'}." (".$ns_server->{'ns_address_ip'}.") -> ".$sth->errstr; + } + } else { + # synchronize Archives for all pollers + my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); + if (!$sth2->execute) { + writeLogFile("Error:" . $sth2->errstr); + return ; + } else { + while (my $server = $sth2->fetchrow_hashref()) { + writeLogFile("Receive Order to synchronize all archives of all pollers"); + syncArchives($server->{'id'}); + } + } + } +} + +################################## +## Get Monitoring Engine. +# +sub getInfos($) { + my $id = $_[0]; + + # Check MySQL Connexion + CheckMySQLConnexion(); + + # Get configuration + my $ns_server = getServerConfig($id); + my $port = checkSSHPort($ns_server->{'ssh_port'}); + + if (defined($ns_server->{'ns_ip_address'}) && $ns_server->{'ns_ip_address'}) { + # Launch command + my $cmd = "$ssh -p $port ". $ns_server->{'ns_ip_address'} ." ".$ns_server->{'nagios_bin'}.""; + writeLogFile($cmd) if ($debug); + my $stdout = `$cmd`; + + my @tab = split("\n", $stdout); + foreach my $str (@tab) { + if ($str =~ m/(Nagios) Core ([\.0-9]*[a-zA-Z0-9\-\.]+)/) { + writeLogFile("Engine: $1"); + writeLogFile("Version: $2"); + last; + } + if ($str =~ m/(Centreon Engine) ([\.0-9]*[a-zA-Z0-9\-\.]+)/) { + writeLogFile("Engine: $1"); + writeLogFile("Version: $2"); + last; + } + } + } else { + writeLogFile("Cannot get informations for poller $id"); + } +} + +################################ +## Restart SNMPTT Daemon +# +sub restartSNMPTT($) { + my $id = $_[0]; + my $stdout = ""; + my $cmd = ""; + my $debug = 0; + + # Check MySQL Connexion + CheckMySQLConnexion(); + + # Get configuration + my $ns_server = getServerConfig($id); + my $port = checkSSHPort($ns_server->{'ssh_port'}); + + if (defined($ns_server->{'ns_ip_address'}) && $ns_server->{'ns_ip_address'} + && defined($ns_server->{'init_script_snmptt'}) && $ns_server->{'init_script_snmptt'} ne "") { + # Launch command + if (defined($ns_server->{'localhost'}) && $ns_server->{'localhost'}) { + $cmd = "$sudo ".$ns_server->{'init_script_snmptt'}." restart"; + writeLogFile($cmd) if ($debug); + $stdout = `$cmd`; + } else { + $cmd = "$ssh -p $port ". $ns_server->{'ns_ip_address'} ." $sudo ".$ns_server->{'init_script_snmptt'}." restart"; + writeLogFile($cmd) if ($debug); + $stdout = `$cmd`; + } + writeLogFile("Restart SNMPTT on poller $id ($ns_server->{'ns_ip_address'})"); + } else { + writeLogFile("Cannot restart SNMPTT for poller $id"); + } +} + +#################################### +## Parse request +# +sub parseRequest($){ + my ($action) = @_; + if (!$action) { + return ; + } + + # Checks keys for launching commands + if ($action =~ /^RESTART\:([0-9]*)/){ + initEngine($1, "restart"); + } elsif ($action =~ /^RELOAD\:([0-9]*)/){ + initEngine($1, "reload"); + } elsif ($action =~ /^START\:([0-9]*)/){ + initEngine($1, "start"); + } elsif ($action =~ /^STOP\:([0-9]*)/){ + initEngine($1, "stop"); + } elsif ($action =~ /^SENDCFGFILE\:([0-9]*)/){ + sendConfigFile($1); + } elsif ($action =~ /^TEST\:([0-9]*)/){ + # Experimental + testConfig($1); + } elsif ($action =~ /^SYNCTRAP\:([0-9]*)/){ + syncTraps($1); + } elsif ($action =~ /^RESTARTSNMPTT\:([0-9]*)/){ + restartSNMPTT($1); + } elsif ($action =~ /^SYNCARCHIVES\:([0-9]*)/){ + syncArchives($1); + } elsif ($action =~ /^EXTERNALCMD\:([0-9]*)\:(.*)/){ + storeCommands($1, $2); + } elsif ($action =~ /^GETINFOS\:([0-9]*)/){ + getInfos($1); + } +} + +############################################ +## Check Centcore Configuration Profile +# +sub checkProfile() { + # Check MySQL Connexion + CheckMySQLConnexion(); + + my $request = "SELECT * FROM options WHERE `key` IN ('enable_perfdata_sync', 'enable_logs_sync')"; + my $sth = $con->prepare($request); + if ($sth->execute()) { + my $data; + while ($data = $sth->fetchrow_hashref()) { + if (defined($data->{'key'}) && $data->{'key'} ne "" && defined($data->{'value'}) && $data->{'value'} ne "") { + if ($data->{'key'} eq "enable_perfdata_sync") { + $perfdataSync = $data->{'value'}; + } + if ($data->{'key'} eq "enable_logs_sync") { + $logSync = $data->{'value'}; + } + } + } + } + return 0; +} + +# Check if debug has been enable into GUI +sub checkDebugFlag($) { + my ($display) = @_; + + # Check MySQL Connexion + CheckMySQLConnexion(); + my $oldDebug = $debug; + + my $request = "SELECT * FROM options WHERE `key` IN ('debug_centcore')"; + my $sth = $con->prepare($request); + if ($sth->execute()) { + my $data = $sth->fetchrow_hashref(); + if (defined($data->{'value'}) && $data->{'value'} == 1) { + $debug = 1; + if ($debug ne $oldDebug && $display) { + writeLogFile("Enable Debug in Centcore"); + } + } else { + $debug = 0; + if ($debug ne $oldDebug && $display) { + writeLogFile("Disable Debug in Centcore"); + } + } + } +} + +# Store commands in order to group commands to send. +sub storeCommands($$) { + my ($poller_id, $command) = @_; + + if (!defined($commandBuffer{$poller_id})) { + $commandBuffer{$poller_id} = ""; + } + $commandBuffer{$poller_id} .= $command . "\n"; +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + $self->{logger}->redirect_output(); + $self->{logger}->writeLogInfo("Starting centcore engine..."); + + checkDebugFlag(0); + + while ($stop) { + # Read Centcore.cmd + if (-e $cmdFile) { + if (moveCmdFile($cmdFile) && open(FILE, "< $cmdFile"."_read")) { + while (){ + parseRequest($_); + } + my $poller; + foreach $poller (keys(%commandBuffer)) { + if (length($commandBuffer{$poller}) != 0) { + sendExternalCommand($poller, $commandBuffer{$poller}); + $commandBuffer{$poller} = ""; + } + } + } + close(FILE); + $self->{logger}->writeLogError("Error When removing ".$cmdFile."_read file : $!") if (!unlink($cmdFile."_read")); + } + + # Read Centcore Directory + if (-d $cmdDir) { + opendir(my $dh, $cmdDir); + while (my $file = readdir($dh)) { + if ($file ne "." && $file ne ".." && $file ne "") { + if (moveCmdFile($cmdDir.$file) && open(FILE, "< ".$cmdDir.$file."_read")) { + while (){ + parseRequest($_); + } + my $poller; + foreach $poller (keys(%commandBuffer)) { + if (length($commandBuffer{$poller}) != 0) { + sendExternalCommand($poller, $commandBuffer{$poller}); + $commandBuffer{$poller} = ""; + } + } + close(FILE); + $self->{logger}->writeLogError("Error When removing ".$cmdDir.$file."_read file : $!") if (!unlink($cmdDir.$file."_read")); + } + } + } + closedir $dh; + } + + if (defined($timeSyncPerf) && $timeSyncPerf) { + $difTime = time() - $timeSyncPerf; + } + + # Get PerfData on Nagios Poller + if ((defined($difTime) && $timeBetween2SyncPerf <= $difTime) || $timeSyncPerf == 0){ + # Check Activity profile Status + checkProfile(); + + # Check debug Flag + checkDebugFlag(1); + + GetAllNagiosServerPerfData(); + $timeSyncPerf = time(); + } + + sleep(1); + } + + $self->{logger}->writeLogInfo("Centcore stop..."); +} + +1; + +__END__ + From c8e2425dd9c77668679390605e26c25a8ba7c219 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 3 Apr 2013 12:15:31 +0200 Subject: [PATCH 033/458] Working on centcore initial Conflicts: bin/centcore --- centreon/lib/perl/centreon/script/centcore.pm | 814 +++++++++--------- 1 file changed, 401 insertions(+), 413 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index a2550578314..4a2b0be0664 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -9,6 +9,8 @@ use centreon::common::db; use base qw(centreon::script); +my %handlers = ('TERM' => {}, 'HUP' => {}, 'DIE' => {}); + sub new { my $class = shift; my $self = $class->SUPER::new("centcore", @@ -19,99 +21,104 @@ sub new { bless $self, $class; - $installedPath = "@CENTREON_DIR@"; - $cmdFile = "@CENTREON_VARLIB@/centcore.cmd"; - $cmdDir = "@CENTREON_VARLIB@/centcore/"; - $VARLIB = "@CENTREON_VARLIB@"; - - $echo = "/bin/echo"; - $ssh = "@BIN_SSH@"; - $scp = "@BIN_SCP@"; - $rsync = "rsync"; - $rsyncWT = $rsync; - $sudo = "sudo"; - - $ssh .= " -o ConnectTimeout=$timeout -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; - $rsync .= " --timeout=$timeout "; - $scp .= " -o ConnectTimeout=$timeout -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; - - $timeout = 5; - $timeBetween2SyncPerf = 60; - $perfdataSync = 0; - $logSync = 0; - $stop = 1; - - $timeSyncPerf = 0; - $difTime = 10; + $self->{echo} = "echo"; + $self->{ssh} = "ssh"; + $self->{scp} = "scp"; + $self->{rsync} = "rsync"; + $self->{rsyncWT} = $self->{rsync}; + $self->{sudo} = "sudo"; + + $self->{ssh} .= " -o ConnectTimeout=$timeout -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; + $self->{rsync} .= " --timeout=$timeout "; + $self->{scp} .= " -o ConnectTimeout=$timeout -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; + + $self->{timeout} = 5; + $self->{timeBetween2SyncPerf} = 60; + $self->{perfdataSync} = 0; + $self->{logSync} = 0; + $self->{stop} = 1; + $self->{reload} = 1; + + $self->{timeSyncPerf} = 0; + $self->{difTime} = 10; + + %{$self->{commandBuffer}} = (); $self->set_signal_handlers; return $self; } -use vars qw($debug $LOG %status $generalcounter $stop $method $perfdataSync $logSync $timeBetween2SyncPerf); -use vars qw($con $ssh $scp $rsync $rsyncWT $echo $sudo $installedPath $timeout); -use vars qw(%commandBuffer); +sub init { + my $self = shift; + $self->{cmdFile} = $self->{centreon_config}->{VarLib} . "/centcore.cmd"; + $self->{cmdDir} = $self->{centreon_config}->{VarLib} . "/centcore/"; + $self->{centreonDir} = $self->{centreon_config}->{CentreonDir}; +} -####################################### -# Include Configuration Data +sub set_signal_handlers { + my $self = shift; -sub init_config { - my $file = $_[0]; - my $type = $_[1]; - - unless (my $return = do $file) { - writeLogFile("couldn't parse $file: $@") if $@; - writeLogFile("couldn't do $file: $!") unless defined $return; - writeLogFile("couldn't run $file") unless $return; - if ($type == 1) { - writeLogFile("Quit program"); - exit(1); - } + $SIG{TERM} = \&class_handle_TERM; + $handlers{TERM}->{$self} = sub { $self->handle_TERM() }; + $SIG{__DIE__} = \&class_handle_DIE; + $handlers{DIE}->{$self} = sub { $self->handle_DIE($_[0]) }; + $SIG{HUP} = \&class_handle_HUP; + $handlers{HUP}->{$self} = sub { $self->handle_HUP() }; +} + +sub class_handle_TERM { + foreach (keys %{$handlers{TERM}}) { + &{$handlers{TERM}->{$_}}(); } } -sub catch_zap { - $stop = 0; - writeLogFile("Receiving order to stop..."); +sub class_handle_DIE { + my ($msg) = @_; + + foreach (keys %{$handlers{DIE}}) { + &{$handlers{DIE}->{$_}}($msg); + } } -sub catch_reload { - writeLogFile("Receiving order to reload..."); - init_config("@CENTREON_ETC@/conf.pm", 0); - open my $centcore_fh, '>>', $LOG; - open STDOUT, '>&', $centcore_fh; - open STDERR, '>&', $centcore_fh; +sub class_handle_HUP { + foreach (keys %{$handlers{HUP}}) { + &{$handlers{HUP}->{$_}}(); + } } -########################################################### -# Init signal actions -# -$SIG{'TERM'} = \&catch_zap; -$SIG{'HUP'} = \&catch_reload; +sub handle_HUP { + my $self = shift; + + $self->{logger}->writeLogInfo("Receiving order to reload..."); + $self->{reload} = 0; +} + +sub handle_TERM { + my $self = shift; + $self->{logger}->writeLogInfo("$$ Receiving order to stop..."); + $self->{stop} = 0; +} + +sub handle_DIE { + my $self = shift; + my $msg = shift; + + $self->{logger}->writeLogInfo("Receiving die: $msg"); + $self->{logger}->writeLogInfo("Dont die..."); +} ########################################################### # Function to move command file on temporary file # sub moveCmdFile($){ - my $CMDFILE = $_[0]; - if (move($CMDFILE, $CMDFILE."_read")) { - return(1); - } else { - writeLogFile("Cannot move $CMDFILE to ".$CMDFILE."_read"); - return(0); - } -} + my $self = shift; + my $cmdfile = $_[0]; -########################################################### -# Function to remove temporary command file -# -sub removeTmpCmdFile($){ - my $CMDFILE = $_[0]; - if (unlink($CMDFILE."_read")){ + if (move($cmdfile, $cmdfile."_read")) { return(1); } else { - writeLogFile("Can't remove temporary command file."); + $self->{logger}->writeLogError("Cannot move $cmdfile to ".$cmdfile."_read"); return(0); } } @@ -119,30 +126,27 @@ sub removeTmpCmdFile($){ ############################################ ## Get all perfdata files # -sub GetAllNagiosServerPerfData(){ - CheckMySQLConnexion(); - my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `localhost` = '0' AND `ns_activate` = '1'"); - if (!$sth2->execute()) { - writeLogFile("Error when getting server properties : ".$sth2->errstr); - return ; +sub GetAllNagiosServerPerfData { + my $self = shift; + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `id` FROM `nagios_server` WHERE `localhost` = '0' AND `ns_activate` = '1'"); + if ($status == -1) { + $self->{logger}->writeLogError("Error when getting server properties"); + return -1; } - while (my $data = $sth2->fetchrow_hashref()) { - if (!$stop) { - $sth2->finish(); - $con->disconnect(); + while (my $data = $sth->fetchrow_hashref()) { + if (!$self->{stop}) { return ; } - if ($perfdataSync == 1) { - GetPerfData($data->{'id'}); + if ($self->{perfdataSync} == 1) { + $self->GetPerfData($data->{'id'}); } - if ($logSync == 1) { - GetLogFile($data->{'id'}); + if ($self->{logSync} == 1) { + $self->GetLogFile($data->{'id'}); } getBrokerStats($data->{'id'}); } - $sth2->finish(); - $con->disconnect(); - return; + + return 0; } ########################################### @@ -153,7 +157,7 @@ sub getBrokerStats($) { my ($poller_id) = @_; my $port = ""; my $statPipe = "/tmp/.centreon-broker-stats.dat"; - my $destFile = $VARLIB."/broker-stats"; + my $destFile = $self->{centreon_config}->{VarLib} . "/broker-stats"; my $server_info; # Check Cache directory @@ -196,13 +200,14 @@ sub getBrokerStats($) { # ------------------- sub getNagiosConfigurationField($$){ - CheckMySQLConnexion(); - my $sth2 = $con->prepare("SELECT ".$_[1]." FROM `cfg_nagios` WHERE `nagios_server_id` = '".$_[0]."' AND nagios_activate = '1'"); - if (!$sth2->execute()) { - writeLogFile("Error when getting server properties : ".$sth2->errstr); + my $self = shift; + + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT " . $_[1] . " FROM `cfg_nagios` WHERE `nagios_server_id` = '" . $_[0] . "' AND nagios_activate = '1'"); + if ($status == -1) { + $self->{logger}->writeLogError("Error when getting server properties"); + return undef; } - my $data = $sth2->fetchrow_hashref(); - $sth2->finish(); + my $data = $sth->fetchrow_hashref(); return $data->{$_[1]}; } @@ -218,27 +223,29 @@ sub getLocalOptionsField($){ } sub getLocalServerID(){ - CheckMySQLConnexion(); - my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `localhost` = '1'"); - if (!$sth2->execute()) { - writeLogFile("Error when getting server properties : ".$sth2->errstr); + my $self = shift; + + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `id` FROM `nagios_server` WHERE `localhost` = '1' LIMIT 1"); + if ($status == -1) { + $self->{logger}->writeLogError("Error when getting server properties"); + return undef; } - my $id = $sth2->fetchrow_hashref(); - $sth2->finish(); + my $id = $sth->fetchrow_hashref(); return $id->{'id'}; } sub getServerConfig($){ - CheckMySQLConnexion(); - my $sth2 = $con->prepare("SELECT * FROM `nagios_server` WHERE `id` = '".$_[0]."' AND `ns_activate` = '1'"); - if (!$sth2->execute()) { - writeLogFile("Error when getting server properties : ".$sth2->errstr."\n"); + my $self = shift; + + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT * FROM `nagios_server` WHERE `id` = '" . $_[0] . "' AND `ns_activate` = '1' LIMIT 1"); + if ($status == -1) { + $self->{logger}->writeLogError("Error when getting server properties"); + return undef; } - my $data = $sth2->fetchrow_hashref(); - $sth2->finish(); - + my $data = $sth->fetchrow_hashref(); + # Get Nagios User - $data->{'nagios_user'} = getNagiosConfigurationField($_[0], 'nagios_user'); + $data->{'nagios_user'} = $self->getNagiosConfigurationField($_[0], 'nagios_user'); return $data; } @@ -246,21 +253,19 @@ sub getServerConfig($){ ## Get perfdata file path # sub getPerfDataFile($$){ - my ($filename, $sth2, $data); - my ($con, $poller_id) = @_; + my $self = shift; + my ($filename); + my ($poller_id) = @_; # Create request - my $request = "SELECT `nagios_perfdata` FROM `nagios_server` WHERE `id` = '".$poller_id."'"; - $sth2 = $con->prepare($request); - if (!$sth2->execute()) { - writeLogFile("Error when getting perfdata file : " . $sth2->errstr . ""); + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `nagios_perfdata` FROM `nagios_server` WHERE `id` = '".$poller_id."' LIMIT 1"); + if ($status == -1) { + $self->{logger}->writeLogError("Error when getting perfdata file"); return ""; } - $data = $sth2->fetchrow_hashref(); + my $data = $sth->fetchrow_hashref(); $filename = $data->{'nagios_perfdata'}; - # Free - $sth2->finish(); return $filename; } @@ -284,16 +289,17 @@ sub checkSSHPort($) { ## Param : id_remote_server, external command # sub sendExternalCommand($$){ + my $self = shift; # Init Parameters my ($id, $cmd) = @_; my $stdout; # Get server informations - my $server_info = getServerConfig($id); + my $server_info = $self->getServerConfig($id); my $port = checkSSHPort($server_info->{'ssh_port'}); # Get command file - my $command_file = getNagiosConfigurationField($id, "command_file"); + my $command_file = $self->getNagiosConfigurationField($id, "command_file"); # check if ip address is defined if (defined($server_info->{'ns_ip_address'})) { @@ -301,36 +307,34 @@ sub sendExternalCommand($$){ if ($server_info->{'localhost'} == 1) { my $result = waitPipe($command_file); if ($result == 0) { - writeLogFile("External command on Central Server: ($id) : \"".$cmd."\""); - my $cmd = "echo \"".$cmd."\" >> ".$command_file."\n"; + $self->{logger}->writeLogInfo("External command on Central Server: ($id) : \"".$cmd."\""); + my $cmd = "self->{echo} \"".$cmd."\" >> ".$command_file."\n"; $stdout = `$cmd`; } else { - writeLogFile("Cannot write external command on central server : \"".$cmd."\""); + $self->{logger}->writeLogError("Cannot write external command on central server : \"".$cmd."\""); } } else { - writeLogFile("External command : ".$server_info->{'ns_ip_address'}." ($id) : \"".$cmd."\""); - my $cmd = "$ssh -q ". $server_info->{'ns_ip_address'} ." -p $port 'echo \"".$cmd."\" >> ".$command_file."'\n"; + $self->{logger}->writeLogInfo("External command : ".$server_info->{'ns_ip_address'}." ($id) : \"".$cmd."\""); + my $cmd = "$self->{ssh} -q ". $server_info->{'ns_ip_address'} ." -p $port '$self->{echo} \"".$cmd."\" >> ".$command_file."'\n"; $stdout = `$cmd`; } if (defined($stdout) && $stdout){ - writeLogFile("Result : $stdout\n"); + $self->{logger}->writeLogInfo("Result : $stdout"); } } else { - writeLogFile("Ip address not defined for poller $id"); + $self->{logger}->writeLogError("Ip address not defined for poller $id"); } - - $commandBuffer{$id} = ""; } ####################################### ## Wait Nagios Pipe availability # sub waitPipe($) { - my ($pid) = @_; + my ($pipe) = @_; my $i = 0; - while (! -p $pid) { + while (! -p $pipe) { sleep(1); $i++; if ($i >= 30) { @@ -345,29 +349,27 @@ sub waitPipe($) { ## Get perfdata on a specific poller # sub GetPerfData($){ + my $self = shift; # init Values my ($id) = @_; - # Check MySQL Connection - CheckMySQLConnexion(); - # Get Server Infos - my $server_info = getServerConfig($id); + my $server_info = $self->getServerConfig($id); my $port = checkSSHPort($server_info->{'ssh_port'});; my $distantconnexion = $server_info->{'ns_ip_address'}; # Where is perfdata file on remote poller - my $distantperffile = getPerfDataFile($con, $id); + my $distantperffile = $self->getPerfDataFile($id); my $distantperffile_buffer = $distantperffile . ".buff"; if (!defined($distantperffile_buffer) || !$distantperffile_buffer) { - writeLogFile("perfdata file not configured for poller $id ($distantconnexion)"); + $self->{logger}->writeLogError("perfdata file not configured for poller $id ($distantconnexion)"); return; } # Build destination directory reserved for this poller - my $localbasevardir = "$VARLIB/perfdata/$id"; + my $localbasevardir = $self->{centreon_config}->{VarLib} . "/perfdata/$id"; # check if directory exists if (!-d $localbasevardir) { @@ -375,38 +377,39 @@ sub GetPerfData($){ } my $localtmpperffile = "$localbasevardir/service-perfdata"; - my $localperffile = getPerfDataFile($con, getLocalServerID()); + my $localperffile = $self->getPerfDataFile($self->getLocalServerID()); my $move_cmd = "rm -f $distantperffile_buffer 2> /dev/null; cp $distantperffile $distantperffile_buffer 2> /dev/null ; echo \"# New File\" > $distantperffile"; # Get Perfdata file if (!defined($distantperffile)) { - writeLogFile("Cannot get perfdata file. Unkown perfdata file on poller $id"); - } else { - # Rename perfdata file - my $cmd = "$ssh ". $server_info->{'ns_ip_address'} ." -p $port '".$move_cmd."'"; - writeLogFile($cmd) if ($debug); - my $stdout = `$cmd`; - if (defined($stdout) && $stdout){ - writeLogFile("Result : $stdout\n"); - } + $self->{logger}->writeLogError("Cannot get perfdata file. Unkown perfdata file on poller $id"); + return ; + } + + # Rename perfdata file + my $cmd = "$self->{ssh} ". $server_info->{'ns_ip_address'} ." -p $port '".$move_cmd."'"; + $self->{logger}->writeLogDebug($cmd); + my $stdout = `$cmd`; + if (defined($stdout) && $stdout){ + $self->{logger}->writeLogInfo("Result : $stdout"); + } - # Get Perfdata File - writeLogFile("$scp -P $port $distantconnexion:$distantperffile_buffer $localtmpperffile") if ($debug); - $stdout = `$scp -P $port $distantconnexion:$distantperffile_buffer $localtmpperffile 2>> /dev/null`; - if (defined($stdout) && $stdout){ - writeLogFile("Result : $stdout\n"); - } + # Get Perfdata File + $self->{logger}->writeLogDebug("$self->{scp} -P $port $distantconnexion:$distantperffile_buffer $localtmpperffile"); + $stdout = `$self->{scp} -P $port $distantconnexion:$distantperffile_buffer $localtmpperffile 2>> /dev/null`; + if (defined($stdout) && $stdout){ + $self->{logger}->writeLogInfo("Result : $stdout"); + } - # Write data from distant poller on local file for centstorage - if (-f $localtmpperffile){ - # Concat poller perfdata to central perfdata. - writeLogFile("cat $localtmpperffile >> $localperffile") if ($debug); - `cat $localtmpperffile >> $localperffile`; + # Write data from distant poller on local file for centstorage + if (-f $localtmpperffile){ + # Concat poller perfdata to central perfdata. + $self->{logger}->writeLogDebug("cat $localtmpperffile >> $localperffile"); + `cat $localtmpperffile >> $localperffile`; - # Remove old file - if (!unlink($localtmpperffile)) { - writeLogFile("Cannot Remove performance data file : $localtmpperffile"); - } + # Remove old file + if (!unlink($localtmpperffile)) { + $self->{logger}->writeLogError("Cannot Remove performance data file : $localtmpperffile"); } } } @@ -415,85 +418,86 @@ sub GetPerfData($){ # Checks if rotation occured, # sub checkRotation($$$$$) { - my $instanceId = $_[0]; - my $lastUpdate = $_[1]; - my $remoteConnection = $_[2]; - my $localLogFile = $_[3]; - my $port = $_[4]; - - my $archivePath = getNagiosConfigurationField($instanceId, 'log_archive_path'); - my $getLastCmd = 'echo "$(find '.$archivePath.' -type f -exec stat -c "%Z:%n" {} \; | sort | tail -1)"'; - my $check_cmd = "$ssh -p $port -q $remoteConnection '".$getLastCmd."'"; - my $result = `$check_cmd`; - $result =~ /(\d+):(.+)/; - my $updateTime = $1; - my $fileName = $2; - if (defined($updateTime) && defined($lastUpdate) && $updateTime > $lastUpdate) { - my $cmd = "$scp -P $port $remoteConnection:$fileName $localLogFile.rotate > /dev/null"; - `$cmd`; - writeLogFile("Info: copied rotated file for instance $instanceId"); - } + my $self = shift; + my $instanceId = $_[0]; + my $lastUpdate = $_[1]; + my $remoteConnection = $_[2]; + my $localLogFile = $_[3]; + my $port = $_[4]; + + my $archivePath = $self->getNagiosConfigurationField($instanceId, 'log_archive_path'); + my $getLastCmd = 'echo "$(find '.$archivePath.' -type f -exec stat -c "%Z:%n" {} \; | sort | tail -1)"'; + my $check_cmd = "$self->{ssh} -p $port -q $remoteConnection '".$getLastCmd."'"; + my $result = `$check_cmd`; + $result =~ /(\d+):(.+)/; + my $updateTime = $1; + my $fileName = $2; + if (defined($updateTime) && defined($lastUpdate) && $updateTime > $lastUpdate) { + my $cmd = "$self->{scp} -P $port $remoteConnection:$fileName $localLogFile.rotate > /dev/null"; + `$cmd`; + $self->{logger}->writeLogInfo("Info: copied rotated file for instance $instanceId"); + } } ################################## ## Get Log files on the specific ## poller # -sub GetLogFile($){ +sub GetLogFile($) { + my $self = shift; # Init values my $id = $_[0]; my $last_access; # Get Server informations - my $server_info = getServerConfig($id); + my $server_info = $self->getServerConfig($id); my $port = checkSSHPort($server_info->{'ssh_port'}); # Check configuration my $distantconnexion = $server_info->{'ns_ip_address'}; if (!defined($distantconnexion)) { - writeLogFile("IP address not defined for poller $id"); + $self->{logger}->writeLogError("IP address not defined for poller $id"); + return -1; } # Set local directory - my $localDir = $VARLIB."/log/$id/"; + my $localDir = $self->{centreon_config}->{VarLib} . "/log/$id/"; # Create tmp directory mkpath $localDir if (!-d $localDir); # Get logs if dir exists - if (-d $localDir){ - - # Get distant log file path - my $distantlogfile = getNagiosConfigurationField($id, "log_file");; - my $locallogfile = $localDir."nagios.log"; - - # check if we can do the transfert - if (defined($distantconnexion) && defined($distantlogfile)) { - # Check if nagios.log file is up to date - my $flag; - if (-f $localDir.".nagios.log.flag") { - # Cet old flag - my $cmd = $localDir.".nagios.log.flag"; - my $value = `cat $cmd`; - $value =~ s/\n//g; - - checkRotation($id, $value, $distantconnexion, $locallogfile, $port); - - # Check update - my $check_cmd = "$ssh -p $port -q $distantconnexion 'stat -c \'STAT_RESULT=%Y\' $distantlogfile'"; - writeLogFile("Get Log Files - stat: $check_cmd") if ($debug); - $last_access = `$check_cmd`; - $last_access =~ /STAT_RESULT=(\d+)/; - $last_access = $1; - writeLogFile("Get Log File - stat: Finished") if ($debug); - - # Check buffer - if ($value !~ $last_access) { - $flag = 1; - } else { - $flag = 0; - } - + if (-d $localDir) { + # Get distant log file path + my $distantlogfile = $self->getNagiosConfigurationField($id, "log_file");; + my $locallogfile = $localDir."nagios.log"; + + # check if we can do the transfert + if (defined($distantconnexion) && defined($distantlogfile)) { + # Check if nagios.log file is up to date + my $flag; + if (-f $localDir.".nagios.log.flag") { + # Cet old flag + my $cmd = $localDir.".nagios.log.flag"; + my $value = `cat $cmd`; + $value =~ s/\n//g; + + $self->checkRotation($id, $value, $distantconnexion, $locallogfile, $port); + + # Check update + my $check_cmd = "$self->{ssh} -p $port -q $distantconnexion 'stat -c \'STAT_RESULT=%Y\' $distantlogfile'"; + $self->{logger}->writeLogDebug("Get Log Files - stat: $check_cmd"); + $last_access = `$check_cmd`; + $last_access =~ /STAT_RESULT=(\d+)/; + $last_access = $1; + $self->{logger}->writeLogDebug("Get Log File - stat: Finished"); + + # Check buffer + if ($value !~ $last_access) { + $flag = 1; + } else { + $flag = 0; + } } else { $flag = 1; } @@ -502,18 +506,17 @@ sub GetLogFile($){ # Get file with rsync my $cmd = "$scp -P $port $distantconnexion:$distantlogfile $locallogfile > /dev/null"; `$cmd`; - writeLogFile($cmd) if ($debug); + $self->{logger}->writeLogDebug($cmd); if ($? ne 0) { - writeLogFile("Cannot get log file or log file doesn't exists on poller $id"); + $self->{logger}->writeLogError("Cannot get log file or log file doesn't exists on poller $id"); } } - # Update or create time buffer my $buffer_cmd = "echo '$last_access' > ".$localDir.".nagios.log.flag"; `$buffer_cmd`; } } else { - writeLogFile("Unable to create $localDir. Can get nagios log file for poller $id"); + $self->{logger}->writeLogError("Unable to create $localDir. Can get nagios log file for poller $id"); } } @@ -521,61 +524,56 @@ sub GetLogFile($){ # Send config files to a remote server # sub sendConfigFile($){ + my $self = shift; # Init Values my $id = $_[0]; my $debug = 0; - my $cfg_dir = getNagiosConfigurationField($id, "cfg_dir"); - my $server_info = getServerConfig($id); + my $cfg_dir = $self->getNagiosConfigurationField($id, "cfg_dir"); + my $server_info = $self->getServerConfig($id); my $port = checkSSHPort($server_info->{'ssh_port'}); if (!defined($cfg_dir) || $cfg_dir =~ //) { - writeLogFile("Engine configuration file is empty for poller $id. Please check nagios.cfg file."); + $self->{logger}->writeLogError("Engine configuration file is empty for poller $id. Please check nagios.cfg file."); return; } - my $origin = $installedPath."/filesGeneration/nagiosCFG/".$id."/*"; + my $origin = $self->{centreonDir} . "/filesGeneration/nagiosCFG/".$id."/*"; my $dest = $server_info->{'ns_ip_address'}.":$cfg_dir"; # Send data with SCP - writeLogFile("Start: Send config files on poller $id"); - my $cmd = "$scp -P $port $origin $dest > /dev/null"; + $self->{logger}->writeLogInfo("Start: Send config files on poller $id"); + my $cmd = "$self->{scp} -P $port $origin $dest 2>&1"; my $stdout = `$cmd`; - if (defined($stdout) && $stdout){ - writeLogFile("Result : $stdout\n"); - } - writeLogFile("End: Send config files on poller $id"); + $self->{logger}->writeLogInfo("Result : $stdout"); + $self->{logger]->writeLogInfo("End: Send config files on poller $id"); # Send configuration for Centreon Broker - if ( -e $installedPath."/filesGeneration/broker/".$id) { + if ( -e $self->{centreonDir} . "/filesGeneration/broker/".$id) { # Check availability of broker files. my $count = 0; - opendir(my $dh, $installedPath."/filesGeneration/broker/".$id); + opendir(my $dh, $self->{centreonDir} . "/filesGeneration/broker/".$id); while(readdir $dh) { $count++; } closedir $dh; if ($count > 2) { - writeLogFile("Start: Send Centreon Broker config files on poller $id") if ($debug); + $self->{logger}->writeLogDebug("Start: Send Centreon Broker config files on poller $id"); if ($server_info->{'localhost'} == 0) { $cfg_dir = $server_info->{'centreonbroker_cfg_path'}; - $origin = $installedPath."/filesGeneration/broker/".$id."/*.xml"; + $origin = $self->{centreonDir} . "/filesGeneration/broker/".$id."/*.xml"; $dest = $server_info->{'ns_ip_address'}.":$cfg_dir"; - $cmd = "$scp -P $port $origin $dest 2>&1"; + $cmd = "$self->{scp} -P $port $origin $dest 2>&1"; my $stdout = `$cmd`; - if (defined($stdout) && $stdout) { - writeLogFile("Result : $stdout\n"); - } + $self->{logger}->writeLogInfo("Result : $stdout"); } else { my $cmd = "cp $origin $cfg_dir 2>&1"; my $stdout = `$cmd`; - if (defined($stdout) && $stdout) { - writeLogFile("Result : $stdout\n"); - } + $self->{logger}->writeLogInfo("Result : $stdout"); } - writeLogFile("End: Send Centreon Broker config files on poller $id") if ($debug); + $self->{logger}->writeLogDebug("End: Send Centreon Broker config files on poller $id"); } } } @@ -588,34 +586,35 @@ sub sendConfigFile($){ # - stop # sub initEngine($$){ + my $self = shift; my $id = $_[0]; my $options = $_[1]; my ($cmd, $stdout); # Get configuration - my $conf = getServerConfig($id); + my $conf = $self->getServerConfig($id); my $port = checkSSHPort($conf->{'ssh_port'}); if (!defined($conf)) { - writeLogFile("Poller $id doesn't exists..."); - writeLogFile("Cannot manage undefined poller..."); - return; + $self->{logger}->writeLogError("Poller $id doesn't exists..."); + $self->{logger}->writeLogError("Cannot manage undefined poller..."); + return ; } if (defined($conf->{'ns_ip_address'}) && $conf->{'ns_ip_address'}) { # Launch command - $cmd = "$ssh -p $port ". $conf->{'ns_ip_address'} ." $sudo ".$conf->{'init_script'}." ".$options; + $cmd = "$self->{ssh} -p $port ". $conf->{'ns_ip_address'} ." $self->{sudo} ".$conf->{'init_script'}." ".$options; $stdout = `$cmd`; } else { - writeLogFile("Cannot $options Nagios for poller $id"); + $self->{logger}->writeLogError("Cannot $options Engine for poller $id"); } # Logs Actions - writeLogFile("Init Script : '$sudo ".$conf->{'init_script'}." ".$options."' On poller ".$conf->{'ns_ip_address'}." ($id)"); + $self->{logger}->writeLogInfo("Init Script : '$self->{sudo} ".$conf->{'init_script'}." ".$options."' On poller ".$conf->{'ns_ip_address'}." ($id)"); my $line; if (defined($stdout)) { foreach $line (split(/\n/, $stdout)){ - writeLogFile("Engine : ".$line); + $self->{logger}->writeLogDebug("Engine : ".$line); } } } @@ -624,64 +623,58 @@ sub initEngine($$){ # Function for synchronize SNMP trap configuration # sub syncTraps($) { + my $self = shift; my $id = $_[0]; my $stdout; - # Check MySQL Connexion - CheckMySQLConnexion(); - if ($id != 0) { # Get configuration - my $ns_server = getServerConfig($id); + my $ns_server = $self->getServerConfig($id); my $port = checkSSHPort($ns_server->{'ssh_port'}); if ($id != 0 && $ns_server->{'localhost'} == 0) { - my $cmd = "$scp -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/"; - writeLogFile($cmd) if ($debug); + my $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/ 2>&1"; + $self->{logger}->writeLogDebug($cmd); $stdout = `$cmd`; if (defined($stdout) && $stdout){ - writeLogFile("Result : $stdout\n"); + $self->{logger}->writeLogInfo("Result : $stdout"); } - writeLogFile("ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l") if ($debug); + $self->{logger}->writeLogDebug("ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l"); my $ls = `ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l`; if ($ls > 1) { - writeLogFile("$rsync --port=$port -c /etc/snmp/centreon_traps/*.conf ". $ns_server->{'ns_ip_address'} .":/etc/snmp/centreon_traps/") if ($debug); - $stdout = `$rsync --port=$port -c /etc/snmp/centreon_traps/*.conf $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/`; + $self->{logger}->writeLogDebug("$self->{rsync} --port=$port -c /etc/snmp/centreon_traps/*.conf ". $ns_server->{'ns_ip_address'} .":/etc/snmp/centreon_traps/"); + $stdout = `$self->{rsync} --port=$port -c /etc/snmp/centreon_traps/*.conf $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/`; if (defined($stdout) && $stdout){ - writeLogFile("Result : $stdout\n"); + $self->{logger}->writeLogInfo("Result : $stdout\n"); } } } } else { # synchronize Archives for all pollers - my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); - if (!$sth2->execute) { - writeLogFile("Error:" . $sth2->errstr); - return ; - } else { - while (my $server = $sth2->fetchrow_hashref()) { - # Get configuration - my $ns_server = getServerConfig($server->{'id'}); - my $port = checkSSHPort($ns_server->{'ssh_port'}); - - if ($id == 0) { - my $cmd = "$scp -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/"; - writeLogFile($cmd) if ($debug); + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `id` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); + return if ($status == -1); + while (my $server = $sth2->fetchrow_hashref()) { + # Get configuration + my $ns_server = getServerConfig($server->{'id'}); + my $port = checkSSHPort($ns_server->{'ssh_port'}); + + if ($id == 0) { + my $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/ 2>&1"; + $self->{logger}->writeLogDebug($cmd); + $stdout = `$cmd`; + if (defined($stdout) && $stdout){ + $self->{logger}->writeLogInfo("Result : $stdout"); + } + $cmd = "ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l"; + $self->{logger}->writeLogDebug($cmd); + my $ls = `$cmd`; + if ($ls > 1) { + $cmd = "$self->{rsync} --port=$port -c /etc/snmp/centreon_traps/*.conf $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/"; + $self->{logger}->writeLogDebug($cmd); $stdout = `$cmd`; if (defined($stdout) && $stdout){ - writeLogFile("Result : $stdout\n"); - } - $cmd = "ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l"; - writeLogFile($cmd) if ($debug); - my $ls = `$cmd`; - if ($ls > 1) { - $cmd = "$rsync --port=$port -c /etc/snmp/centreon_traps/*.conf $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/"; - writeLogFile($cmd) if ($debug); - $stdout = `$cmd`; - if (defined($stdout) && $stdout){ - writeLogFile("Result : $stdout\n"); - } + $self->{logger}->writeLogInfo("Result : $stdout"); } } } @@ -693,15 +686,16 @@ sub syncTraps($) { ## Test Engine configuration # sub testConfig($) { + my $self = shift; my $id = $_[0]; - my $cfg_dir = getNagiosConfigurationField($id, "cfg_dir"); - my $data = getServerConfig($id); + my $cfg_dir = $self->getNagiosConfigurationField($id, "cfg_dir"); + my $data = $self->getServerConfig($id); my $port = checkSSHPort($data->{'ssh_port'}); my $distantconnexion = $data->{'ns_ip_address'}; - my $cmd = "$ssh -p ".$port." $distantconnexion $sudo ".$data->{'nagios_bin'}." -v $cfg_dir/nagios.cfg"; + my $cmd = "$self->{ssh} -p ".$port." $distantconnexion $self->{sudo} ".$data->{'nagios_bin'}." -v $cfg_dir/nagios.cfg"; my $stdout = `$cmd`; - writeLogFile("$stdout\n"); + $self->{logger}->writeLogInfo("Test Config Result: $stdout"); } ################################### @@ -709,44 +703,40 @@ sub testConfig($) { ## central Server # sub syncArchives($) { + my $self = shift; my $id = $_[0]; - # Check MySQL Connexion - CheckMySQLConnexion(); - # Get configuration - my $ns_server = getServerConfig($id); + my $ns_server = $self->getServerConfig($id); my $port = checkSSHPort($ns_server->{'ssh_port'}); if ($id != 0) { + $self->{logger}->writeLogInfo("Begin synchronize all archives of poller " . $id); # Sync Archive for one poller - if (! -d "$VARLIB/log/".$ns_server->{'id'}."/archives/") { - if (! -d "$VARLIB/log/".$ns_server->{'id'}."/archives/") { - mkpath "$VARLIB/log/".$ns_server->{'id'}."/archives/"; + if (! -d $self->{centreon_config}->{VarLib} . "/log/".$ns_server->{'id'}."/archives/") { + if (! -d $self->{centreon_config}->{VarLib} . "/log/".$ns_server->{'id'}."/archives/") { + mkpath $self->{centreon_config}->{VarLib} . "/log/".$ns_server->{'id'}."/archives/"; } } - my $sth = $con->prepare("SELECT `log_archive_path` FROM `cfg_nagios` WHERE `nagios_server_id` = '".$id."' AND `nagios_activate` = '1'"); - if ($sth->execute()) { - my $data = $sth->fetchrow_hashref(); - - # Archive Sync - my $cmd = "$rsync --port=$port -c ". $ns_server->{'ns_ip_address'}. ":".$data->{'log_archive_path'}."/*.log $VARLIB/log/".$ns_server->{'id'}."/archives/"; - writeLogFile($cmd) if ($debug); - `$rsyncWT --port=$port -c $ns_server->{'ns_ip_address'}:$data->{'log_archive_path'}/*.log $VARLIB/log/$ns_server->{'id'}/archives/ 2>> /dev/null`; - } else { - print "Can't get archive path for poller ".$ns_server->{'id'}." (".$ns_server->{'ns_address_ip'}.") -> ".$sth->errstr; + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `log_archive_path` FROM `cfg_nagios` WHERE `nagios_server_id` = '".$id."' AND `nagios_activate` = '1'"); + if ($status == -1) { + $self->{logger}->writeLogError("Can't get archive path for poller ".$ns_server->{'id'}." (".$ns_server->{'ns_address_ip'}.")"); + return ; } + my $data = $sth->fetchrow_hashref(); + # Archive Sync + my $cmd = "$self->{rsyncWT} --port=$port -c ". $ns_server->{'ns_ip_address'}. ":".$data->{'log_archive_path'}."/*.log $self->{centreon_config}->{VarLib}/log/".$ns_server->{'id'}."/archives/"; + $self->{logger}->writeLogDebug($cmd); + `$self->{rsyncWT} --port=$port -c $ns_server->{'ns_ip_address'}:$data->{'log_archive_path'}/*.log $self->{centreon_config}->{VarLib}/log/$ns_server->{'id'}/archives/ 2>> /dev/null`; } else { # synchronize Archives for all pollers - my $sth2 = $con->prepare("SELECT `id` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); - if (!$sth2->execute) { - writeLogFile("Error:" . $sth2->errstr); + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `id` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); + if ($status == -1) { return ; - } else { - while (my $server = $sth2->fetchrow_hashref()) { - writeLogFile("Receive Order to synchronize all archives of all pollers"); - syncArchives($server->{'id'}); - } + } + $self->{logger}->writeLogInfo("Receive Order to synchronize all archives of all pollers"); + while (my $server = $sth->fetchrow_hashref()) { + $self->syncArchives($server->{'id'}); } } } @@ -755,36 +745,34 @@ sub syncArchives($) { ## Get Monitoring Engine. # sub getInfos($) { + my $self = shift; my $id = $_[0]; - # Check MySQL Connexion - CheckMySQLConnexion(); - # Get configuration - my $ns_server = getServerConfig($id); + my $ns_server = $self->getServerConfig($id); my $port = checkSSHPort($ns_server->{'ssh_port'}); if (defined($ns_server->{'ns_ip_address'}) && $ns_server->{'ns_ip_address'}) { # Launch command - my $cmd = "$ssh -p $port ". $ns_server->{'ns_ip_address'} ." ".$ns_server->{'nagios_bin'}.""; - writeLogFile($cmd) if ($debug); + my $cmd = "$self->{ssh} -p $port ". $ns_server->{'ns_ip_address'} ." ".$ns_server->{'nagios_bin'}.""; + $self->{logger}->writeLogDebug($cmd); my $stdout = `$cmd`; my @tab = split("\n", $stdout); foreach my $str (@tab) { if ($str =~ m/(Nagios) Core ([\.0-9]*[a-zA-Z0-9\-\.]+)/) { - writeLogFile("Engine: $1"); - writeLogFile("Version: $2"); + $self->{logger}->writeLogInfo("Engine: $1"); + $self->{logger}->writeLogInfo("Version: $2"); last; } - if ($str =~ m/(Centreon Engine) ([\.0-9]*[a-zA-Z0-9\-\.]+)/) { - writeLogFile("Engine: $1"); - writeLogFile("Version: $2"); + if ($str =~ m/(Centreon Engine) ([\.0-9]*[a-zA-Z0-9\-\.]+)/) { + $self->{logger}->writeLogInfo("Engine: $1"); + $self->{logger}->writeLogInfo("Version: $2"); last; } } } else { - writeLogFile("Cannot get informations for poller $id"); + $self->{logger}->writeLogError("Cannot get informations for poller $id"); } } @@ -792,33 +780,30 @@ sub getInfos($) { ## Restart SNMPTT Daemon # sub restartSNMPTT($) { + my $self = shift; my $id = $_[0]; my $stdout = ""; my $cmd = ""; - my $debug = 0; - - # Check MySQL Connexion - CheckMySQLConnexion(); # Get configuration - my $ns_server = getServerConfig($id); + my $ns_server = $self->getServerConfig($id); my $port = checkSSHPort($ns_server->{'ssh_port'}); if (defined($ns_server->{'ns_ip_address'}) && $ns_server->{'ns_ip_address'} && defined($ns_server->{'init_script_snmptt'}) && $ns_server->{'init_script_snmptt'} ne "") { # Launch command if (defined($ns_server->{'localhost'}) && $ns_server->{'localhost'}) { - $cmd = "$sudo ".$ns_server->{'init_script_snmptt'}." restart"; - writeLogFile($cmd) if ($debug); + $cmd = "$self->{sudo} ".$ns_server->{'init_script_snmptt'}." restart"; + $self->{logger}->writeLogDebug($cmd); $stdout = `$cmd`; } else { - $cmd = "$ssh -p $port ". $ns_server->{'ns_ip_address'} ." $sudo ".$ns_server->{'init_script_snmptt'}." restart"; - writeLogFile($cmd) if ($debug); + $cmd = "$self->{ssh} -p $port ". $ns_server->{'ns_ip_address'} ." $self->{sudo} ".$ns_server->{'init_script_snmptt'}." restart"; + $self->{logger}->writeLogDebug($cmd); $stdout = `$cmd`; } - writeLogFile("Restart SNMPTT on poller $id ($ns_server->{'ns_ip_address'})"); + $self->{logger}->writeLogInfo("Restart SNMPTT on poller $id ($ns_server->{'ns_ip_address'})"); } else { - writeLogFile("Cannot restart SNMPTT for poller $id"); + $self->{logger}->writeLogError("Cannot restart SNMPTT for poller $id"); } } @@ -826,35 +811,37 @@ sub restartSNMPTT($) { ## Parse request # sub parseRequest($){ + my $self = shift; my ($action) = @_; + if (!$action) { return ; } # Checks keys for launching commands if ($action =~ /^RESTART\:([0-9]*)/){ - initEngine($1, "restart"); + $self->initEngine($1, "restart"); } elsif ($action =~ /^RELOAD\:([0-9]*)/){ - initEngine($1, "reload"); + $self->initEngine($1, "reload"); } elsif ($action =~ /^START\:([0-9]*)/){ - initEngine($1, "start"); + $self->initEngine($1, "start"); } elsif ($action =~ /^STOP\:([0-9]*)/){ - initEngine($1, "stop"); + $self->initEngine($1, "stop"); } elsif ($action =~ /^SENDCFGFILE\:([0-9]*)/){ - sendConfigFile($1); + $self->sendConfigFile($1); } elsif ($action =~ /^TEST\:([0-9]*)/){ # Experimental - testConfig($1); + $self->testConfig($1); } elsif ($action =~ /^SYNCTRAP\:([0-9]*)/){ - syncTraps($1); + $self->syncTraps($1); } elsif ($action =~ /^RESTARTSNMPTT\:([0-9]*)/){ - restartSNMPTT($1); + $self->restartSNMPTT($1); } elsif ($action =~ /^SYNCARCHIVES\:([0-9]*)/){ - syncArchives($1); + $self->syncArchives($1); } elsif ($action =~ /^EXTERNALCMD\:([0-9]*)\:(.*)/){ - storeCommands($1, $2); + $self->storeCommands($1, $2); } elsif ($action =~ /^GETINFOS\:([0-9]*)/){ - getInfos($1); + $self->getInfos($1); } } @@ -862,21 +849,18 @@ sub parseRequest($){ ## Check Centcore Configuration Profile # sub checkProfile() { - # Check MySQL Connexion - CheckMySQLConnexion(); + my $self = shift; my $request = "SELECT * FROM options WHERE `key` IN ('enable_perfdata_sync', 'enable_logs_sync')"; - my $sth = $con->prepare($request); - if ($sth->execute()) { - my $data; - while ($data = $sth->fetchrow_hashref()) { - if (defined($data->{'key'}) && $data->{'key'} ne "" && defined($data->{'value'}) && $data->{'value'} ne "") { - if ($data->{'key'} eq "enable_perfdata_sync") { - $perfdataSync = $data->{'value'}; - } - if ($data->{'key'} eq "enable_logs_sync") { - $logSync = $data->{'value'}; - } + my ($status, $sth) = $self->{centreon_dbc}->query($request); + return -1 if ($status == -1); + while ((my $data = $sth->fetchrow_hashref())) { + if (defined($data->{'key'}) && $data->{'key'} ne "" && defined($data->{'value'}) && $data->{'value'} ne "") { + if ($data->{'key'} eq "enable_perfdata_sync") { + $self->{perfdataSync} = $data->{'value'}; + } + if ($data->{'key'} eq "enable_logs_sync") { + $self->{logSync} = $data->{'value'}; } } } @@ -884,106 +868,110 @@ sub checkProfile() { } # Check if debug has been enable into GUI -sub checkDebugFlag($) { - my ($display) = @_; - - # Check MySQL Connexion - CheckMySQLConnexion(); - my $oldDebug = $debug; +sub checkDebugFlag { + my $self = shift; - my $request = "SELECT * FROM options WHERE `key` IN ('debug_centcore')"; - my $sth = $con->prepare($request); - if ($sth->execute()) { - my $data = $sth->fetchrow_hashref(); - if (defined($data->{'value'}) && $data->{'value'} == 1) { - $debug = 1; - if ($debug ne $oldDebug && $display) { - writeLogFile("Enable Debug in Centcore"); - } - } else { - $debug = 0; - if ($debug ne $oldDebug && $display) { - writeLogFile("Disable Debug in Centcore"); - } - } + my $request = "SELECT value FROM options WHERE `key` IN ('debug_centcore')"; + my ($status, $sth) = $self->{centreon_dbc}->query($request); + return -1 if ($status == -1); + my $data = $sth->fetchrow_hashref(); + if (defined($data->{'value'}) && $data->{'value'} == 1) { + $debug = 1; + $self->{logger}->writeLogInfo("Enable Debug in Centcore"); + } else { + $debug = 0; + $self->{logger}->writeLogInfo("Disable Debug in Centcore"); } + return 0; } # Store commands in order to group commands to send. sub storeCommands($$) { + my $self = shift; my ($poller_id, $command) = @_; - if (!defined($commandBuffer{$poller_id})) { - $commandBuffer{$poller_id} = ""; + if (!defined($self->{commandBuffer}{$poller_id})) { + $self->{commandBuffer}{$poller_id} = ""; } - $commandBuffer{$poller_id} .= $command . "\n"; + $self->{commandBuffer}{$poller_id} .= $command . "\n"; } sub run { my $self = shift; $self->SUPER::run(); + $self->init(); $self->{logger}->redirect_output(); $self->{logger}->writeLogInfo("Starting centcore engine..."); - checkDebugFlag(0); + $self->{centreon_dbc} = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 0, + logger => $self->{logger}); + $self->checkDebugFlag(); - while ($stop) { + while ($self->{stop}) { + if ($self->{reload} == 0) { + $self->{logger}->writeLogInfo("Reload in progress..."); + } # Read Centcore.cmd - if (-e $cmdFile) { - if (moveCmdFile($cmdFile) && open(FILE, "< $cmdFile"."_read")) { + if (-e $self->{cmdFile}) { + if ($self->moveCmdFile($self->{cmdFile}) && open(FILE, "< $self->{cmdFile}"."_read")) { while (){ - parseRequest($_); + $self->parseRequest($_); } my $poller; - foreach $poller (keys(%commandBuffer)) { - if (length($commandBuffer{$poller}) != 0) { - sendExternalCommand($poller, $commandBuffer{$poller}); - $commandBuffer{$poller} = ""; + foreach $poller (keys(%{$self->{commandBuffer}})) { + if (length($self->{commandBuffer}{$poller}) != 0) { + $self->sendExternalCommand($poller, $self->{commandBuffer}{$poller}); + $self->{commandBuffer}{$poller} = ""; } } + close(FILE); + $self->{logger}->writeLogError("Error When removing ".$self->{cmdFile}."_read file : $!") if (!unlink($self->{cmdFile}."_read")); } - close(FILE); - $self->{logger}->writeLogError("Error When removing ".$cmdFile."_read file : $!") if (!unlink($cmdFile."_read")); } # Read Centcore Directory - if (-d $cmdDir) { - opendir(my $dh, $cmdDir); + if (-d $self->{cmdDir}) { + opendir(my $dh, $self->{cmdDir}); while (my $file = readdir($dh)) { if ($file ne "." && $file ne ".." && $file ne "") { - if (moveCmdFile($cmdDir.$file) && open(FILE, "< ".$cmdDir.$file."_read")) { + if ($self->moveCmdFile($self->{cmdDir} . $file) && open(FILE, "< ". $self->{cmdDir} . $file . "_read")) { while (){ - parseRequest($_); + $self->parseRequest($_); } my $poller; - foreach $poller (keys(%commandBuffer)) { - if (length($commandBuffer{$poller}) != 0) { - sendExternalCommand($poller, $commandBuffer{$poller}); - $commandBuffer{$poller} = ""; + foreach $poller (keys(%{$self->{commandBuffer}})) { + if (length($self->{commandBuffer}{$poller}) != 0) { + $self->sendExternalCommand($poller, $self->{commandBuffer}{$poller}); + $self->{commandBuffer}{$poller} = ""; } } close(FILE); - $self->{logger}->writeLogError("Error When removing ".$cmdDir.$file."_read file : $!") if (!unlink($cmdDir.$file."_read")); + $self->{logger}->writeLogError("Error When removing ".$self->{cmdDir}.$file."_read file : $!") if (!unlink($self->{cmdDir}.$file."_read")); } } } closedir $dh; } - if (defined($timeSyncPerf) && $timeSyncPerf) { - $difTime = time() - $timeSyncPerf; + if (defined($self->{timeSyncPerf}) && $self->{timeSyncPerf}) { + $self->{difTime} = time() - $self->{timeSyncPerf}; } # Get PerfData on Nagios Poller - if ((defined($difTime) && $timeBetween2SyncPerf <= $difTime) || $timeSyncPerf == 0){ + if ((defined($self->{difTime}) && $self->{timeBetween2SyncPerf} <= $self->{difTime}) || $self->{timeSyncPerf} == 0){ # Check Activity profile Status - checkProfile(); + $self->checkProfile(); # Check debug Flag - checkDebugFlag(1); + $self->checkDebugFlag(); - GetAllNagiosServerPerfData(); + $self->GetAllNagiosServerPerfData(); $timeSyncPerf = time(); } From 6cb63a51f18a79fd56f9d8e568ccd5eb8d4ab27c Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 3 Apr 2013 13:44:00 +0200 Subject: [PATCH 034/458] Centcore migrate continue --- centreon/lib/perl/centreon/common/logger.pm | 13 +++ centreon/lib/perl/centreon/script/centcore.pm | 97 ++++++++++++------- 2 files changed, 74 insertions(+), 36 deletions(-) diff --git a/centreon/lib/perl/centreon/common/logger.pm b/centreon/lib/perl/centreon/common/logger.pm index 22611382df9..b13cfe613fd 100644 --- a/centreon/lib/perl/centreon/common/logger.pm +++ b/centreon/lib/perl/centreon/common/logger.pm @@ -45,6 +45,7 @@ sub new { filehandler => undef, # 0 = nothing, 1 = critical, 3 = info, 7 = debug severity => 3, + old_severity => 3, # 0 = stdout, 1 = file, 2 = syslog log_mode => 0, # syslog @@ -57,6 +58,9 @@ sub new { sub file_mode($$) { my ($self, $file) = @_; + if (defined($self->{filehandler})) { + $self->{filehandler}->close(); + } if (open($self->{filehandler}, ">>", $file)){ $self->{log_mode} = 1; $self->{filehandler}->autoflush(1); @@ -105,10 +109,17 @@ sub redirect_output { } } +sub set_default_severity { + my $self = shift; + + $self->{"severity"} = $self->{"old_severity"}; +} + # Getter/Setter Log severity sub severity { my $self = shift; if (@_) { + my $save_severity = $self->{"severity"}; if ($_[0] =~ /^[012347]$/) { $self->{"severity"} = $_[0]; } elsif ($_[0] eq "none") { @@ -121,7 +132,9 @@ sub severity { $self->{"severity"} = 7; } else { $self->writeLogError("Wrong severity value set."); + return -1; } + $self->{"old_severity"} = $save_severity; } return $self->{"severity"}; } diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index 4a2b0be0664..915f5a72f96 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -10,6 +10,7 @@ use centreon::common::db; use base qw(centreon::script); my %handlers = ('TERM' => {}, 'HUP' => {}, 'DIE' => {}); +use vars qw($centreon_config); sub new { my $class = shift; @@ -27,12 +28,13 @@ sub new { $self->{rsync} = "rsync"; $self->{rsyncWT} = $self->{rsync}; $self->{sudo} = "sudo"; - - $self->{ssh} .= " -o ConnectTimeout=$timeout -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; - $self->{rsync} .= " --timeout=$timeout "; - $self->{scp} .= " -o ConnectTimeout=$timeout -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; - $self->{timeout} = 5; + + $self->{ssh} .= " -o ConnectTimeout=$self->{timeout} -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; + $self->{rsync} .= " --timeout=$self->{timeout} "; + $self->{scp} .= " -o ConnectTimeout=$self->{timeout} -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; + + $self->{timeBetween2SyncPerf} = 60; $self->{perfdataSync} = 0; $self->{logSync} = 0; @@ -108,6 +110,31 @@ sub handle_DIE { $self->{logger}->writeLogInfo("Dont die..."); } +sub reload { + my $self = shift; + + if (defined $self->{log_file}) { + $self->{logger}->file_mode($self->{log_file}); + } + $self->{logger}->redirect_output(); + + # Get Config + unless (my $return = do $self->{config_file}) { + $self->{logger}->writeLogError("couldn't parse $file: $@") if $@; + $self->{logger}->writeLogError("couldn't do $file: $!") unless defined $return; + $self->{logger}->writeLogError("couldn't run $file") unless $return; + } else { + $self->{centreon_config} = $centreon_config; + } + + $self->{centreon_dbc}->disconnect(); + $self->{centreon_dbc}->db($self->{centreon_config}->{centreon_db}); + $self->{centreon_dbc}->host($self->{centreon_config}->{db_host}); + $self->{centreon_dbc}->user($self->{centreon_config}->{db_user}); + $self->{centreon_dbc}->password($self->{centreon_config}->{db_passwd}); + $self->{centreon_dbc}->port($self->{centreon_config}->{db_port}); +} + ########################################################### # Function to move command file on temporary file # @@ -143,7 +170,7 @@ sub GetAllNagiosServerPerfData { if ($self->{logSync} == 1) { $self->GetLogFile($data->{'id'}); } - getBrokerStats($data->{'id'}); + $self->getBrokerStats($data->{'id'}); } return 0; @@ -154,6 +181,7 @@ sub GetAllNagiosServerPerfData { ## fifo # sub getBrokerStats($) { + my $self = shift; my ($poller_id) = @_; my $port = ""; my $statPipe = "/tmp/.centreon-broker-stats.dat"; @@ -162,37 +190,34 @@ sub getBrokerStats($) { # Check Cache directory if (!-d $destFile) { - writeLogFile("Create data directory for broker-stats: $destFile"); + $self->{logger}->writeLogInfo("Create data directory for broker-stats: $destFile"); mkpath($destFile); } - # Check MySQL Configuration - CheckMySQLConnexion(); - - my $sth2 = $con->prepare("SELECT cbi.config_value FROM cfg_centreonbroker_info as cbi, cfg_centreonbroker as cb WHERE cb.config_id = cbi.config_id AND cbi.config_group = 'stats' AND cbi.config_key = 'fifo' AND cb.ns_nagios_server = '".$poller_id."'"); - if (!$sth2->execute()) { - writeLogFile("Error poller broker pipe : ".$sth2->errstr); - return ; + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT cbi.config_value FROM cfg_centreonbroker_info as cbi, cfg_centreonbroker as cb WHERE cb.config_id = cbi.config_id AND cbi.config_group = 'stats' AND cbi.config_key = 'fifo' AND cb.ns_nagios_server = '".$poller_id."'"); + if ($status == -1) { + $self->{logger}->writeLogError("Error poller broker pipe"); + return -1; } - while (my $data = $sth2->fetchrow_hashref()) { + while (my $data = $sth->fetchrow_hashref()) { # Get poller Configuration - $server_info = getServerConfig($poller_id); + $server_info = $self->getServerConfig($poller_id); $port = checkSSHPort($server_info->{'ssh_port'}); # Copy the stat file into a buffer - my $stdout = `$ssh -q $server_info->{'ns_ip_address'} -p $port 'cat \"$data->{'config_value'}" > $statPipe'`; - if (defined($stdout) && $stdout){ - writeLogFile("Result : $stdout\n"); + my $stdout = `$self->{ssh} -q $server_info->{'ns_ip_address'} -p $port 'cat \"$data->{'config_value'}" > $statPipe'`; + if (defined($stdout) && $stdout) { + $self->{logger}->writeLogInfo("Result : $stdout"); } # Get the stats file - $stdout = `$scp -P $port $server_info->{'ns_ip_address'}:$statPipe $destFile/broker-stats-$poller_id.dat >> /dev/null`; + $stdout = `$self->{scp} -P $port $server_info->{'ns_ip_address'}:$statPipe $destFile/broker-stats-$poller_id.dat >> /dev/null`; if (defined($stdout) && $stdout){ - writeLogFile("Result : $stdout\n"); + $self->{logger}->writeLogInfo("Result : $stdout"); } } - return; + return 0; } # ------------------- @@ -504,7 +529,7 @@ sub GetLogFile($) { if ($flag == 1) { # Get file with rsync - my $cmd = "$scp -P $port $distantconnexion:$distantlogfile $locallogfile > /dev/null"; + my $cmd = "$self->{scp} -P $port $distantconnexion:$distantlogfile $locallogfile > /dev/null"; `$cmd`; $self->{logger}->writeLogDebug($cmd); if ($? ne 0) { @@ -527,7 +552,6 @@ sub sendConfigFile($){ my $self = shift; # Init Values my $id = $_[0]; - my $debug = 0; my $cfg_dir = $self->getNagiosConfigurationField($id, "cfg_dir"); my $server_info = $self->getServerConfig($id); @@ -546,7 +570,7 @@ sub sendConfigFile($){ my $cmd = "$self->{scp} -P $port $origin $dest 2>&1"; my $stdout = `$cmd`; $self->{logger}->writeLogInfo("Result : $stdout"); - $self->{logger]->writeLogInfo("End: Send config files on poller $id"); + $self->{logger}->writeLogInfo("End: Send config files on poller $id"); # Send configuration for Centreon Broker if ( -e $self->{centreonDir} . "/filesGeneration/broker/".$id) { @@ -654,9 +678,9 @@ sub syncTraps($) { # synchronize Archives for all pollers my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `id` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); return if ($status == -1); - while (my $server = $sth2->fetchrow_hashref()) { + while (my $server = $sth->fetchrow_hashref()) { # Get configuration - my $ns_server = getServerConfig($server->{'id'}); + my $ns_server = $self->getServerConfig($server->{'id'}); my $port = checkSSHPort($ns_server->{'ssh_port'}); if ($id == 0) { @@ -876,10 +900,10 @@ sub checkDebugFlag { return -1 if ($status == -1); my $data = $sth->fetchrow_hashref(); if (defined($data->{'value'}) && $data->{'value'} == 1) { - $debug = 1; + $self->{logger}->severity("debug"); $self->{logger}->writeLogInfo("Enable Debug in Centcore"); } else { - $debug = 0; + $self->{logger}->set_default_severity(); $self->{logger}->writeLogInfo("Disable Debug in Centcore"); } return 0; @@ -905,16 +929,17 @@ sub run { $self->{logger}->writeLogInfo("Starting centcore engine..."); $self->{centreon_dbc} = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, - host => $self->{centreon_config}->{db_host}, - port => $self->{centreon_config}->{db_port}, - user => $self->{centreon_config}->{db_user}, - password => $self->{centreon_config}->{db_passwd}, - force => 0, - logger => $self->{logger}); + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 0, + logger => $self->{logger}); $self->checkDebugFlag(); while ($self->{stop}) { if ($self->{reload} == 0) { + $self->reload(); $self->{logger}->writeLogInfo("Reload in progress..."); } # Read Centcore.cmd @@ -972,7 +997,7 @@ sub run { $self->checkDebugFlag(); $self->GetAllNagiosServerPerfData(); - $timeSyncPerf = time(); + $self->{timeSyncPerf} = time(); } sleep(1); From 3c779437ec9f175646bd27b98ebc7583756fbaae Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 3 Apr 2013 14:02:24 +0200 Subject: [PATCH 035/458] Finish centcore migrate --- centreon/lib/perl/centreon/common/db.pm | 6 ++-- centreon/lib/perl/centreon/script/centcore.pm | 32 ++++++++----------- 2 files changed, 16 insertions(+), 22 deletions(-) diff --git a/centreon/lib/perl/centreon/common/db.pm b/centreon/lib/perl/centreon/common/db.pm index 5bc01354bf8..79d8cb66bae 100644 --- a/centreon/lib/perl/centreon/common/db.pm +++ b/centreon/lib/perl/centreon/common/db.pm @@ -19,7 +19,6 @@ sub new { ); my $self = {%defaults, %options}; - $self->{port} = 3306 if (!defined($self->{port})); $self->{"instance"} = undef; $self->{"type"} = "mysql"; $self->{"args"} = []; @@ -129,7 +128,7 @@ sub kill { my $rv = $self->{'instance'}->do("KILL QUERY " . $self->{'instance'}->{'mysql_thread_id'}); if (!$rv) { my ($package, $filename, $line) = caller; - $self->{'logger'}->writeLogError("MySQL error : " . $self->{'instance'}->errstr . " (caller: $package:$filename:$line)\n"); + $self->{'logger'}->writeLogError("MySQL error : " . $self->{'instance'}->errstr . " (caller: $package:$filename:$line)"); } } } @@ -141,6 +140,7 @@ sub connect() { my $status = 0; while (1) { + $self->{port} = 3306 if (!defined($self->{port})); $self->{"instance"} = DBI->connect( "DBI:".$self->{"type"} .":".$self->{"db"} @@ -155,7 +155,7 @@ sub connect() { } my ($package, $filename, $line) = caller; - $logger->writeLogError("MySQL error : cannot connect to database " . $self->{"db"} . ": " . $DBI::errstr . " (caller: $package:$filename:$line)\n"); + $logger->writeLogError("MySQL error : cannot connect to database " . $self->{"db"} . ": " . $DBI::errstr . " (caller: $package:$filename:$line)"); if ($self->{'force'} == 0) { $status = -1; last; diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index 915f5a72f96..f796ed61c97 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -120,9 +120,9 @@ sub reload { # Get Config unless (my $return = do $self->{config_file}) { - $self->{logger}->writeLogError("couldn't parse $file: $@") if $@; - $self->{logger}->writeLogError("couldn't do $file: $!") unless defined $return; - $self->{logger}->writeLogError("couldn't run $file") unless $return; + $self->{logger}->writeLogError("couldn't parse $self->{config_file}: $@") if $@; + $self->{logger}->writeLogError("couldn't do $self->{config_file}: $!") unless defined $return; + $self->{logger}->writeLogError("couldn't run $self->{config_file}") unless $return; } else { $self->{centreon_config} = $centreon_config; } @@ -236,17 +236,6 @@ sub getNagiosConfigurationField($$){ return $data->{$_[1]}; } -sub getLocalOptionsField($){ - CheckMySQLConnexion(); - my $sth2 = $con->prepare("SELECT `value` FROM `options` WHERE `key` LIKE '".$_[0]."' LIMIT 1"); - if (!$sth2->execute()) { - writeLogFile("Error when getting general options properties : ".$sth2->errstr); - } - my $data = $sth2->fetchrow_hashref(); - $sth2->finish(); - return $data->{'value'}; -} - sub getLocalServerID(){ my $self = shift; @@ -900,11 +889,15 @@ sub checkDebugFlag { return -1 if ($status == -1); my $data = $sth->fetchrow_hashref(); if (defined($data->{'value'}) && $data->{'value'} == 1) { - $self->{logger}->severity("debug"); - $self->{logger}->writeLogInfo("Enable Debug in Centcore"); + if (!$self->{logger}->is_debug()) { + $self->{logger}->severity("debug"); + $self->{logger}->writeLogInfo("Enable Debug in Centcore"); + } } else { - $self->{logger}->set_default_severity(); - $self->{logger}->writeLogInfo("Disable Debug in Centcore"); + if ($self->{logger}->is_debug()) { + $self->{logger}->set_default_severity(); + $self->{logger}->writeLogInfo("Disable Debug in Centcore"); + } } return 0; } @@ -939,8 +932,9 @@ sub run { while ($self->{stop}) { if ($self->{reload} == 0) { - $self->reload(); $self->{logger}->writeLogInfo("Reload in progress..."); + $self->reload(); + $self->{reload} = 1; } # Read Centcore.cmd if (-e $self->{cmdFile}) { From fb62861b26fc9e363775e90c84801bfee0a35b1c Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 3 Apr 2013 14:46:18 +0200 Subject: [PATCH 036/458] Migrate centFillTrapDB --- .../perl/centreon/script/centFillTrapDB.pm | 133 ++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 centreon/lib/perl/centreon/script/centFillTrapDB.pm diff --git a/centreon/lib/perl/centreon/script/centFillTrapDB.pm b/centreon/lib/perl/centreon/script/centFillTrapDB.pm new file mode 100644 index 00000000000..af9b68b9845 --- /dev/null +++ b/centreon/lib/perl/centreon/script/centFillTrapDB.pm @@ -0,0 +1,133 @@ + +package centreon::script::centFillTrapDB; + +use strict; +use warnings; +use centreon::script; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("centFillTrapDB", + centreon_db_conn => 0, + centstorage_db_conn => 0, + ); + + bless $self, $class; + $self->add_options( + "f=s" => \$self->{opt_f}, "file" => \$self->{opt_f}, + "m=s" => \$self->{opt_m}, "man=s" => \$self->{opt_m} + ); + return $self; +} + +######################################### +## TEST IF OID ALREADY EXISTS IN DATABASE +# +sub existsInDB { + my $self = shift; + my ($oid, $name) = @_; + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `traps_id` FROM `traps` WHERE `traps_oid` = " . $self->{centreon_dbc}->query($oid) . " AND `traps_name` = " . self->{centreon_dbc}->quote($name) . " LIMIT 1"); + if ($status == -1) { + return 0; + } + if (defined($sth->fetchrow_array())) { + return 1; + } + return 0; +} + +##################################### +## RETURN ENUM FROM STRING FOR STATUS +# +sub getStatus($$) { + my ($val, $name) = @_; + if ($val =~ /up/i) { + return 0; + } elsif ($val =~ /warning|degraded|minor/i) { + return 1; + } elsif ($val =~ /critical|major|failure|error|down/i) { + return 2; + }else { + if ($name =~ /normal|up/i || $name =~ /on$/i) { + return 0; + } elsif ($name =~ /warning|degraded|minor/i) { + return 1; + } elsif ($name =~ /critical|major|fail|error|down|bad/i | $name =~ /off|low$/i) { + return 2; + } + } + return 3; +} + +################ +## MAIN FUNCTION +# +sub main { + my $self = shift; + my $manuf = $self->{opt_m}; + + if (!open(FILE, $self->{opt_f})) { + $self->{logger}->writeLogError("Cannot open configuration file : $self->{opt_f}"); + exit(1); + } + my $last_oid = ""; + while () { + if ($_ =~ /^EVENT\ ([a-zA-Z0-9\_\-]+)\ ([0-9\.]+)\ (\"[A-Za-z\ \_\-]+\")\ ([a-zA-Z]+)/) { + my ($name,$oid,$type,$val) = ($1, $2, $3, $4); + if ($self->existsInDB($oid, $name)) { + $self->{logger}->writeLogInfo("Trap oid : $name => $oid already exists in database"); + $last_oid = $oid; + } else { + $val = getStatus($val,$name); + my ($status, $sth) = $self->{centreon_dbc}->query("INSERT INTO `traps` (`traps_name`, `traps_oid`, `traps_status`, `manufacturer_id`, `traps_submit_result_enable`) VALUES (" . $self->{centreon_dbc}->quote($name) . ", " . $self->{centreon_dbc}->quote($oid) . ", " . $self->{centreon_dbc}->quote($val) . ", " . $self->{centreon_dbc}->quote($manuf) . ", '1')"); + $last_oid = $oid; + } + } elsif ($_ =~/^FORMAT\ (.*)/ && $last_oid ne "") { + my ($status, $sth) = $self->{centreon_dbc}->query("UPDATE `traps` set `traps_args` = '$1' WHERE `traps_oid` = " . $self->{centreon_dbc}->quote($last_oid)); + } elsif ($_ =~ /^SDESC(.*)/ && $last_oid ne "") { + my $temp_val = $1; + my $desc = ""; + if (! ($temp_val =~ /\s+/)){ + $temp_val =~ s/\"/\\\"/g; + $temp_val =~ s/\'/\\\'/g; + $desc .= $temp_val; + } + my $found = 0; + while (!$found) { + my $line = ; + if ($line =~ /^EDESC/) { + $found = 1; + } else { + $line =~ s/\"/\\\"/g; + $line =~ s/\'/\\\'/g; + $desc .= $line; + } + } + if ($desc ne "") { + my ($status, $sth) = $self->{centreon_dbc}->query("UPDATE `traps` SET `traps_comments` = '$desc' WHERE `traps_oid` = " . $self->{centreon_dbc}->quote($last_oid)); + } + } + } +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + if (!defined($self->{opt_f}) || !defined($self->{opt_m})) { + $self->{logger}->writeLogError("Arguments missing."); + exit(1); + } + $self->{centreon_dbc} = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 0, + logger => $self->{logger}); + + $self->main(); + exit(0); +} \ No newline at end of file From 5b055436f47994c516f29e544976d02587604b8c Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 3 Apr 2013 14:50:50 +0200 Subject: [PATCH 037/458] Finish migration --- centreon/lib/perl/centreon/script/centFillTrapDB.pm | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centFillTrapDB.pm b/centreon/lib/perl/centreon/script/centFillTrapDB.pm index af9b68b9845..0ec2baf076f 100644 --- a/centreon/lib/perl/centreon/script/centFillTrapDB.pm +++ b/centreon/lib/perl/centreon/script/centFillTrapDB.pm @@ -28,7 +28,7 @@ sub new { sub existsInDB { my $self = shift; my ($oid, $name) = @_; - my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `traps_id` FROM `traps` WHERE `traps_oid` = " . $self->{centreon_dbc}->query($oid) . " AND `traps_name` = " . self->{centreon_dbc}->quote($name) . " LIMIT 1"); + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `traps_id` FROM `traps` WHERE `traps_oid` = " . $self->{centreon_dbc}->quote($oid) . " AND `traps_name` = " . $self->{centreon_dbc}->quote($name) . " LIMIT 1"); if ($status == -1) { return 0; } @@ -130,4 +130,6 @@ sub run { $self->main(); exit(0); -} \ No newline at end of file +} + +1; \ No newline at end of file From c892f17d53a8dd7673b6a23d558c80517a9383fe Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 3 Apr 2013 15:25:52 +0200 Subject: [PATCH 038/458] Migrate trapdforward --- .../lib/perl/centreon/script/centreontrapd.pm | 33 ++++--- .../centreon/script/centreontrapdforward.pm | 87 +++++++++++++++++++ .../lib/perl/centreon/script/centstorage.pm | 24 +++-- 3 files changed, 121 insertions(+), 23 deletions(-) create mode 100644 centreon/lib/perl/centreon/script/centreontrapdforward.pm diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 02790447be2..5837f95afa8 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -49,18 +49,7 @@ sub new { cmd_timeout => 10, centreon_user => "centreon" ); - - if (!defined($self->{opt_extra})) { - $self->{opt_extra} = "/etc/centreon/centreontrapd.pm"; - } - if (-f $self->{opt_extra}) { - require $self->{opt_extra}; - } else { - $self->{logger}->writeLogInfo("Can't find extra config file $self->{opt_extra}"); - } - - $self->{centreontrapd_config} = {%centreontrapd_default_config, %centreontrapd_config}; - + $self->{htmlentities} = 0; @{$self->{var}} = undef; # Variables of trap received by SNMPTRAPD @{$self->{entvar}} = undef; # Enterprise variable values of trap received by SNMPTRAPD @@ -82,17 +71,32 @@ sub new { # redefine to avoid out when we try modules $SIG{__DIE__} = undef; + return $self; +} + +sub init { + my $self = shift; + + if (!defined($self->{opt_extra})) { + $self->{opt_extra} = "/etc/centreon/centreontrapd.pm"; + } + if (-f $self->{opt_extra}) { + require $self->{opt_extra}; + } else { + $self->{logger}->writeLogInfo("Can't find extra config file $self->{opt_extra}"); + } + + $self->{centreontrapd_config} = {%centreontrapd_default_config, %centreontrapd_config}; + # Daemon Only if ($self->{centreontrapd_config}->{daemon} == 1) { $self->set_signal_handlers; } - return $self; } sub set_signal_handlers { my $self = shift; - $SIG{TERM} = \&class_handle_TERM; $handlers{TERM}->{$self} = sub { $self->handle_TERM() }; $SIG{HUP} = \&class_handle_HUP; @@ -519,6 +523,7 @@ sub run { my $self = shift; $self->SUPER::run(); + $self->init(); $self->{logger}->redirect_output(); ($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}) = diff --git a/centreon/lib/perl/centreon/script/centreontrapdforward.pm b/centreon/lib/perl/centreon/script/centreontrapdforward.pm new file mode 100644 index 00000000000..03c8226f27d --- /dev/null +++ b/centreon/lib/perl/centreon/script/centreontrapdforward.pm @@ -0,0 +1,87 @@ + +package centreon::script::centreontrapdforward; + +use strict; +use warnings; +use Time::HiRes qw(gettimeofday); +use centreon::script; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("centreontrapdforward", + centreon_db_conn => 0, + centstorage_db_conn => 0, + noconfig => 1 + ); + bless $self, $class; + $self->add_options( + "config-extra" => \$self->{opt_extra}, + ); + my %centreontrapd_default_config = + ( + spool_directory => "/var/spool/centreontrapd/" + ) + ); + return $self; +} + +sub init { + my $self = shift; + + if (!defined($self->{opt_extra})) { + $self->{opt_extra} = "/etc/centreon/centreontrapd.pm"; + } + if (-f $self->{opt_extra}) { + require $self->{opt_extra}; + } else { + $self->{logger}->writeLogInfo("Can't find extra config file $self->{opt_extra}"); + } + + $self->{centreontrapd_config} = {%centreontrapd_default_config, %centreontrapd_config}; +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + $self->init(); + + # Create file in spool directory based on current time + my ($s, $usec) = gettimeofday; + + # Pad the numbers with 0's to make sure they are all the same length. Sometimes the + # usec is shorter than 6. + my $s_pad = sprintf("%09d",$s); + my $usec_pad = sprintf("%06d",$usec); + + # Print out time + $self->{logger}->writeLogDebug("centreon-trapforward started: " . scalar(localtime)); + $self->{logger}->writeLogDebug("s = $s, usec = $usec"); + $self->{logger}->writeLogDebug("s_pad = $s_pad, usec_pad = $usec_pad"); + $self->{logger}->writeLogDebug("Data received:"); + + my $spoolfile = $self->{centreontrapd_config}->{spool_directory} . '#centreon-trap-'.$s_pad.$usec_pad; + + unless (open SPOOL, ">$spoolfile") { + $self->{logger}->writeLogError("Could not write to file file $spoolfile! Trap will be lost!"); + exit(1); + } + + print SPOOL time()."\n"; + + while (defined(my $line = <>)) { + print SPOOL $line; + + if ($self->{logger}->is_debug()) { + # Print out item passed from snmptrapd + chomp $line; + $self->{logger}->writeLogDebug($line); + } + } + + exit(0); +} + +1; \ No newline at end of file diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index 4c5d00fa763..7743824e7f7 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -56,19 +56,24 @@ sub new { centreon_23_compatibility => 0, perfdata_parser_stop => 1 ); - - if (defined($self->{opt_extra})) { + + $self->set_signal_handlers; + + return $self; +} + +sub init { + my $self = shift; + + if (!defined($self->{opt_extra})) { + $self->{opt_extra} = "/etc/centreon/centstorage.pm"; + } + if (-f $self->{opt_extra}) { require $self->{opt_extra}; } else { - if (-f "/etc/centreon/centstorage.pm") { - require "/etc/centreon/centstorage.pm"; - } + $self->{logger}->writeLogInfo("Can't find extra config file $self->{opt_extra}"); } $self->{centstorage_config} = {%centstorage_default_config, %centstorage_config}; - - $self->set_signal_handlers; - - return $self; } sub set_signal_handlers { @@ -329,6 +334,7 @@ sub run { my $self = shift; $self->SUPER::run(); + $self->init(); $self->{logger}->redirect_output(); #### From 9508595e2d3a78d35e4152597af739fed56d6098 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 3 Apr 2013 15:36:06 +0200 Subject: [PATCH 039/458] Migrate trapdforward done --- centreon/lib/perl/centreon/script/centreontrapd.pm | 5 +++-- .../lib/perl/centreon/script/centreontrapdforward.pm | 9 +++++---- centreon/lib/perl/centreon/script/centstorage.pm | 5 +++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 5837f95afa8..0bb678ca96e 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -24,7 +24,7 @@ sub new { "config-extra" => \$self->{opt_extra}, ); - my %centreontrapd_default_config = + %{$self->{centreontrapd_default_config}} = ( daemon => 0, spool_directory => "/var/spool/centreontrapd/", @@ -76,6 +76,7 @@ sub new { sub init { my $self = shift; + $self->SUPER::init(); if (!defined($self->{opt_extra})) { $self->{opt_extra} = "/etc/centreon/centreontrapd.pm"; @@ -86,7 +87,7 @@ sub init { $self->{logger}->writeLogInfo("Can't find extra config file $self->{opt_extra}"); } - $self->{centreontrapd_config} = {%centreontrapd_default_config, %centreontrapd_config}; + $self->{centreontrapd_config} = {%{$self->{centreontrapd_default_config}}, %centreontrapd_config}; # Daemon Only if ($self->{centreontrapd_config}->{daemon} == 1) { diff --git a/centreon/lib/perl/centreon/script/centreontrapdforward.pm b/centreon/lib/perl/centreon/script/centreontrapdforward.pm index 03c8226f27d..33863efcd43 100644 --- a/centreon/lib/perl/centreon/script/centreontrapdforward.pm +++ b/centreon/lib/perl/centreon/script/centreontrapdforward.pm @@ -7,6 +7,7 @@ use Time::HiRes qw(gettimeofday); use centreon::script; use base qw(centreon::script); +use vars qw(%centreontrapd_config); sub new { my $class = shift; @@ -19,17 +20,17 @@ sub new { $self->add_options( "config-extra" => \$self->{opt_extra}, ); - my %centreontrapd_default_config = + %{$self->{centreontrapd_default_config}} = ( spool_directory => "/var/spool/centreontrapd/" - ) ); return $self; } sub init { my $self = shift; - + $self->SUPER::init(); + if (!defined($self->{opt_extra})) { $self->{opt_extra} = "/etc/centreon/centreontrapd.pm"; } @@ -39,7 +40,7 @@ sub init { $self->{logger}->writeLogInfo("Can't find extra config file $self->{opt_extra}"); } - $self->{centreontrapd_config} = {%centreontrapd_default_config, %centreontrapd_config}; + $self->{centreontrapd_config} = {%{$self->{centreontrapd_default_config}}, %centreontrapd_config}; } sub run { diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index 7743824e7f7..0720220e862 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -47,7 +47,7 @@ sub new { $self->{rebuild_progress} = 0; $self->{rebuild_pool_choosen} = 0; - my %centstorage_default_config = + %{$self->{centstorage_default_config}} = ( pool_childs => 4, TIMEOUT => 60, @@ -64,6 +64,7 @@ sub new { sub init { my $self = shift; + $self->SUPER::init(); if (!defined($self->{opt_extra})) { $self->{opt_extra} = "/etc/centreon/centstorage.pm"; @@ -73,7 +74,7 @@ sub init { } else { $self->{logger}->writeLogInfo("Can't find extra config file $self->{opt_extra}"); } - $self->{centstorage_config} = {%centstorage_default_config, %centstorage_config}; + $self->{centstorage_config} = {%{$self->{centstorage_default_config}}, %centstorage_config}; } sub set_signal_handlers { From e2232147005d06e61e023433d0ce9af1c590fd8f Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 3 Apr 2013 15:55:40 +0200 Subject: [PATCH 040/458] Migrate PurgeLogs --- .../lib/perl/centreon/script/purgeLogs.pm | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 centreon/lib/perl/centreon/script/purgeLogs.pm diff --git a/centreon/lib/perl/centreon/script/purgeLogs.pm b/centreon/lib/perl/centreon/script/purgeLogs.pm new file mode 100644 index 00000000000..c06fc19d45d --- /dev/null +++ b/centreon/lib/perl/centreon/script/purgeLogs.pm @@ -0,0 +1,84 @@ + +package centreon::script::purgeLogs; + +use strict; +use warnings; +use centreon::script; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("purgeLogs", + centreon_db_conn => 1, + centstorage_db_conn => 1 + ); + bless $self, $class; + + return $self; +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + + # Get conf Data + my $logRetention; + my $reportingRetention; + my ($status, $sth_config) = $self->{csdb}->query("SELECT `archive_retention`, `reporting_retention` FROM `config` LIMIT 1"); + if ($status != -1) { + my $data = $sth_config->fetchrow_hashref(); + $logRetention = $data->{'archive_retention'}; + $reportingRetention = $data->{'reporting_retention'}; + } + + ################################ + # Get broker + my $broker = "ndo"; + ($status, $sth_config) = $self->{csdb}->query("SELECT `value` FROM `options` WHERE `key` = 'broker' LIMIT 1"); + if ($status != -1) { + my $data = $sth_config->fetchrow_hashref(); + $broker = $data->{'value'}; + } + + #################################################### + # Logs Data purge + if (defined($logRetention) && $logRetention ne 0){ + my $last_log = time() - ($logRetention * 24 * 60 * 60); + + # Purge Log Database + if ($broker eq "ndo") { + $self->{logger}->writeLogInfo("Begin centstorage.log purge"); + $self->{csdb}->query("DELETE FROM `log` WHERE `ctime` < '$last_log'"); + $self->{logger}->writeLogInfo("End centstorage.log purge"); + } else { + $self->{logger}->writeLogInfo("Begin centstorage.logs purge"); + $self->{csdb}->query("DELETE FROM `logs` WHERE `ctime` < '$last_log'"); + $self->{logger}->writeLogInfo("End centstorage.logs purge"); + } + } + + #################################################### + # Reporting Data purge + if (defined($reportingRetention) && $reportingRetention ne 0){ + my $last_log = time() - ($reportingRetention * 24 * 60 * 60); + + $self->{logger}->writeLogInfo("Begin log_archive table purge"); + $self->{csdb}->query("DELETE FROM `log_archive_host` WHERE `date_end` < '$last_log'"); + $self->{csdb}->query("DELETE FROM `log_archive_service` WHERE `date_end` < '$last_log'"); + $self->{logger}->writeLogInfo("End log_archive table purge"); + } + + exit(0); +} + +1; + +__END__ + +=head1 NAME + + sample - Using GetOpt::Long and Pod::Usage + +=cut From a43161684811f6eecaea68554fd4293af77aa82f Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 3 Apr 2013 16:15:09 +0200 Subject: [PATCH 041/458] New script to purge (remove old ones). And purgeComments not needed --- .../lib/perl/centreon/script/purgeLogs.pm | 84 ------------------- 1 file changed, 84 deletions(-) delete mode 100644 centreon/lib/perl/centreon/script/purgeLogs.pm diff --git a/centreon/lib/perl/centreon/script/purgeLogs.pm b/centreon/lib/perl/centreon/script/purgeLogs.pm deleted file mode 100644 index c06fc19d45d..00000000000 --- a/centreon/lib/perl/centreon/script/purgeLogs.pm +++ /dev/null @@ -1,84 +0,0 @@ - -package centreon::script::purgeLogs; - -use strict; -use warnings; -use centreon::script; - -use base qw(centreon::script); - -sub new { - my $class = shift; - my $self = $class->SUPER::new("purgeLogs", - centreon_db_conn => 1, - centstorage_db_conn => 1 - ); - bless $self, $class; - - return $self; -} - -sub run { - my $self = shift; - - $self->SUPER::run(); - - # Get conf Data - my $logRetention; - my $reportingRetention; - my ($status, $sth_config) = $self->{csdb}->query("SELECT `archive_retention`, `reporting_retention` FROM `config` LIMIT 1"); - if ($status != -1) { - my $data = $sth_config->fetchrow_hashref(); - $logRetention = $data->{'archive_retention'}; - $reportingRetention = $data->{'reporting_retention'}; - } - - ################################ - # Get broker - my $broker = "ndo"; - ($status, $sth_config) = $self->{csdb}->query("SELECT `value` FROM `options` WHERE `key` = 'broker' LIMIT 1"); - if ($status != -1) { - my $data = $sth_config->fetchrow_hashref(); - $broker = $data->{'value'}; - } - - #################################################### - # Logs Data purge - if (defined($logRetention) && $logRetention ne 0){ - my $last_log = time() - ($logRetention * 24 * 60 * 60); - - # Purge Log Database - if ($broker eq "ndo") { - $self->{logger}->writeLogInfo("Begin centstorage.log purge"); - $self->{csdb}->query("DELETE FROM `log` WHERE `ctime` < '$last_log'"); - $self->{logger}->writeLogInfo("End centstorage.log purge"); - } else { - $self->{logger}->writeLogInfo("Begin centstorage.logs purge"); - $self->{csdb}->query("DELETE FROM `logs` WHERE `ctime` < '$last_log'"); - $self->{logger}->writeLogInfo("End centstorage.logs purge"); - } - } - - #################################################### - # Reporting Data purge - if (defined($reportingRetention) && $reportingRetention ne 0){ - my $last_log = time() - ($reportingRetention * 24 * 60 * 60); - - $self->{logger}->writeLogInfo("Begin log_archive table purge"); - $self->{csdb}->query("DELETE FROM `log_archive_host` WHERE `date_end` < '$last_log'"); - $self->{csdb}->query("DELETE FROM `log_archive_service` WHERE `date_end` < '$last_log'"); - $self->{logger}->writeLogInfo("End log_archive table purge"); - } - - exit(0); -} - -1; - -__END__ - -=head1 NAME - - sample - Using GetOpt::Long and Pod::Usage - -=cut From 64b8363f95912188f4c0215d5eed39f4857f4af5 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 3 Apr 2013 17:31:38 +0200 Subject: [PATCH 042/458] First version migrate LogAnalyserBroker --- .../perl/centreon/script/logAnalyserBroker.pm | 324 ++++++++++++++++++ 1 file changed, 324 insertions(+) create mode 100644 centreon/lib/perl/centreon/script/logAnalyserBroker.pm diff --git a/centreon/lib/perl/centreon/script/logAnalyserBroker.pm b/centreon/lib/perl/centreon/script/logAnalyserBroker.pm new file mode 100644 index 00000000000..5a87aa477a1 --- /dev/null +++ b/centreon/lib/perl/centreon/script/logAnalyserBroker.pm @@ -0,0 +1,324 @@ +package centreon::script::logAnalyserBroker; + +use strict; +use warnings; +use centreon::script; + +use base qw(centreon::script); + +my %svc_status_code = ( + "OK" => 0, + "WARNING" => 1, + "CRITICAL" => 2, + "UNKNOWN" => 3 +); +my %host_status_code = ( + "UP" => 0, + "DOWN" => 1, + "UNREACHABLE" => 2, + "PENDING" => 4 +); +my %type_code = ( + "SOFT" => 0, + "HARD" => 1 +); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("logAnalyserBroker", + centreon_db_conn => 1, + centstorage_db_conn => 1, + noroot => 1 + ); + + bless $self, $class; + $self->add_options( + "p=s" => \$self->{opt_p}, "poller" => \$self->{opt_p}, + "s=s" => \$self->{opt_s}, "startdate=s" => \$self->{opt_s} + ); + $self->{launch_time} = time(); + $self->{msg_type5_disabled} = 0; + $self->{queries_per_transaction} = 500; + + %{$self->{cache_host}} = (); + %{$self->{cache_host_service}} = (); + $self->{current_time} = time(); + $self->{retention_time} = undef; + return $self; +} + +# Get poller id from poller name +sub getPollerId($) { + my $self = shift; + my $instanceName = $_[0]; + + my ($status, $sth) = $self->{cdb}->query("SELECT id + FROM nagios_server + WHERE name = " . $self->{cdb}->quote($instanceName) . " + AND ns_activate = '1' LIMIT 1"); + die ("Can't get poller id") if ($status == -1); + while ((my $row = $sth->fetchrow_hashref())) { + return $row->{'id'}; + } + return 0; +} + +sub commit_to_log { + my ($self, $sth, $log_table_rows) = @_; + my @tuple_status; + + $sth->execute_for_fetch(sub { shift @$log_table_rows }, \@tuple_status); + $self->{csdb}->commit; + $self->{csdb}->transaction_mode(1); +} + +# Parsing .log +sub parseFile($$) { + my $self = shift; + my $instance_name = $_[1]; + my $logFile = $_[0]; + my $ctime; + my ($nbqueries, $counter) = (0, 0, 0); + my @log_table_rows; + + # Open Log File for parsing + if (!open (FILE, $_[0])){ + $self->{logger}->writeLogError("Cannot open file : $_[0]"); + return; + } + + $self->{csdb}->transaction_mode(1); + eval { + my $sth = $self->{csdb}->{instance}->prepare(<<"EOQ"); +INSERT INTO log (ctime, host_name, service_description, status, output, notification_cmd, notification_contact, type, retry, msg_type, instance, host_id, service_id) +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) +EOQ + + while () { + my $cur_ctime; + + if ($_ =~ m/^\[([0-9]*)\]\sSERVICE ALERT\:\s(.*)$/) { + my @tab = split(/;/, $2); + next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})); + $cur_ctime = $1; + push @log_table_rows, + [($cur_ctime, $tab[0], $tab[1], $svc_status_code{$tab[2]}, $tab[5], '', '', $type_code{$tab[3]}, $tab[4], '0', $instance_name, $cache_host{$tab[0]}, $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})]; + } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST ALERT\:\s(.*)$/) { + my @tab = split(/;/, $2); + next if (!defined($cache_host{$tab[0]})); + $cur_ctime = $1; + push @log_table_rows, + [($cur_ctime, $tab[0], '', $host_status_code{$tab[1]}, $tab[4], '', '', $type_code{$tab[2]}, $tab[3], '1', $instance_name, $cache_host{$tab[0]}, '')]; + } elsif ($_ =~ m/^\[([0-9]*)\]\sSERVICE NOTIFICATION\:\s(.*)$/) { + my @tab = split(/;/, $2); + next if (!defined($cache_host_service{$tab[1] . ":" . $tab[2]}->{'service_id'})); + $cur_ctime = $1; + push @log_table_rows, + [($cur_ctime, $tab[1], $tab[2], $svc_status_code{$tab[3]}, $tab[5], $tab[4], $tab[0], '', 0, '2', $instance_name, $cache_host{$tab[1]}, $cache_host_service{$tab[1] . ":" . $tab[2]}->{'service_id'})]; + } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST NOTIFICATION\:\s(.*)$/) { + my @tab = split(/;/, $2); + next if (!defined($cache_host{$tab[1]})); + $cur_ctime = $1; + push @log_table_rows, + [($cur_ctime, $tab[1], '', $host_status_code{$tab[2]}, $tab[4], $tab[3], $tab[0], '', 0, '3', $instance_name, $cache_host{$tab[1]}, '')]; + } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sHOST\sSTATE\:\s(.*)$/) { + my @tab = split(/;/, $2); + next if (!defined($cache_host{$tab[0]})); + $cur_ctime = $1; + push @log_table_rows, + [($cur_ctime, $tab[0], '', $host_status_code{$tab[1]}, '', '', '', $type_code{$tab[2]}, 0, '7', $instance_name, $cache_host{$tab[0]}, '')]; + } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sSERVICE\sSTATE\:\s(.*)$/) { + my @tab = split(/;/, $2); + next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})); + $cur_ctime = $1; + push @log_table_rows, + [($cur_ctime, $tab[0], $tab[1], $svc_status_code{$tab[2]}, '', '', '', $type_code{$tab[3]}, 0, '6', $instance_name, $cache_host{$tab[0]}, $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})]; + } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sHOST\sSTATE\:\s(.*)$/) { + my @tab = split(/;/, $2); + next if (!defined($cache_host{$tab[0]})); + $cur_ctime = $1; + push @log_table_rows, + [($cur_ctime, $tab[0], '', $host_status_code{$tab[1]}, '', '', '', $type_code{$tab[2]}, 0, '9', $instance_name, $cache_host{$tab[0]}, '')]; + } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sSERVICE\sSTATE\:\s(.*)$/) { + my @tab = split(/;/, $2); + next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})); + $cur_ctime = $1; + push @log_table_rows, + [($cur_ctime, $tab[0], $tab[1], $svc_status_code{$tab[2]}, '', '', '', $type_code{$tab[3]}, 0, '8', $instance_name, $cache_host{$tab[0]}, $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})]; + } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_SVC\_PROBLEM\;(.*)$/) { + $cur_ctime = $1; + my @tab = split(/;/, $2); + next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})); + push @log_table_rows, + [($cur_ctime, $tab[0], $tab[1], '', $tab[6], '', $tab[5], '', 0, '10', $instance_name, $cache_host{$tab[0]}, $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})]; + } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_HOST\_PROBLEM\;(.*)$/) { + $cur_ctime = $1; + my @tab = split(/;/, $2); + next if (!defined($cache_host{$tab[0]})); + push @log_table_rows, + [($cur_ctime, $tab[0], '', '', $tab[5], '', $tab[4], '', 0, '11', $instance_name, $cache_host{$tab[0]}, '')]; + } elsif ($_ =~ m/^\[([0-9]*)\]\sWarning\:\s(.*)$/) { + my $tab = $2; + $cur_ctime = $1; + push @log_table_rows, + [($cur_ctime, '', '', '', $tab, '', '', '', 0, '4', $instance_name, '', '')]; + } elsif ($_ =~ m/^\[([0-9]*)\]\s(.*)$/ && (!$self->{msg_type5_disabled})) { + $cur_ctime = $1; + my $tab = $2; + push @log_table_rows, + [($cur_ctime, '', '', '', $tab, '', '', '', 0, '5', $instance_name, '', '')]; + } + $counter++; + $nbqueries++; + if ($nbqueries == $self->{queries_per_transaction}) { + $self->commit_to_log($sth, \@log_table_rows); + $nbqueries = 0; + @log_table_rows = (); + } + } + $self->commit_to_log($sth, \@log_table_rows); + }; + close FILE; + if ($@) { + $self->{csdb}->rollback; + die "Database error: $@"; + } + $self->{csdb}->transaction_mode(0); +} + +=head2 date_to_time($date) + +Convert $date to a timestamp. + +=cut +sub date_to_time($) { + my $date = shift; + + $date =~ s|-|/|g; + return int(`date -d $date +%s`); +} + +sub parseArchive { + my $self = shift; + my ($instance) = @_; + my $archives; + + # Get instance name + my ($status, $sth) = $self->{cdb}->query("SELECT localhost, id, name FROM `nagios_server` WHERE id = " . $instance); + if ($status == -1) { + die "Can't get information on poller"; + } + my $tmp_server = $sth->fetchrow_hashref(); + + if ($tmp_server->{'localhost'}) { + ($status, $sth) = $self->{cdb}->query("SELECT `log_archive_path` + FROM `cfg_nagios`, `nagios_server` + WHERE `nagios_server_id` = '$instance' + AND `nagios_server`.`id` = `cfg_nagios`.`nagios_server_id` + AND `nagios_server`.`ns_activate` = '1' + AND `cfg_nagios`.`nagios_activate` = '1' LIMIT 1"); + if ($status == -1) { + die "Can't get information on poller"; + } + $data = $sth->fetchrow_hashref(); + if (!$data->{'log_archive_path'}) { + die "Could not find local var log directory"; + } + $archives = $data->{'log_archive_path'}; + } else { + $archives = $self->{centreon_config}->{VarLib} . "/log/$instance/archives/"; + } + + my @log_files = split /\s/,`ls $archives`; + foreach (@log_files) { + $self->parseFile($archives.$_, $tmp_server->{'name'}); + } +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + + if (defined($opt_s)) { + if ($opt_s !~ m/\d{2}-\d{2}-\d{4}/) { + $self->{logger}->writeLogError("Invalid start date provided"); + exit 1; + } + } + + # Get conf Data + my ($status, $sth_config) = $self->{csdb}->query("SELECT `archive_log`, `archive_retention`, `nagios_log_file` FROM `config` LIMIT 1"); + die("Cannot get archive log path") if ($status == -1); + $data = $sth_config->fetchrow_hashref(); + die("Cannot get archive log path") if (!$data->{'archive_log'}); + + my $retention = $data->{'archive_retention'}; + + my ($day,$month,$year) = (localtime(time()))[3,4,5]; + $self->{retention_time} = mktime(0,0,0,$day-$retention,$month,$year,0,0,-1); + + # Get cache + my $filter_instance = ""; + my $instanceId; + if (defined($self->{opt_p})) { + $instanceId = $self->getPollerId($self->{opt_p}); + if ($instanceId == 0) { + $self->{logger}->writeLogError("Unknown poller $self->{opt_p}"); + die("Unknown poller $self->{opt_p}"); + } + $filter_instance = "ns_host_relation.nagios_server_id = $instanceId AND "; + } + + ($status, my $sth_cache) = $self->{cdb}->query("SELECT host.host_id, host.host_name FROM host, ns_host_relation WHERE ${filter_instance}ns_host_relation.host_host_id = host.host_id AND host.host_activate = '1'"); + die("Cannot get host cache") if ($status == -1); + while ((my $tmp_cache = $sth_cache->fetchrow_hashref())) { + $self->{cache_host}{$tmp_cache->{'host_name'}} = $tmp_cache->{'host_id'}; + } + + ($status, $sth_cache) = $self->{cdb}->query("SELECT host.host_name, host.host_id, service.service_id, service.service_description FROM host, host_service_relation, service, ns_host_relation WHERE ${filter_instance}ns_host_relation.host_host_id = host.host_id AND host.host_id = host_service_relation.host_host_id AND host_service_relation.service_service_id = service.service_id AND service.service_activate = '1'"); + die("Cannot get service cache") if ($status == -1); + while ((my $tmp_cache = $sth_cache->fetchrow_hashref())) { + $self->{cache_host_service}{$tmp_cache->{'host_name'} . ':' . $tmp_cache->{'service_description'}} = {'host_id' => $tmp_cache->{'host_id'}, 'service_id' => $tmp_cache->{'service_id'}}; + } + + ($status, $sth_cache) = $self->{cdb}->query("SELECT host.host_name, host.host_id, service.service_id, service.service_description FROM host, host_service_relation, hostgroup_relation, service, ns_host_relation WHERE ${filter_instance}ns_host_relation.host_host_id = host.host_id AND host.host_id = hostgroup_relation.host_host_id AND hostgroup_relation.hostgroup_hg_id = host_service_relation.hostgroup_hg_id AND host_service_relation.service_service_id = service.service_id AND service.service_activate = '1'"); + die("Cannot get service by hostgroup cache") if ($status == -1); + while ((my $tmp_cache = $sth_cache->fetchrow_hashref())) { + $self->{cache_host_service}{$tmp_cache->{'host_name'} . ':' . $tmp_cache->{'service_description'}} = {'host_id' => $tmp_cache->{'host_id'}, 'service_id' => $tmp_cache->{'service_id'}}; + } + + if (defined($self->{opt_p}) && $instanceId) { + if (!defined($self->{opt_s})) { + $self->{csdb}->query("DELETE FROM `logs` WHERE instance_name = '$opt_p' AND `ctime` < $current_time"); + } else { + my $limit = date_to_time($self->{opt_s}); + if ($limit > $self->{retention_time}) { + $self->{retention_time} = $limit; + } + $self->{csdb}->query("DELETE FROM `logs` WHERE `ctime` >= $limit AND `ctime` < $current_time"); + } + $self->parseArchive($instanceId); + } else { + my ($status, $sth) = $self->{cdb}->query("SELECT `id`, `name`, `localhost` FROM `nagios_server` WHERE `ns_activate` = 1"); + if ($status == -1) { + die("Can't get poller list"); + } + while (my $ns_server = $sth->fetchrow_hashref()) { + if (!defined $opt_s) { + $self->{csdb}->query("DELETE FROM `logs` WHERE `ctime` < $current_time"); + } else { + my $limit = date_to_time($self->{opt_s}); + if ($limit > $self->{retention_time}) { + $self->{retention_time} = $limit; + } + $res = $self->{csdb}->query("DELETE FROM `logs` WHERE `ctime` >= $limit AND `ctime` < $current_time"); + } + $self->parseArchive($ns_server->{'id'}); + } + } + + $self->{logger}->writeLogInfo("Done"); +} + +1; \ No newline at end of file From 22bea68d46a4a4957b5acd6d2536a60ec15562a8 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 4 Apr 2013 10:06:40 +0200 Subject: [PATCH 043/458] Migrate some misc scripts --- .../centreon/script/centreonSyncArchives.pm | 52 ++++++++++++++++ .../centreon/script/centreonSyncPlugins.pm | 61 +++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 centreon/lib/perl/centreon/script/centreonSyncArchives.pm create mode 100644 centreon/lib/perl/centreon/script/centreonSyncPlugins.pm diff --git a/centreon/lib/perl/centreon/script/centreonSyncArchives.pm b/centreon/lib/perl/centreon/script/centreonSyncArchives.pm new file mode 100644 index 00000000000..72850ea8372 --- /dev/null +++ b/centreon/lib/perl/centreon/script/centreonSyncArchives.pm @@ -0,0 +1,52 @@ + +package centreon::script::centreonSyncArchives; + +use strict; +use warnings; +use centreon::script; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("centreonSyncArchives", + centreon_db_conn => 0, + centstorage_db_conn => 0 + ); + bless $self, $class; + $self->{rsync} = "rsync"; + return $self; +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + my $cdb = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 0, + logger => $self->{logger}); + my ($status, $sth) = $cdb->query("SELECT nagios_server.id, nagios_server.ns_ip_address, cfg_nagios.log_archive_path FROM nagios_server, cfg_nagios + WHERE nagios_server.ns_activate = '1' AND nagios_server.localhost = '0' AND nagios_server.id = cfg_nagios.ns_server_id"); + die("Error SQL Quit") if ($status == -1); + while ((my $data = $sth->fetchrow_hashref())) { + if (defined($data->{log_archive_path}) && $data->{log_archive_path} ne '') { + `$self->{rsync} -c $ns_server->{'ns_ip_address'}:$data->{'log_archive_path'}/* $self->{centreon_config}->{VarLib}/log/$ns_server->{'id'}/archives/`; + } else { + $self->{logger}->writeLogError("Can't get archive path for service " . $ns_server->{'id'} . " (" . $ns_server->{'ns_address_ip'} . ")"); + } + } +} + +1; + +__END__ + +=head1 NAME + + sample - Using GetOpt::Long and Pod::Usage + +=cut diff --git a/centreon/lib/perl/centreon/script/centreonSyncPlugins.pm b/centreon/lib/perl/centreon/script/centreonSyncPlugins.pm new file mode 100644 index 00000000000..1f3b237778d --- /dev/null +++ b/centreon/lib/perl/centreon/script/centreonSyncPlugins.pm @@ -0,0 +1,61 @@ + +package centreon::script::centreonSyncPlugins; + +use strict; +use warnings; +use centreon::script; + +use base qw(centreon::script); + +sub new { + my $class = shift; + my $self = $class->SUPER::new("centreonSyncPlugins", + centreon_db_conn => 0, + centstorage_db_conn => 0 + ); + bless $self, $class; + $self->{rsync} = "rsync"; + return $self; +} + +sub run { + my $self = shift; + + $self->SUPER::run(); + my $cdb = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 0, + logger => $self->{logger}); + my ($status, $sth) = $cdb->query("SELECT `value` FROM `options` WHERE `key` LIKE 'nagios_path_plugins' LIMIT 1"); + die("Error SQL Quit") if ($status == -1); + my $data = $sth->fetchrow_hashref(); + if (!defined($data->{value}) || $data->{value} eq '') { + $self->{logger}->writeLogError("Plugin path is not set."); + die("Quit"); + } + my $path_plugins = $data->{value}; + + ($status, $sth) = $cdb->query("SELECT `id`, `ns_ip_address` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); + die("Error SQL Quit") if ($status == -1); + while ((my $data = $sth->fetchrow_hashref())) { + my $ls = `$self->{ssh} -q $ns_server->{'ns_ip_address'} ls -l $path_plugins/ 2>> /dev/null | wc -l`; + if ($ls > 1) { + `$self->{rsync} -prc $path_plugins/* $ns_server->{'ns_ip_address'}:$path_plugins/`; + } else { + $self->{logger}->writeLogError("Directory not present on remote server : " . $ns_server->{'ns_ip_address'}); + } + } +} + +1; + +__END__ + +=head1 NAME + + sample - Using GetOpt::Long and Pod::Usage + +=cut \ No newline at end of file From 892a6d1a9a66d871aab38c64d8a9cad73c798315 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 4 Apr 2013 10:17:22 +0200 Subject: [PATCH 044/458] Fix error scripts --- .../centreon/script/centreonSyncArchives.pm | 4 +- .../centreon/script/centreonSyncPlugins.pm | 6 +- .../perl/centreon/script/logAnalyserBroker.pm | 58 +++++++++---------- 3 files changed, 34 insertions(+), 34 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreonSyncArchives.pm b/centreon/lib/perl/centreon/script/centreonSyncArchives.pm index 72850ea8372..1bc99125ae1 100644 --- a/centreon/lib/perl/centreon/script/centreonSyncArchives.pm +++ b/centreon/lib/perl/centreon/script/centreonSyncArchives.pm @@ -34,9 +34,9 @@ sub run { die("Error SQL Quit") if ($status == -1); while ((my $data = $sth->fetchrow_hashref())) { if (defined($data->{log_archive_path}) && $data->{log_archive_path} ne '') { - `$self->{rsync} -c $ns_server->{'ns_ip_address'}:$data->{'log_archive_path'}/* $self->{centreon_config}->{VarLib}/log/$ns_server->{'id'}/archives/`; + `$self->{rsync} -c $data->{'ns_ip_address'}:$data->{'log_archive_path'}/* $self->{centreon_config}->{VarLib}/log/$data->{'id'}/archives/`; } else { - $self->{logger}->writeLogError("Can't get archive path for service " . $ns_server->{'id'} . " (" . $ns_server->{'ns_address_ip'} . ")"); + $self->{logger}->writeLogError("Can't get archive path for service " . $data->{'id'} . " (" . $data->{'ns_address_ip'} . ")"); } } } diff --git a/centreon/lib/perl/centreon/script/centreonSyncPlugins.pm b/centreon/lib/perl/centreon/script/centreonSyncPlugins.pm index 1f3b237778d..eaad605dc16 100644 --- a/centreon/lib/perl/centreon/script/centreonSyncPlugins.pm +++ b/centreon/lib/perl/centreon/script/centreonSyncPlugins.pm @@ -41,11 +41,11 @@ sub run { ($status, $sth) = $cdb->query("SELECT `id`, `ns_ip_address` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); die("Error SQL Quit") if ($status == -1); while ((my $data = $sth->fetchrow_hashref())) { - my $ls = `$self->{ssh} -q $ns_server->{'ns_ip_address'} ls -l $path_plugins/ 2>> /dev/null | wc -l`; + my $ls = `$self->{ssh} -q $data->{'ns_ip_address'} ls -l $path_plugins/ 2>> /dev/null | wc -l`; if ($ls > 1) { - `$self->{rsync} -prc $path_plugins/* $ns_server->{'ns_ip_address'}:$path_plugins/`; + `$self->{rsync} -prc $path_plugins/* $data->{'ns_ip_address'}:$path_plugins/`; } else { - $self->{logger}->writeLogError("Directory not present on remote server : " . $ns_server->{'ns_ip_address'}); + $self->{logger}->writeLogError("Directory not present on remote server : " . $data->{'ns_ip_address'}); } } } diff --git a/centreon/lib/perl/centreon/script/logAnalyserBroker.pm b/centreon/lib/perl/centreon/script/logAnalyserBroker.pm index 5a87aa477a1..b0a72eff879 100644 --- a/centreon/lib/perl/centreon/script/logAnalyserBroker.pm +++ b/centreon/lib/perl/centreon/script/logAnalyserBroker.pm @@ -99,64 +99,64 @@ EOQ if ($_ =~ m/^\[([0-9]*)\]\sSERVICE ALERT\:\s(.*)$/) { my @tab = split(/;/, $2); - next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})); + next if (!defined($self->{cache_host_service}{$tab[0] . ":" . $tab[1]}->{'service_id'})); $cur_ctime = $1; push @log_table_rows, - [($cur_ctime, $tab[0], $tab[1], $svc_status_code{$tab[2]}, $tab[5], '', '', $type_code{$tab[3]}, $tab[4], '0', $instance_name, $cache_host{$tab[0]}, $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})]; + [($cur_ctime, $tab[0], $tab[1], $svc_status_code{$tab[2]}, $tab[5], '', '', $type_code{$tab[3]}, $tab[4], '0', $instance_name, $self->{cache_host}{$tab[0]}, $self->{cache_host_service}{$tab[0] . ":" . $tab[1]}->{'service_id'})]; } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST ALERT\:\s(.*)$/) { my @tab = split(/;/, $2); - next if (!defined($cache_host{$tab[0]})); + next if (!defined($self->{cache_host}{$tab[0]})); $cur_ctime = $1; push @log_table_rows, - [($cur_ctime, $tab[0], '', $host_status_code{$tab[1]}, $tab[4], '', '', $type_code{$tab[2]}, $tab[3], '1', $instance_name, $cache_host{$tab[0]}, '')]; + [($cur_ctime, $tab[0], '', $host_status_code{$tab[1]}, $tab[4], '', '', $type_code{$tab[2]}, $tab[3], '1', $instance_name, $self->{cache_host}{$tab[0]}, '')]; } elsif ($_ =~ m/^\[([0-9]*)\]\sSERVICE NOTIFICATION\:\s(.*)$/) { my @tab = split(/;/, $2); - next if (!defined($cache_host_service{$tab[1] . ":" . $tab[2]}->{'service_id'})); + next if (!defined($self->{cache_host_service}{$tab[1] . ":" . $tab[2]}->{'service_id'})); $cur_ctime = $1; push @log_table_rows, - [($cur_ctime, $tab[1], $tab[2], $svc_status_code{$tab[3]}, $tab[5], $tab[4], $tab[0], '', 0, '2', $instance_name, $cache_host{$tab[1]}, $cache_host_service{$tab[1] . ":" . $tab[2]}->{'service_id'})]; + [($cur_ctime, $tab[1], $tab[2], $svc_status_code{$tab[3]}, $tab[5], $tab[4], $tab[0], '', 0, '2', $instance_name, $self->{cache_host}{$tab[1]}, $self->{cache_host_service}{$tab[1] . ":" . $tab[2]}->{'service_id'})]; } elsif ($_ =~ m/^\[([0-9]*)\]\sHOST NOTIFICATION\:\s(.*)$/) { my @tab = split(/;/, $2); - next if (!defined($cache_host{$tab[1]})); + next if (!defined($self->{cache_host}{$tab[1]})); $cur_ctime = $1; push @log_table_rows, - [($cur_ctime, $tab[1], '', $host_status_code{$tab[2]}, $tab[4], $tab[3], $tab[0], '', 0, '3', $instance_name, $cache_host{$tab[1]}, '')]; + [($cur_ctime, $tab[1], '', $host_status_code{$tab[2]}, $tab[4], $tab[3], $tab[0], '', 0, '3', $instance_name, $self->{cache_host}{$tab[1]}, '')]; } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sHOST\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); - next if (!defined($cache_host{$tab[0]})); + next if (!defined($self->{cache_host}{$tab[0]})); $cur_ctime = $1; push @log_table_rows, - [($cur_ctime, $tab[0], '', $host_status_code{$tab[1]}, '', '', '', $type_code{$tab[2]}, 0, '7', $instance_name, $cache_host{$tab[0]}, '')]; + [($cur_ctime, $tab[0], '', $host_status_code{$tab[1]}, '', '', '', $type_code{$tab[2]}, 0, '7', $instance_name, $self->{cache_host}{$tab[0]}, '')]; } elsif ($_ =~ m/^\[([0-9]*)\]\sCURRENT\sSERVICE\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); - next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})); + next if (!defined($self->{cache_host_service}{$tab[0] . ":" . $tab[1]}->{'service_id'})); $cur_ctime = $1; push @log_table_rows, - [($cur_ctime, $tab[0], $tab[1], $svc_status_code{$tab[2]}, '', '', '', $type_code{$tab[3]}, 0, '6', $instance_name, $cache_host{$tab[0]}, $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})]; + [($cur_ctime, $tab[0], $tab[1], $svc_status_code{$tab[2]}, '', '', '', $type_code{$tab[3]}, 0, '6', $instance_name, $self->{cache_host}{$tab[0]}, $self->{cache_host_service}{$tab[0] . ":" . $tab[1]}->{'service_id'})]; } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sHOST\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); - next if (!defined($cache_host{$tab[0]})); + next if (!defined($self->{cache_host}{$tab[0]})); $cur_ctime = $1; push @log_table_rows, - [($cur_ctime, $tab[0], '', $host_status_code{$tab[1]}, '', '', '', $type_code{$tab[2]}, 0, '9', $instance_name, $cache_host{$tab[0]}, '')]; + [($cur_ctime, $tab[0], '', $host_status_code{$tab[1]}, '', '', '', $type_code{$tab[2]}, 0, '9', $instance_name, $self->{cache_host}{$tab[0]}, '')]; } elsif ($_ =~ m/^\[([0-9]*)\]\sINITIAL\sSERVICE\sSTATE\:\s(.*)$/) { my @tab = split(/;/, $2); - next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})); + next if (!defined($self->{cache_host_service}{$tab[0] . ":" . $tab[1]}->{'service_id'})); $cur_ctime = $1; push @log_table_rows, - [($cur_ctime, $tab[0], $tab[1], $svc_status_code{$tab[2]}, '', '', '', $type_code{$tab[3]}, 0, '8', $instance_name, $cache_host{$tab[0]}, $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})]; + [($cur_ctime, $tab[0], $tab[1], $svc_status_code{$tab[2]}, '', '', '', $type_code{$tab[3]}, 0, '8', $instance_name, $self->{cache_host}{$tab[0]}, $self->{cache_host_service}{$tab[0] . ":" . $tab[1]}->{'service_id'})]; } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_SVC\_PROBLEM\;(.*)$/) { $cur_ctime = $1; my @tab = split(/;/, $2); - next if (!defined($cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})); + next if (!defined($self->{cache_host_service}{$tab[0] . ":" . $tab[1]}->{'service_id'})); push @log_table_rows, - [($cur_ctime, $tab[0], $tab[1], '', $tab[6], '', $tab[5], '', 0, '10', $instance_name, $cache_host{$tab[0]}, $cache_host_service{$tab[0] . ":" . $tab[1]}->{'service_id'})]; + [($cur_ctime, $tab[0], $tab[1], '', $tab[6], '', $tab[5], '', 0, '10', $instance_name, $self->{cache_host}{$tab[0]}, $self->{cache_host_service}{$tab[0] . ":" . $tab[1]}->{'service_id'})]; } elsif ($_ =~ m/^\[([0-9]*)\]\sEXTERNAL\sCOMMAND\:\sACKNOWLEDGE\_HOST\_PROBLEM\;(.*)$/) { $cur_ctime = $1; my @tab = split(/;/, $2); - next if (!defined($cache_host{$tab[0]})); + next if (!defined($self->{cache_host}{$tab[0]})); push @log_table_rows, - [($cur_ctime, $tab[0], '', '', $tab[5], '', $tab[4], '', 0, '11', $instance_name, $cache_host{$tab[0]}, '')]; + [($cur_ctime, $tab[0], '', '', $tab[5], '', $tab[4], '', 0, '11', $instance_name, $self->{cache_host}{$tab[0]}, '')]; } elsif ($_ =~ m/^\[([0-9]*)\]\sWarning\:\s(.*)$/) { my $tab = $2; $cur_ctime = $1; @@ -220,7 +220,7 @@ sub parseArchive { if ($status == -1) { die "Can't get information on poller"; } - $data = $sth->fetchrow_hashref(); + my $data = $sth->fetchrow_hashref(); if (!$data->{'log_archive_path'}) { die "Could not find local var log directory"; } @@ -240,8 +240,8 @@ sub run { $self->SUPER::run(); - if (defined($opt_s)) { - if ($opt_s !~ m/\d{2}-\d{2}-\d{4}/) { + if (defined($self->{opt_s})) { + if ($self->{opt_s} !~ m/\d{2}-\d{2}-\d{4}/) { $self->{logger}->writeLogError("Invalid start date provided"); exit 1; } @@ -250,7 +250,7 @@ sub run { # Get conf Data my ($status, $sth_config) = $self->{csdb}->query("SELECT `archive_log`, `archive_retention`, `nagios_log_file` FROM `config` LIMIT 1"); die("Cannot get archive log path") if ($status == -1); - $data = $sth_config->fetchrow_hashref(); + my $data = $sth_config->fetchrow_hashref(); die("Cannot get archive log path") if (!$data->{'archive_log'}); my $retention = $data->{'archive_retention'}; @@ -290,13 +290,13 @@ sub run { if (defined($self->{opt_p}) && $instanceId) { if (!defined($self->{opt_s})) { - $self->{csdb}->query("DELETE FROM `logs` WHERE instance_name = '$opt_p' AND `ctime` < $current_time"); + $self->{csdb}->query("DELETE FROM `logs` WHERE instance_name = " . $self->{csdb}->quote($self->{opt_p}) . " AND `ctime` < $self->{current_time}"); } else { my $limit = date_to_time($self->{opt_s}); if ($limit > $self->{retention_time}) { $self->{retention_time} = $limit; } - $self->{csdb}->query("DELETE FROM `logs` WHERE `ctime` >= $limit AND `ctime` < $current_time"); + $self->{csdb}->query("DELETE FROM `logs` WHERE `ctime` >= $limit AND `ctime` < $self->{current_time}"); } $self->parseArchive($instanceId); } else { @@ -305,14 +305,14 @@ sub run { die("Can't get poller list"); } while (my $ns_server = $sth->fetchrow_hashref()) { - if (!defined $opt_s) { - $self->{csdb}->query("DELETE FROM `logs` WHERE `ctime` < $current_time"); + if (!defined($self->{opt_s})) { + $self->{csdb}->query("DELETE FROM `logs` WHERE `ctime` < $self->{current_time}"); } else { my $limit = date_to_time($self->{opt_s}); if ($limit > $self->{retention_time}) { $self->{retention_time} = $limit; } - $res = $self->{csdb}->query("DELETE FROM `logs` WHERE `ctime` >= $limit AND `ctime` < $current_time"); + $self->{csdb}->query("DELETE FROM `logs` WHERE `ctime` >= $limit AND `ctime` < $self->{current_time}"); } $self->parseArchive($ns_server->{'id'}); } From f851685a8ccad22408ef8a183b25e58f23a7aa12 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 4 Apr 2013 10:28:54 +0200 Subject: [PATCH 045/458] Fix some bugs --- centreon/lib/perl/centreon/script/centreonSyncArchives.pm | 2 +- centreon/lib/perl/centreon/script/logAnalyserBroker.pm | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreonSyncArchives.pm b/centreon/lib/perl/centreon/script/centreonSyncArchives.pm index 1bc99125ae1..57be92c484e 100644 --- a/centreon/lib/perl/centreon/script/centreonSyncArchives.pm +++ b/centreon/lib/perl/centreon/script/centreonSyncArchives.pm @@ -30,7 +30,7 @@ sub run { force => 0, logger => $self->{logger}); my ($status, $sth) = $cdb->query("SELECT nagios_server.id, nagios_server.ns_ip_address, cfg_nagios.log_archive_path FROM nagios_server, cfg_nagios - WHERE nagios_server.ns_activate = '1' AND nagios_server.localhost = '0' AND nagios_server.id = cfg_nagios.ns_server_id"); + WHERE nagios_server.ns_activate = '1' AND nagios_server.localhost = '0' AND nagios_server.id = cfg_nagios.nagios_server_id"); die("Error SQL Quit") if ($status == -1); while ((my $data = $sth->fetchrow_hashref())) { if (defined($data->{log_archive_path}) && $data->{log_archive_path} ne '') { diff --git a/centreon/lib/perl/centreon/script/logAnalyserBroker.pm b/centreon/lib/perl/centreon/script/logAnalyserBroker.pm index b0a72eff879..fe07fe05b67 100644 --- a/centreon/lib/perl/centreon/script/logAnalyserBroker.pm +++ b/centreon/lib/perl/centreon/script/logAnalyserBroker.pm @@ -2,6 +2,7 @@ package centreon::script::logAnalyserBroker; use strict; use warnings; +use POSIX; use centreon::script; use base qw(centreon::script); @@ -28,7 +29,6 @@ sub new { my $self = $class->SUPER::new("logAnalyserBroker", centreon_db_conn => 1, centstorage_db_conn => 1, - noroot => 1 ); bless $self, $class; @@ -90,8 +90,8 @@ sub parseFile($$) { $self->{csdb}->transaction_mode(1); eval { my $sth = $self->{csdb}->{instance}->prepare(<<"EOQ"); -INSERT INTO log (ctime, host_name, service_description, status, output, notification_cmd, notification_contact, type, retry, msg_type, instance, host_id, service_id) -VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) +INSERT INTO logs (ctime, host_name, service_description, status, output, notification_cmd, notification_contact, type, retry, msg_type, instance_name, host_id, service_id) +VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) EOQ while () { From 3ca99e2a1b4bc330f60a94ae81f312e6a197033b Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 4 Apr 2013 10:36:47 +0200 Subject: [PATCH 046/458] Optimize centcore reload connection --- centreon/lib/perl/centreon/common/db.pm | 1 + centreon/lib/perl/centreon/script/centcore.pm | 19 +++++++++++++------ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/centreon/lib/perl/centreon/common/db.pm b/centreon/lib/perl/centreon/common/db.pm index 79d8cb66bae..c2a6a533325 100644 --- a/centreon/lib/perl/centreon/common/db.pm +++ b/centreon/lib/perl/centreon/common/db.pm @@ -18,6 +18,7 @@ sub new { force => 0 ); my $self = {%defaults, %options}; + $self->{port} = 3306 if (!defined($self->{port})); $self->{"instance"} = undef; $self->{"type"} = "mysql"; diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index f796ed61c97..e47319e09fc 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -127,12 +127,19 @@ sub reload { $self->{centreon_config} = $centreon_config; } - $self->{centreon_dbc}->disconnect(); - $self->{centreon_dbc}->db($self->{centreon_config}->{centreon_db}); - $self->{centreon_dbc}->host($self->{centreon_config}->{db_host}); - $self->{centreon_dbc}->user($self->{centreon_config}->{db_user}); - $self->{centreon_dbc}->password($self->{centreon_config}->{db_passwd}); - $self->{centreon_dbc}->port($self->{centreon_config}->{db_port}); + if ($self->{centreon_config}->{centreon_db} ne $self->{centreon_dbc}->db() || + $self->{centreon_config}->{db_host} ne $self->{centreon_dbc}->host() || + $self->{centreon_config}->{db_user} ne $self->{centreon_dbc}->user() || + $self->{centreon_config}->{db_passwd} ne $self->{centreon_dbc}->password() || + $self->{centreon_config}->{db_port} ne $self->{centreon_dbc}->port()) { + $self->{logger}->writeLogInfo("Database config had been modified") + $self->{centreon_dbc}->disconnect(); + $self->{centreon_dbc}->db($self->{centreon_config}->{centreon_db}); + $self->{centreon_dbc}->host($self->{centreon_config}->{db_host}); + $self->{centreon_dbc}->user($self->{centreon_config}->{db_user}); + $self->{centreon_dbc}->password($self->{centreon_config}->{db_passwd}); + $self->{centreon_dbc}->port($self->{centreon_config}->{db_port}); + } } ########################################################### From 2004567ead5fe66b4792d8f47516671b63589135 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 4 Apr 2013 11:40:48 +0200 Subject: [PATCH 047/458] Add reload system --- .../centreon/centstorage/CentstorageAction.pm | 60 ++++++++++++++-- .../centreon/centstorage/CentstoragePool.pm | 70 +++++++++++++++--- centreon/lib/perl/centreon/common/misc.pm | 72 +++++++++++++++++++ centreon/lib/perl/centreon/script/centcore.pm | 2 +- .../lib/perl/centreon/script/centstorage.pm | 58 ++++++++++++++- 5 files changed, 240 insertions(+), 22 deletions(-) create mode 100644 centreon/lib/perl/centreon/common/misc.pm diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm index b4e00456611..69fd108d3ba 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm @@ -1,11 +1,11 @@ -use strict; -use warnings; - package centreon::centstorage::CentstorageAction; +use strict; +use warnings; +use centreon::common::misc; use centreon::centstorage::CentstorageLib; -my %handlers = ('TERM' => {}); +my %handlers = ('TERM' => {}, 'HUP' => {}); sub new { my $class = shift; @@ -26,6 +26,9 @@ sub new { $self->{"save_read"} = []; + # reload flag + $self->{reload} = 1; + $self->{config_file} = undef; bless $self, $class; $self->set_signal_handlers; @@ -37,6 +40,13 @@ sub set_signal_handlers { $SIG{TERM} = \&class_handle_TERM; $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; + $SIG{HUP} = \&class_handle_HUP; + $handlers{HUP}->{$self} = sub { $self->handle_HUP() }; +} + +sub handle_HUP { + my $self = shift; + $self->{reload} = 0; } sub handle_TERM { @@ -54,6 +64,37 @@ sub class_handle_TERM { exit(0); } +sub class_handle_HUP { + foreach (keys %{$handlers{HUP}}) { + &{$handlers{HUP}->{$_}}(); + } +} + +sub reload { + my $self = shift; + + $self->{logger}->writeLogInfo("Reload in progress for delete process..."); + # reopen file + if (defined($self->{logger}->is_file_mode())) { + $self->{logger}->file_mode($self->{logger}->{file_name}); + } + $self->{logger}->redirect_output(); + + my ($status, $status_cdb, $status_csdb) = centreon::common::misc::reload_db_config($self->{logger}, $self->{config_file}, + $self->{dbcentreon}, $self->{dbcentstorage}); + if ($status_cdb == 1) { + $self->{dbcentreon}->disconnect(); + $self->{dbcentreon}->connect(); + } + if ($status_csdb == 1) { + $self->{dbcentstorage}->disconnect(); + $self->{dbcentstorage}->connect(); + } + centreon::common::misc::check_debug($self->{logger}, "debug_centstorage", $self->{dbcentreon}, "centstorage delete process"); + + $self->{reload} = 1; +} + sub check_deleted { my $self = shift; my $pipe_write = $_[0]; @@ -246,11 +287,12 @@ sub check_purge { sub main { my $self = shift; - my ($dbcentreon, $dbcentstorage, $pipe_read, $pipe_write) = @_; + my ($dbcentreon, $dbcentstorage, $pipe_read, $pipe_write, $config_file) = @_; my $status; - $self->{'dbcentreon'} = $dbcentreon; - $self->{'dbcentstorage'} = $dbcentstorage; + $self->{dbcentreon} = $dbcentreon; + $self->{dbcentstorage} = $dbcentstorage; + $self->{config_file} = $config_file; ($status, $self->{"rrd_metrics_path"}, $self->{"rrd_status_path"}) = $self->get_centstorage_information(); @@ -281,6 +323,10 @@ sub main { $self->check_deleted($pipe_write); $self->check_purge(); } + + if ($self->{reload} == 0) { + $self->reload(); + } } } diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index 129bbcd0533..c026b773f9b 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -1,13 +1,14 @@ -use strict; -use warnings; - package centreon::centstorage::CentstoragePool; +use strict; +use warnings; use centreon::common::db; +use centreon::common::misc; use centreon::centstorage::CentstorageLib; use centreon::centstorage::CentstorageRebuild; -my %handlers = ('TERM' => {}, 'CHLD' => {}); + +my %handlers = ('TERM' => {}, 'CHLD' => {}, 'HUP' => {}); my %rrd_trans = ("g" => 0, "c" => 1, "d" => 2, "a" => 3); sub new { @@ -80,6 +81,10 @@ sub new { $self->{"rebuild_key"} = undef; $self->{"current_pid"} = undef; + # reload flag + $self->{reload} = 1; + $self->{config_file} = undef; + $self->{"save_read"} = []; $self->{"read_select"} = undef; $self->{"pipe_write"} = undef; @@ -95,6 +100,13 @@ sub set_signal_handlers { $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; $SIG{CHLD} = \&class_handle_CHLD; $handlers{'CHLD'}->{$self} = sub { $self->handle_CHLD() }; + $SIG{HUP} = \&class_handle_HUP; + $handlers{HUP}->{$self} = sub { $self->handle_HUP() }; +} + +sub handle_HUP { + my $self = shift; + $self->{reload} = 0; } sub handle_TERM { @@ -216,6 +228,37 @@ sub class_handle_CHLD { } } +sub class_handle_HUP { + foreach (keys %{$handlers{HUP}}) { + &{$handlers{HUP}->{$_}}(); + } +} + +sub reload { + my $self = shift; + + $self->{logger}->writeLogInfo("Reload in progress for pool process " . $self->{num_pool} . "..."); + # reopen file + if (defined($self->{logger}->is_file_mode())) { + $self->{logger}->file_mode($self->{logger}->{file_name}); + } + $self->{logger}->redirect_output(); + + my ($status, $status_cdb, $status_csdb) = centreon::common::misc::reload_db_config($self->{logger}, $self->{config_file}, + $self->{dbcentreon}, $self->{dbcentstorage}); + if ($status_cdb == 1) { + $self->{dbcentreon}->disconnect(); + $self->{dbcentreon}->connect(); + } + if ($status_csdb == 1) { + $self->{dbcentstorage}->disconnect(); + $self->{dbcentstorage}->connect(); + } + centreon::common::misc::check_debug($self->{logger}, "debug_centstorage", $self->{dbcentreon}, "centstorage pool process " . $self->{num_pool}); + + $self->{reload} = 1; +} + sub add_data_mysql { my $self = shift; my ($metric_id, $ctime, $value) = @_; @@ -997,8 +1040,8 @@ sub send_rename_finish { my ($host_name, $service_description) = @_; $self->{"rename_rebuild_wait"} = 0; - my $fh = $self->{'pipe_write'}; - print $fh "RENAMEFINISH\t$host_name\t$service_description\n"; + my $fh = $self->{'pipe_write'}; + print $fh "RENAMEFINISH\t$host_name\t$service_description\n"; } sub rename_clean { @@ -1042,13 +1085,14 @@ sub delete_clean { sub main { my $self = shift; - my ($dbcentreon, $dbcentstorage, $pipe_read, $pipe_write, $num_pool, $rrd_cache_mode, $rrd_flush_time, $perfdata_parser_stop) = @_; + my ($dbcentreon, $dbcentstorage, $pipe_read, $pipe_write, $num_pool, $rrd_cache_mode, $rrd_flush_time, $perfdata_parser_stop, $config_file) = @_; my $status; - $self->{'dbcentreon'} = $dbcentreon; - $self->{'dbcentstorage'} = $dbcentstorage; - $self->{'num_pool'} = $num_pool; - $self->{'perfdata_parser_stop'} = $perfdata_parser_stop if (defined($perfdata_parser_stop)); + $self->{dbcentreon} = $dbcentreon; + $self->{dbcentstorage} = $dbcentstorage; + $self->{num_pool} = $num_pool; + $self->{config_file} = $config_file; + $self->{perfdata_parser_stop} = $perfdata_parser_stop if (defined($perfdata_parser_stop)); ($status, $self->{"main_perfdata_file"}) = centreon::centstorage::CentstorageLib::get_main_perfdata_file($self->{'dbcentreon'}); ($status, $self->{"len_storage_rrd"}, $self->{"rrd_metrics_path"}, $self->{"rrd_status_path"}, $self->{"storage_type"}) = $self->get_centstorage_information(); @@ -1100,6 +1144,10 @@ sub main { } } $self->flush_failed(); + + if ($self->{reload} == 0) { + $self->reload(); + } } } diff --git a/centreon/lib/perl/centreon/common/misc.pm b/centreon/lib/perl/centreon/common/misc.pm new file mode 100644 index 00000000000..e21425d99c6 --- /dev/null +++ b/centreon/lib/perl/centreon/common/misc.pm @@ -0,0 +1,72 @@ + +package centreon::common::misc; +use vars qw($centreon_config); + +sub reload_db_config { + my ($logger, $config_file, $cdb, $csdb) = @_; + my ($cdb_mod, $csdb_mod) = (0, 0); + + unless (my $return = do $config_file) { + $logger->writeLogError("couldn't parse $config_file: $@") if $@; + $logger->writeLogError("couldn't do $config_file: $!") unless defined $return; + $logger->writeLogError("couldn't run $config_file") unless $return; + return -1; + } + + if (defined($cdb)) { + if ($centreon_config->{centreon_db} ne $cdb->db() || + $centreon_config->{db_host} ne $cdb->host() || + $centreon_config->{db_user} ne $cdb->user() || + $centreon_config->{db_passwd} ne $cdb->password() || + $centreon_config->{db_port} ne $cdb->port()) { + $logger->writeLogInfo("Database centreon db config had been modified") + $cdb->db($centreon_config->{centreon_db}); + $cdb->host($centreon_config->{db_host}); + $cdb->user($centreon_config->{db_user}); + $cdb->password($centreon_config->{db_passwd}); + $cdb->port($centreon_config->{db_port}); + $cdb_mod = 1; + } + } + + if (defined($csdb)) { + if ($centreon_config->{centreon_db} ne $csdb->db() || + $centreon_config->{db_host} ne $csdb->host() || + $centreon_config->{db_user} ne $csdb->user() || + $centreon_config->{db_passwd} ne $csdb->password() || + $centreon_config->{db_port} ne $csdb->port()) { + $logger->writeLogInfo("Database centreon db config had been modified") + $csdb->db($centreon_config->{centreon_db}); + $csdb->host($centreon_config->{db_host}); + $csdb->user($centreon_config->{db_user}); + $csdb->password($centreon_config->{db_passwd}); + $csdb->port($centreon_config->{db_port}); + $csdb_mod = 1; + } + } + + return (0, $cdb_mod, $csdb_mod); +} + +sub check_debug { + my ($logger, $key, $cdb, $name) = @_; + + my $request = "SELECT value FROM options WHERE `key` = " . $cdb->quote($key)); + my ($status, $sth) = $cdb->query($request); + return -1 if ($status == -1); + my $data = $sth->fetchrow_hashref(); + if (defined($data->{'value'}) && $data->{'value'} == 1) { + if (!$logger->is_debug()) { + $logger->severity("debug"); + $logger->writeLogInfo("Enable Debug in $name"); + } + } else { + if ($logger->is_debug()) { + $logger->set_default_severity(); + $logger->writeLogInfo("Disable Debug in $name"); + } + } + return 0; +} + +1; diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index e47319e09fc..0df69cd38e7 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -113,7 +113,7 @@ sub handle_DIE { sub reload { my $self = shift; - if (defined $self->{log_file}) { + if (defined($self->{log_file})) { $self->{logger}->file_mode($self->{log_file}); } $self->{logger}->redirect_output(); diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index 0720220e862..32bea498374 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -8,6 +8,7 @@ use IO::Select; use IO::Handle; use centreon::script; use centreon::common::db; +use centreon::common::misc; use centreon::centstorage::CentstorageLib; use centreon::centstorage::CentstoragePool; use centreon::centstorage::CentstoragePerfdataFile; @@ -18,7 +19,7 @@ use centreon::centstorage::CentstorageRRD; use base qw(centreon::script); use vars qw(%centstorage_config); -my %handlers = ('TERM' => {}, 'CHLD' => {}, 'DIE' => {}); +my %handlers = ('TERM' => {}, 'CHLD' => {}, 'DIE' => {}, 'HUP' => {}); sub new { my $class = shift; @@ -47,6 +48,9 @@ sub new { $self->{rebuild_progress} = 0; $self->{rebuild_pool_choosen} = 0; + # reload flag + $self->{reload} = 1; + %{$self->{centstorage_default_config}} = ( pool_childs => 4, @@ -77,6 +81,37 @@ sub init { $self->{centstorage_config} = {%{$self->{centstorage_default_config}}, %centstorage_config}; } +sub reload { + my $self = shift; + + $self->{logger}->writeLogInfo("Reload in progress for main process..."); + # reopen file + if (defined($self->{logger}->is_file_mode())) { + $self->{logger}->file_mode($self->{logger}->{file_name}); + } + $self->{logger}->redirect_output(); + + centreon::common::misc::reload_db_config($self->{logger}, $self->{config_file}, $self->{centreon_db_centreon}); + centreon::common::misc::check_debug($self->{logger}, "debug_centstorage", $self->{centreon_db_centreon}, "centstorage main process"); + + # Not needed anymore + $self->{centreon_db_centreon}->disconnect(); + + # Send HUP to childs + for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { + if ($self->{pool_pipes}{$i}->{'running'} == 1) { + kill('HUP', $self->{pool_pipes}{$i}->{'pid'}); + $self->{logger}->writeLogInfo("Send -HUP signal to pool process.."); + } + } + if ($self->{delete_pipes}{'running'} == 1) { + kill('HUP', $self->{pid_delete_child}); + $self->{logger}->writeLogInfo("Send -HUP signal to delete process.."); + } + + $self->{reload} = 1; +} + sub set_signal_handlers { my $self = shift; @@ -86,6 +121,8 @@ sub set_signal_handlers { $handlers{DIE}->{$self} = sub { $self->handle_DIE($_[0]) }; $SIG{CHLD} = \&class_handle_CHLD; $handlers{CHLD}->{$self} = sub { $self->handle_CHLD() }; + $SIG{HUP} = \&class_handle_HUP; + $handlers{HUP}->{$self} = sub { $self->handle_HUP() }; } sub class_handle_TERM { @@ -109,6 +146,12 @@ sub class_handle_CHLD { } } +sub class_handle_HUP { + foreach (keys %{$handlers{HUP}}) { + &{$handlers{HUP}->{$_}}(); + } +} + sub handle_DIE { my $self = shift; my $msg = shift; @@ -176,6 +219,11 @@ sub handle_TERM { die("Quit"); } +sub handle_HUP { + my $self = shift; + $self->{reload} = 0; +} + #### # First Part # - Create Pool of child process @@ -259,7 +307,7 @@ sub create_pool_child { my $centstorage_pool = centreon::centstorage::CentstoragePool->new($self->{logger}, $centstorage_rrd, $self->{rebuild_progress}); $centstorage_pool->main($centreon_db_centreon, $centreon_db_centstorage, $self->{pool_pipes}{$pool_num}->{'reader_two'}, $self->{pool_pipes}{$pool_num}->{'writer_one'}, $pool_num, - $self->{centstorage_config}->{rrd_cache_mode}, $self->{centstorage_config}->{rrd_flush_time}, $self->{centstorage_config}->{perfdata_parser_stop}); + $self->{centstorage_config}->{rrd_cache_mode}, $self->{centstorage_config}->{rrd_flush_time}, $self->{centstorage_config}->{perfdata_parser_stop}, $self->{config_file}); exit(0); } $self->{pool_pipes}{$pool_num}->{'pid'} = $current_pid; @@ -310,7 +358,7 @@ sub create_delete_child { my $centstorage_action = centreon::centstorage::CentstorageAction->new($self->{logger}, $self->{rebuild_progress}, $self->{centstorage_config}->{centreon_23_compatibility}); $centstorage_action->main($centreon_db_centreon, $centreon_db_centstorage, - $self->{delete_pipes}{'reader_two'}, $self->{delete_pipes}{'writer_one'}); + $self->{delete_pipes}{'reader_two'}, $self->{delete_pipes}{'writer_one'}, $self->{config_file}); exit(0); } $self->{pid_delete_child} = $current_pid; @@ -429,6 +477,10 @@ sub run { } } } + + if ($self->{reload} == 0) { + $self->reload(); + } } } From eb65fa690ddf183f4bd1c303fa8665325a3b847c Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 4 Apr 2013 12:02:22 +0200 Subject: [PATCH 048/458] Fix reload for centstorage --- .../lib/perl/centreon/centstorage/CentstorageAction.pm | 2 +- .../lib/perl/centreon/centstorage/CentstoragePool.pm | 2 +- centreon/lib/perl/centreon/common/misc.pm | 10 +++++----- centreon/lib/perl/centreon/script/centstorage.pm | 4 ++-- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm index 69fd108d3ba..04badd6aabf 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm @@ -75,7 +75,7 @@ sub reload { $self->{logger}->writeLogInfo("Reload in progress for delete process..."); # reopen file - if (defined($self->{logger}->is_file_mode())) { + if ($self->{logger}->is_file_mode()) { $self->{logger}->file_mode($self->{logger}->{file_name}); } $self->{logger}->redirect_output(); diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index c026b773f9b..86df5ace468 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -239,7 +239,7 @@ sub reload { $self->{logger}->writeLogInfo("Reload in progress for pool process " . $self->{num_pool} . "..."); # reopen file - if (defined($self->{logger}->is_file_mode())) { + if ($self->{logger}->is_file_mode()) { $self->{logger}->file_mode($self->{logger}->{file_name}); } $self->{logger}->redirect_output(); diff --git a/centreon/lib/perl/centreon/common/misc.pm b/centreon/lib/perl/centreon/common/misc.pm index e21425d99c6..7591a5bdda8 100644 --- a/centreon/lib/perl/centreon/common/misc.pm +++ b/centreon/lib/perl/centreon/common/misc.pm @@ -19,7 +19,7 @@ sub reload_db_config { $centreon_config->{db_user} ne $cdb->user() || $centreon_config->{db_passwd} ne $cdb->password() || $centreon_config->{db_port} ne $cdb->port()) { - $logger->writeLogInfo("Database centreon db config had been modified") + $logger->writeLogInfo("Database centreon config had been modified"); $cdb->db($centreon_config->{centreon_db}); $cdb->host($centreon_config->{db_host}); $cdb->user($centreon_config->{db_user}); @@ -30,13 +30,13 @@ sub reload_db_config { } if (defined($csdb)) { - if ($centreon_config->{centreon_db} ne $csdb->db() || + if ($centreon_config->{centstorage_db} ne $csdb->db() || $centreon_config->{db_host} ne $csdb->host() || $centreon_config->{db_user} ne $csdb->user() || $centreon_config->{db_passwd} ne $csdb->password() || $centreon_config->{db_port} ne $csdb->port()) { - $logger->writeLogInfo("Database centreon db config had been modified") - $csdb->db($centreon_config->{centreon_db}); + $logger->writeLogInfo("Database centstorage config had been modified"); + $csdb->db($centreon_config->{centstorage_db}); $csdb->host($centreon_config->{db_host}); $csdb->user($centreon_config->{db_user}); $csdb->password($centreon_config->{db_passwd}); @@ -51,7 +51,7 @@ sub reload_db_config { sub check_debug { my ($logger, $key, $cdb, $name) = @_; - my $request = "SELECT value FROM options WHERE `key` = " . $cdb->quote($key)); + my $request = "SELECT value FROM options WHERE `key` = " . $cdb->quote($key); my ($status, $sth) = $cdb->query($request); return -1 if ($status == -1); my $data = $sth->fetchrow_hashref(); diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index 32bea498374..515cea1bb0c 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -86,7 +86,7 @@ sub reload { $self->{logger}->writeLogInfo("Reload in progress for main process..."); # reopen file - if (defined($self->{logger}->is_file_mode())) { + if ($self->{logger}->is_file_mode()) { $self->{logger}->file_mode($self->{logger}->{file_name}); } $self->{logger}->redirect_output(); @@ -162,7 +162,7 @@ sub handle_DIE { ### # Send -TERM signal ### - for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { + for (my $i = 0; defined($self->{centstorage_config}->{pool_childs}) && $i < $self->{centstorage_config}->{pool_childs}; $i++) { if (defined($self->{pool_pipes}{$i}) && $self->{pool_pipes}{$i}->{'running'} == 1) { kill('TERM', $self->{pool_pipes}{$i}->{'pid'}); $self->{logger}->writeLogInfo("Send -TERM signal to pool process.."); From c6bd45a0b0c11540a448672b269819ca2dc3f887 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 10 Apr 2013 17:10:37 +0200 Subject: [PATCH 049/458] Working progress --- .../lib/perl/centreon/script/centreontrapd.pm | 163 +++++++++++++++--- centreon/lib/perl/centreon/trapd/lib.pm | 2 +- 2 files changed, 138 insertions(+), 27 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 0bb678ca96e..ca90cb59f53 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -10,7 +10,7 @@ use centreon::trapd::lib; use base qw(centreon::script); use vars qw(%centreontrapd_config); -my %handlers = ('TERM' => {}, 'HUP' => {}); +my %handlers = ('TERM' => {}, 'HUP' => {}, 'DIE' => {}, 'CHLD' => {}); sub new { my $class = shift; @@ -26,7 +26,7 @@ sub new { %{$self->{centreontrapd_default_config}} = ( - daemon => 0, + daemon => 1, spool_directory => "/var/spool/centreontrapd/", sleep => 2, use_trap_time => 1, @@ -47,7 +47,9 @@ sub new { mode => 0, cmdFile => "/var/lib/centreon/centcore.cmd", cmd_timeout => 10, - centreon_user => "centreon" + centreon_user => "centreon", + # 0 => skip if MySQL error | 1 => dont skip (block) if MySQL error (and keep order) + policy_trap => 1 ); $self->{htmlentities} = 0; @@ -61,12 +63,22 @@ sub new { $self->{trap_date_time_epoch} = undef; %{$self->{duplicate_traps}} = (); $self->{timetoreload} = 0; - $self->{timetodie} = 0; @{$self->{filenames}} = undef; $self->{oids_cache} = undef; $self->{last_cache_time} = undef; $self->{whoami} = undef; + # Fork manage + %{$self->{return_child}} = (); + %{$self->{running_processes}} = (); + %{$self->{last_time_exec}} = ('oid' => {}, 'host' => {}); + # Current ID of working + $self->{current_host_id} = undef; + + # For policy_trap = 1 (temp). To avoid doing the same thing twice + # ID oid ===> Host ID ===> Service ID + %{$self->{policy_trap_skip}} = (); + $self->{cmdFile} = undef; # redefine to avoid out when we try modules @@ -102,6 +114,10 @@ sub set_signal_handlers { $handlers{TERM}->{$self} = sub { $self->handle_TERM() }; $SIG{HUP} = \&class_handle_HUP; $handlers{HUP}->{$self} = sub { $self->handle_HUP() }; + $SIG{__DIE__} = \&class_handle_DIE; + $handlers{DIE}->{$self} = sub { $self->handle_DIE($_[0]) }; + $SIG{CHLD} = \&class_handle_CHLD; + $handlers{CHLD}->{$self} = sub { $self->handle_CHLD() }; } sub class_handle_TERM { @@ -116,9 +132,25 @@ sub class_handle_HUP { } } +sub class_handle_CHLD { + foreach (keys %{$handlers{CHLD}}) { + &{$handlers{CHLD}->{$_}}(); + } +} + +sub class_handle_DIE { + my ($msg) = @_; + + foreach (keys %{$handlers{DIE}}) { + &{$handlers{DIE}->{$_}}($msg); + } +} + sub handle_TERM { my $self = shift; - $self->{timetodie} = 1; + $self->{logger}->writeLogInfo("$$ Receiving order to stop..."); + die("Quit"); +} } sub handle_HUP { @@ -126,6 +158,27 @@ sub handle_HUP { $self->{timetoreload} = 1; } +sub handle_DIE { + my $self = shift; + my $msg = shift; + + # We get SIGCHLD signals + $self->{logger}->writeLogInfo($msg); + + exit(0); +} + +sub handle_CHLD { + my $self = shift; + my $child_pid; + + while (($child_pid = waitpid(-1, &WNOHANG)) > 0) { + $self->{return_child}{$child_pid} = {'exit_code' => $? >> 8}; + $self->{logger}->writeLogInfo("SIGCHLD received: $child_pid"); + } + $SIG{CHLD} = \&class_handle_CHLD; +} + sub reload_config { my $self = shift; my $file = $_[0]; @@ -137,12 +190,23 @@ sub reload_config { } } +sub manage_pool { + my $self = shift; + + foreach my $child_pid (keys %{$self->{return_child}}) { + if (defined($self->{running_processes}->{$child_pid})) { + delete $self->{running_processes}->{$child_pid}; + delete $self->{return_child}->{$child_pid}; + } + } +} + ############################### ## Execute a command Nagios or Centcore # -sub send_command { +sub do_command { my $self = shift; - + eval { local $SIG{ALRM} = sub { die "TIMEOUT"; }; alarm($self->{centreontrapd_config}->{cmd_timeout}); @@ -155,6 +219,27 @@ sub send_command { return 0; } } + + return 1; +} + +sub manage_exec { + my $self = shift; + + if ($self->{centreontrapd_config}->{daemon} == 0) { + return $self->do_command(); + } + + #### Fork And manage exec #### + my $current_pid = fork(); + if (!$current_pid) { + exit($self->do_command()); + } + + $self->{logger}->writeLogInfo("CHLD command launched: $current_pid"); + $self->{running_processes}->{$current_pid} = 1; + $self->{last_time_exec}{oid}->{${$self->{var}}[3]} = $self->{trap_date_time_epoch}; + $self->{last_time_exec}{host}->{$self->{current_host_id}} = $self->{trap_date_time_epoch}; return 1; } @@ -302,7 +387,7 @@ sub forceCheck($$$) { } else { $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] SCHEDULE_FORCED_SVC_CHECK;$this_host;$this_service;$datetime\" >> " . $self->{centreontrapd_config}->{cmdFile} . "'"; } - $result = $self->send_command($submit); + $result = $self->manage_exec($submit); $self->{logger}->writeLogInfo("FORCE: Reschedule linked service"); $self->{logger}->writeLogInfo("FORCE: Launched command: $submit"); @@ -332,7 +417,7 @@ sub submitResult($$$$$) { $str =~ s/"/\\"/g; $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile} . "'"; } - $result = $self->send_command($submit); + $result = $self->manage_exec($submit); $self->{logger}->writeLogInfo("SUBMIT: Force service status via passive check update"); $self->{logger}->writeLogInfo("SUBMIT: Launched command: $submit"); @@ -471,11 +556,19 @@ sub getTrapsInfos($$$) { my $ip = shift; my $hostname = shift; my $oid = shift; - my $status; + # LOOP on OID + { + # Get Hosts + { + # Get Services + } + } + my %host = $self->get_hostinfos($ip, $hostname); foreach my $host_id (keys %host) { + $self->{current_host_id} = $host_id; my $this_host = $host{$host_id}; my ($trap_id, $status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, $ref_servicename) = $self->getServiceInformations($oid, $host_id); if (!defined($trap_id)) { @@ -518,6 +611,8 @@ sub getTrapsInfos($$$) { } } } + + return 1; } sub run { @@ -542,6 +637,8 @@ sub run { password => $self->{centreon_config}->{db_passwd}, force => 0, logger => $self->{logger}); + $self->{cbd}->set_inactive_destroy(); + if ($self->{centreontrapd_config}->{mode} == 0) { $self->{cmdFile} = $self->{centreon_config}->{cmdFile}; } else { @@ -553,7 +650,7 @@ sub run { $self->{whoami} = getpwuid($<); if ($self->{centreontrapd_config}->{daemon} == 1) { - while (!$self->{timetodie}) { + while (1) { centreon::trapd::lib::purge_duplicate_trap(config => $self->{centreontrapd_config}, duplicate_traps => \%{$self->{duplicate_traps}}); while ((my $file = centreon::trapd::lib::get_trap(logger => $self->{logger}, @@ -562,6 +659,7 @@ sub run { $self->{logger}->writeLogDebug("Processing file: $file"); if (open FILE, $self->{centreontrapd_config}->{spool_directory} . $file) { + my $unlink_trap = 1; my $trap_is_a_duplicate = 0; my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, config => $self->{centreontrapd_config}, @@ -583,7 +681,7 @@ sub run { cdb => $self->{cdb}, last_cache_time => \$self->{last_cache_time}, oids_cache => \$self->{oids_cache}) == 1) { - $self->getTrapsInfos(${$self->{var}}[1], ${$self->{var}}[2], ${$self->{var}}[3]); + $unlink_trap = $self->getTrapsInfos(${$self->{var}}[1], ${$self->{var}}[2], ${$self->{var}}[3]); } } elsif ($readtrap_result == 0) { $self->{logger}->writeLogDebug("Error processing trap file $file. Skipping..."); @@ -593,27 +691,40 @@ sub run { } close FILE; - unless (unlink($file)) { - $self->{logger}->writeLogError("Unable to delete trap file $file from spool dir:$!"); - } + if ($self->{centreontrapd_config}->{policy_trap} == 0 || ($self->{centreontrapd_config}->{policy_trap} == 1 && $unlink_trap == 1)) { + unless (unlink($file)) { + $self->{logger}->writeLogError("Unable to delete trap file $file from spool dir:$!"); + } + } else { + $self->{logger}->writeLogError("Dont skip trap. Need to solve the error."); + # we reput in + unshift @{$self->{filenames}}, $file; + } } else { $self->{logger}->writeLogError("Could not open trap file " . $self->{centreontrapd_config}->{spool_directory} . "$file: ($!)"); + if ($self->{centreontrapd_config}->{policy_trap} == 1) { + $self->{logger}->writeLogError("Dont skip trap. Need to solve the error."); + # we reput in + unshift @{$self->{filenames}}, $file; + } + } + + if ($self->{timetoreload} == 1) { + $self->{logger}->writeLogDebug("Reloading configuration file"); + $self->reload_config($self->{opt_extra}); + ($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}) = + centreon::trapd::lib::manage_params_conf($self->{centreontrapd_config}->{date_format}, + $self->{centreontrapd_config}->{time_format}); + centreon::trapd::lib::init_modules(); + centreon::trapd::lib::get_cache_oids(); + $self->{timetoreload} = 0; } } $self->{logger}->writeLogDebug("Sleeping for " . $self->{centreontrapd_config}->{sleep} . " seconds"); sleep $self->{centreontrapd_config}->{sleep}; - - if ($self->{timetoreload} == 1) { - $self->{logger}->writeLogDebug("Reloading configuration file"); - $self->reload_config($self->{opt_extra}); - ($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}) = - centreon::trapd::lib::manage_params_conf($self->{centreontrapd_config}->{date_format}, - $self->{centreontrapd_config}->{time_format}); - centreon::trapd::lib::init_modules(); - centreon::trapd::lib::get_cache_oids(); - $self->{timetoreload} = 0; - } + + $self->manage_pool(); } } else { my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index aa75f53a326..31fdda7250b 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -534,7 +534,7 @@ sub readtrap { $args{logger}->writeLogDebug("Host IP address (" . ${$args{var}}[0] . ") resolved to: $temp"); ${$args{var}}[0] = $temp; } else { - $args{logger}->writeLogDebug("Host IP address (" . ${$args{var}}[0] . ") could not be resolved by DNS. Variable \$r / \$R etc will use the IP address"); + $args{logger}->writeLogDebug("Host IP address (" . ${$args{var}}[0] . ") could not be resolved by DNS. Variable \$r / \$R etc will use the IP address"); } } From f965a836a12b6df44e50dc7a3ba307230d0e3b39 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 11 Apr 2013 10:32:04 +0200 Subject: [PATCH 050/458] progress --- .../lib/perl/centreon/script/centreontrapd.pm | 40 +++++++++----- centreon/lib/perl/centreon/trapd/lib.pm | 53 +++++++++++++++++++ 2 files changed, 81 insertions(+), 12 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index ca90cb59f53..056a9b7c81e 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -74,6 +74,7 @@ sub new { %{$self->{last_time_exec}} = ('oid' => {}, 'host' => {}); # Current ID of working $self->{current_host_id} = undef; + $self->{current_ip} = undef; # For policy_trap = 1 (temp). To avoid doing the same thing twice # ID oid ===> Host ID ===> Service ID @@ -551,22 +552,23 @@ sub executeCommand($$$$$$$$) { ####################################### ## GET HOSTNAME AND SERVICE DESCRIPTION # -sub getTrapsInfos($$$) { +sub getTrapsInfos($$) { my $self = shift; - my $ip = shift; my $hostname = shift; my $oid = shift; my $status; + $self->{current_ip} = ${$self->{var}}[1]; + # LOOP on OID - { + #{ # Get Hosts - { + # { # Get Services - } - } + # } + #} - my %host = $self->get_hostinfos($ip, $hostname); + my %host = $self->get_hostinfos($self->{current_ip}, $hostname); foreach my $host_id (keys %host) { $self->{current_host_id} = $host_id; my $this_host = $host{$host_id}; @@ -589,7 +591,7 @@ sub getTrapsInfos($$$) { ###################################################################### # Advanced matching rules if (defined($traps_advanced_treatment) && $traps_advanced_treatment eq 1) { - $status = $self->checkMatchingRules($trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status); + $status = $self->checkMatchingRules($trap_id, $this_host, $this_service, $self->{current_ip}, $hostname, $traps_output, $datetime, $status); } ##################################################################### @@ -607,7 +609,7 @@ sub getTrapsInfos($$$) { ###################################################################### # Execute special command if (defined($traps_execution_command_enable) && $traps_execution_command_enable) { - $self->executeCommand($traps_execution_command, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status); + $self->executeCommand($traps_execution_command, $this_host, $this_service, $self->{current_ip}, $hostname, $traps_output, $datetime, $status); } } } @@ -649,6 +651,9 @@ sub run { } $self->{whoami} = getpwuid($<); + centreon::trapd::lib::get_macros_host(14); + exit(1); + if ($self->{centreontrapd_config}->{daemon} == 1) { while (1) { centreon::trapd::lib::purge_duplicate_trap(config => $self->{centreontrapd_config}, @@ -658,6 +663,17 @@ sub run { filenames => \@{$self->{filenames}}))) { $self->{logger}->writeLogDebug("Processing file: $file"); + # Test can delete before. Dont go after if we cant + if (! -w $self->{centreontrapd_config}->{spool_directory} . $file) { + $self->{logger}->writeLogError("Dont have write permission on '" . $self->{centreontrapd_config}->{spool_directory} . $file . "' file."); + if ($self->{centreontrapd_config}->{policy_trap} == 1) { + unshift @{$self->{filenames}}, $file; + # We're waiting. We are in a loop + sleep $self->{centreontrapd_config}->{sleep}; + next; + } + } + if (open FILE, $self->{centreontrapd_config}->{spool_directory} . $file) { my $unlink_trap = 1; my $trap_is_a_duplicate = 0; @@ -681,7 +697,7 @@ sub run { cdb => $self->{cdb}, last_cache_time => \$self->{last_cache_time}, oids_cache => \$self->{oids_cache}) == 1) { - $unlink_trap = $self->getTrapsInfos(${$self->{var}}[1], ${$self->{var}}[2], ${$self->{var}}[3]); + $unlink_trap = $self->getTrapsInfos(${$self->{var}}[2], ${$self->{var}}[3]); } } elsif ($readtrap_result == 0) { $self->{logger}->writeLogDebug("Error processing trap file $file. Skipping..."); @@ -692,7 +708,7 @@ sub run { close FILE; if ($self->{centreontrapd_config}->{policy_trap} == 0 || ($self->{centreontrapd_config}->{policy_trap} == 1 && $unlink_trap == 1)) { - unless (unlink($file)) { + unless (unlink($self->{centreontrapd_config}->{spool_directory} . $file)) { $self->{logger}->writeLogError("Unable to delete trap file $file from spool dir:$!"); } } else { @@ -746,7 +762,7 @@ sub run { cdb => $self->{cdb}, last_cache_time => \$self->{last_cache_time}, oids_cache => \$self->{oids_cache}) == 1) { - $self->getTrapsInfos(${$self->{var}}[1], ${$self->{var}}[2], ${$self->{var}}[3]); + $self->getTrapsInfos(${$self->{var}}[2], ${$self->{var}}[3]); } } elsif ($readtrap_result == 0) { $self->{logger}->writeLogDebug("Error processing trap file. Skipping..."); diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 31fdda7250b..0e812ef17c7 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -86,6 +86,58 @@ sub manage_params_conf { return ($date_format, $time_format); } +############## +# DB Request +############## + +sub set_macro { + my ($macros, $name, $value) = @_; + + if (!defined($macros->{$name})) { + $macros->{$name} = $value; + } +} + +sub get_macros_host { + my ($cbd, $host_id) = @_; + my ($dstatus, $sth, $value); + my %macros; + my %loop_stop = (); + my @stack = ($host_id); + + while ((my $lhost_id = shift(@stack))) { + if (defined($loop_stop{$lhost_id})) { + # Already done the host + next; + } + $loop_stop{$lhost_id} = 1; + + ($dstatus, $sth) = $cdb->query("SELECT host_snmp_community, host_snmp_version FROM host WHERE host_id = " . $lhost_id . " LIMIT 1"); + return -1 if ($dstatus == -1); + $value = $sth->fetchrow_hashref(); + if (defined($value->{host_snmp_community}) && $value->{host_snmp_community} ne "") { + set_macro(\%macros, '$_HOSTSNMPCOMMUNITY$', $value->{host_snmp_community}); + } + if (defined($value->{host_snmp_version}) && $value->{host_snmp_version} ne "") { + set_macro(\%macros, '$_HOSTSNMPVERSION$', $value->{host_snmp_version}); + } + + ($dstatus, $sth) = $cdb->query("SELECT host_macro_name, host_macro_value FROM on_demand_macro_host WHERE host_host_id = " . $lhost_id); + return -1 if ($dstatus == -1); + while ($value = $sth->fetchrow_hashref()) { + set_macro(\%macros, $value->{host_macro_name}, $value->{host_macro_value}); + } + + ($dstatus, $sth) = $cdb->query("SELECT host_tpl_id FROM host_template_relation WHERE host_host_id = " . $lhost_id . " ORDER BY order DESC"); + return -1 if ($dstatus == -1); + while ($value = $sth->fetchrow_hashref()) { + unshift @stack, $value->{host_tpl_id}; + } + } + + return (0, %macros); +} + ############## # CACHE MANAGEMENT ############## @@ -228,6 +280,7 @@ sub get_trap { while ((my $file = shift @{$args{filenames}})) { next if ($file eq "."); next if ($file eq ".."); + next if (! -f $args{config}->{spool_directory} . $file); return $file; } return undef; From 8ef8ed3d33edf6c3b6e31517f21a1366f8615b1d Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 11 Apr 2013 11:14:02 +0200 Subject: [PATCH 051/458] Continue new system --- .../lib/perl/centreon/script/centreontrapd.pm | 46 ++++++++++--------- .../lib/perl/centreon/script/centstorage.pm | 1 - centreon/lib/perl/centreon/trapd/lib.pm | 16 +++++-- 3 files changed, 36 insertions(+), 27 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 056a9b7c81e..e022741d958 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -75,6 +75,7 @@ sub new { # Current ID of working $self->{current_host_id} = undef; $self->{current_ip} = undef; + $self->{current_oid} = undef; # For policy_trap = 1 (temp). To avoid doing the same thing twice # ID oid ===> Host ID ===> Service ID @@ -102,6 +103,11 @@ sub init { $self->{centreontrapd_config} = {%{$self->{centreontrapd_default_config}}, %centreontrapd_config}; + ($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}) = + centreon::trapd::lib::manage_params_conf($self->{centreontrapd_config}->{date_format}, + $self->{centreontrapd_config}->{time_format}); + centreon::trapd::lib::init_modules(logger => $self->{logger}, config => $self->{centreontrapd_config}, htmlentities => \$self->{htmlentities}); + # Daemon Only if ($self->{centreontrapd_config}->{daemon} == 1) { $self->set_signal_handlers; @@ -152,7 +158,6 @@ sub handle_TERM { $self->{logger}->writeLogInfo("$$ Receiving order to stop..."); die("Quit"); } -} sub handle_HUP { my $self = shift; @@ -552,27 +557,30 @@ sub executeCommand($$$$$$$$) { ####################################### ## GET HOSTNAME AND SERVICE DESCRIPTION # -sub getTrapsInfos($$) { +sub getTrapsInfos($) { my $self = shift; my $hostname = shift; - my $oid = shift; - my $status; - + my ($status, $dstatus); + my ($ref_oids); + $self->{current_ip} = ${$self->{var}}[1]; + $self->{current_oid} = ${$self->{var}}[3]; - # LOOP on OID - #{ - # Get Hosts - # { - # Get Services - # } - #} + ### Get OIDS + ($dstatus, $ref_oids) = centreon::trapd::lib::get_oids($self->{cdb}, $self->{current_oid}); + return 0 if ($dstatus == -1); + foreach (keys %$ref_oids) { + ##### Get Hosts + print Data::Dumper::Dumper($ref_oids); + } + + exit(1); my %host = $self->get_hostinfos($self->{current_ip}, $hostname); foreach my $host_id (keys %host) { $self->{current_host_id} = $host_id; my $this_host = $host{$host_id}; - my ($trap_id, $status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, $ref_servicename) = $self->getServiceInformations($oid, $host_id); + my ($trap_id, $status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, $ref_servicename) = $self->getServiceInformations($self->{current_oid}, $host_id); if (!defined($trap_id)) { return ; } @@ -621,13 +629,7 @@ sub run { my $self = shift; $self->SUPER::run(); - $self->init(); $self->{logger}->redirect_output(); - - ($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}) = - centreon::trapd::lib::manage_params_conf($self->{centreontrapd_config}->{date_format}, - $self->{centreontrapd_config}->{time_format}); - centreon::trapd::lib::init_modules(logger => $self->{logger}, config => $self->{centreontrapd_config}, htmlentities => \$self->{htmlentities}); $self->{logger}->writeLogDebug("centreontrapd launched...."); $self->{logger}->writeLogDebug("PID: $$"); @@ -639,7 +641,7 @@ sub run { password => $self->{centreon_config}->{db_passwd}, force => 0, logger => $self->{logger}); - $self->{cbd}->set_inactive_destroy(); + $self->{cdb}->set_inactive_destroy(); if ($self->{centreontrapd_config}->{mode} == 0) { $self->{cmdFile} = $self->{centreon_config}->{cmdFile}; @@ -697,7 +699,7 @@ sub run { cdb => $self->{cdb}, last_cache_time => \$self->{last_cache_time}, oids_cache => \$self->{oids_cache}) == 1) { - $unlink_trap = $self->getTrapsInfos(${$self->{var}}[2], ${$self->{var}}[3]); + $unlink_trap = $self->getTrapsInfos(${$self->{var}}[2]); } } elsif ($readtrap_result == 0) { $self->{logger}->writeLogDebug("Error processing trap file $file. Skipping..."); @@ -762,7 +764,7 @@ sub run { cdb => $self->{cdb}, last_cache_time => \$self->{last_cache_time}, oids_cache => \$self->{oids_cache}) == 1) { - $self->getTrapsInfos(${$self->{var}}[2], ${$self->{var}}[3]); + $self->getTrapsInfos(${$self->{var}}[2]); } } elsif ($readtrap_result == 0) { $self->{logger}->writeLogDebug("Error processing trap file. Skipping..."); diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index 515cea1bb0c..5667b5bf422 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -383,7 +383,6 @@ sub run { my $self = shift; $self->SUPER::run(); - $self->init(); $self->{logger}->redirect_output(); #### diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 0e812ef17c7..314984b5e89 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -65,7 +65,7 @@ sub init_modules { require Digest::MD5; } - eval "use HTML::Entities"; + eval "require HTML::Entities"; if ($@) { ${$args{htmlentities}} = 0; } else { @@ -90,6 +90,14 @@ sub manage_params_conf { # DB Request ############## +sub get_oids { + my ($cdb, $oid) = @_; + + ($dstatus, $sth) = $cdb->query("SELECT * FROM traps WHERE traps_oid = " . $cdb->quote($oid)); + return -1 if ($dstatus == -1); + return (0, $cdb->fetchall_hashref('traps_id')); +} + sub set_macro { my ($macros, $name, $value) = @_; @@ -99,7 +107,7 @@ sub set_macro { } sub get_macros_host { - my ($cbd, $host_id) = @_; + my ($cdb, $host_id) = @_; my ($dstatus, $sth, $value); my %macros; my %loop_stop = (); @@ -128,14 +136,14 @@ sub get_macros_host { set_macro(\%macros, $value->{host_macro_name}, $value->{host_macro_value}); } - ($dstatus, $sth) = $cdb->query("SELECT host_tpl_id FROM host_template_relation WHERE host_host_id = " . $lhost_id . " ORDER BY order DESC"); + ($dstatus, $sth) = $cdb->query("SELECT host_tpl_id FROM host_template_relation WHERE host_host_id = " . $lhost_id . " ORDER BY `order` DESC"); return -1 if ($dstatus == -1); while ($value = $sth->fetchrow_hashref()) { unshift @stack, $value->{host_tpl_id}; } } - return (0, %macros); + return (0, \%macros); } ############## From 33f8349548bf046d3f3e8edbd3b8669697d74513 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 11 Apr 2013 17:31:23 +0200 Subject: [PATCH 052/458] Continue centreontrapd --- .../lib/perl/centreon/script/centreontrapd.pm | 453 ++++++++---------- centreon/lib/perl/centreon/trapd/lib.pm | 97 +++- 2 files changed, 292 insertions(+), 258 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index e022741d958..8c7a6992ea8 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -56,6 +56,7 @@ sub new { @{$self->{var}} = undef; # Variables of trap received by SNMPTRAPD @{$self->{entvar}} = undef; # Enterprise variable values of trap received by SNMPTRAPD @{$self->{entvarname}} = undef; # Enterprise variable names of trap received by SNMPTRAPD + @{$self->{preexec}} = undef; # Result from PREEXEC $self->{agent_dns_name} = undef; $self->{trap_date} = undef; $self->{trap_time} = undef; @@ -68,12 +69,22 @@ sub new { $self->{last_cache_time} = undef; $self->{whoami} = undef; + $self->{ref_oids} = undef; + $self->{ref_hosts} = undef; + $self->{ref_services} = undef; + $self->{ref_macro_hosts} = undef; + # Fork manage %{$self->{return_child}} = (); %{$self->{running_processes}} = (); %{$self->{last_time_exec}} = ('oid' => {}, 'host' => {}); # Current ID of working $self->{current_host_id} = undef; + $self->{current_hostname} = undef; + $self->{current_server_id} = undef; + $self->{current_service_id} = undef; + $self->{current_service_desc} = undef; + $self->{current_trap_id} = undef; $self->{current_ip} = undef; $self->{current_oid} = undef; @@ -210,225 +221,161 @@ sub manage_pool { ############################### ## Execute a command Nagios or Centcore # -sub do_command { - my $self = shift; - - eval { - local $SIG{ALRM} = sub { die "TIMEOUT"; }; - alarm($self->{centreontrapd_config}->{cmd_timeout}); - system @_; - alarm(0); - }; - if ($@) { - if ($@ =~ "TIMEOUT") { - $self->{logger}->writeLogError("ERROR: Send command timeout"); - return 0; - } - } - - return 1; -} - -sub manage_exec { +sub do_exec { my $self = shift; - if ($self->{centreontrapd_config}->{daemon} == 0) { - return $self->do_command(); - } + my $traps_output = $self->substitute_string($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_args}); + my $status = $self->substitute_string($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_status}); - #### Fork And manage exec #### - my $current_pid = fork(); - if (!$current_pid) { - exit($self->do_command()); + ###################################################################### + # Advanced matching rules + if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment}) && + $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment} == 1) { + $status = $self->checkMatchingRules($traps_output); } - - $self->{logger}->writeLogInfo("CHLD command launched: $current_pid"); - $self->{running_processes}->{$current_pid} = 1; - $self->{last_time_exec}{oid}->{${$self->{var}}[3]} = $self->{trap_date_time_epoch}; - $self->{last_time_exec}{host}->{$self->{current_host_id}} = $self->{trap_date_time_epoch}; - return 1; -} - -############################### -## GET HOSTNAME FROM IP ADDRESS -# -sub get_hostinfos($$) { - my $self = shift; - my %host = (); - my ($status, $sth) = $self->{cdb}->query("SELECT host_id, host_name FROM host WHERE host_address='$_[0]' OR host_address='$_[1]'"); - while (my ($host_id, $host_name) = $sth->fetchrow_array()) { - $host{$host_id} = $host_name; + ##################################################################### + # Submit value to passive service + if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_submit_result_enable}) && + $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_submit_result_enable} == 1) { + $self->submitResult($status, $traps_output); } - return %host; -} -############################### -## GET host location -# -sub get_hostlocation($) { - my $self = shift; + ###################################################################### + # Force service execution with external command + if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_reschedule_svc_enable}) && + $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_reschedule_svc_enable} == 1) { + $self->forceCheck(); + } - my ($status, $sth) = $self->{cdb}->query("SELECT localhost FROM host, `ns_host_relation`, nagios_server WHERE host.host_id = ns_host_relation.host_host_id AND ns_host_relation.nagios_server_id = nagios_server.id AND host.host_name = '".$_[0]."'"); - if ($sth->rows()){ - my $temp = $sth->fetchrow_array(); - $sth->finish(); - return $temp; - } else { - return 0; + ###################################################################### + # Execute special command + if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command_enable}) && + $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command_enable} == 1) { + $self->executeCommand($traps_output, $status); } } -################################## -## GET nagios server id for a host -# -sub get_hostNagiosServerID($) { +sub manage_exec { my $self = shift; - my ($status, $sth) = $self->{cdb}->query("SELECT id FROM host, `ns_host_relation`, nagios_server WHERE host.host_id = ns_host_relation.host_host_id AND ns_host_relation.nagios_server_id = nagios_server.id AND (host.host_name = '".$_[0]."' OR host.host_address = '".$_[0]."')"); - if ($sth->rows()){ - my $temp = $sth->fetchrow_array(); - $sth->finish(); - return $temp; - } else { - return 0; + if ($self->{centreontrapd_config}->{daemon} == 0) { + eval { + local $SIG{ALRM} = sub { die "TIMEOUT"; }; + alarm($self->{centreontrapd_config}->{cmd_timeout}); + $self->do_exec(); + alarm(0); + }; + if ($@) { + $self->{logger}->writeLogError("ERROR: Exec timeout"); + return 0; + } + return 1; } -} - -##################################################################### -## GET SERVICES FOR GIVEN HOST (GETTING SERVICES TEMPLATES IN ACCOUNT) -# -sub getServicesIncludeTemplate($$$) { - my $self = shift; - my $status; - my ($sth_st, $host_id, $trap_id) = @_; - my @service; - while (my @temp = $sth_st->fetchrow_array()) { - my $tr_query = "SELECT `traps_id` FROM `traps_service_relation` WHERE `service_id` = '".$temp[0]."' AND `traps_id` = '".$trap_id."'"; - ($status, my $sth_st3) = $self->{cdb}->query($tr_query); - my @trap = $sth_st3->fetchrow_array(); - if (defined($trap[0])) { - $service[scalar(@service)] = $temp[1]; - } else { - if (defined($temp[2])) { - my $found = 0; - my $service_template = $temp[2]; - while (!$found) { - my $st1_query = "SELECT `service_id`, `service_template_model_stm_id`, `service_description` FROM service s WHERE `service_id` = '".$service_template."'"; - ($status, my $sth_st1) = $self->{cdb}->query($st1_query); - my @st1_result = $sth_st1->fetchrow_array(); - if (defined($st1_result[0])) { - ($status, my $sth_st2) = $self->{cdb}->query("SELECT `traps_id` FROM `traps_service_relation` WHERE `service_id` = '".$service_template."' AND `traps_id` = '".$trap_id."'"); - my @st2_result = $sth_st2->fetchrow_array(); - if (defined($st2_result[0])) { - $found = 1; - $service[scalar(@service)] = $temp[1]; - } else { - $found = 1; - if (defined($st1_result[1]) && $st1_result[1]) { - $service_template = $st1_result[1]; - $found = 0; - } - } - $sth_st2->finish; - } - $sth_st1->finish; - } + #### Fork And manage exec #### + ####### Check Interval ###### + if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type}) && + defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval})) && + ) { + # OID type + if ($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type} == 1 && + defined($self->{last_time_exec}{oid}->{$self->{current_oid}}) && + $self->{trap_date_time_epoch} < ($self->{last_time_exec}{oid}->{$self->{current_oid}} + $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval})) { + $self->{logger}->writeLogInfo("Skipping trap '" . $self->{current_trap_id} . "': time interval"); + return 1; + } + + # Host type + if ($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type} == 2 && + defined($self->{last_time_exec}{host}->{$self->{current_host_id} . ";" . $self->{current_oid}}) && + $self->{trap_date_time_epoch} < ($self->{last_time_exec}{host}->{$self->{current_host_id} . ";" . $self->{current_oid}} + $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval})) { + $self->{logger}->writeLogInfo("Skipping trap '" . $self->{current_trap_id} . "' for host ID '" . $self->{current_host_id} . "': time interval"); + return 1; + } + } + + my $current_pid = fork(); + if (!$current_pid) { + eval { + $self->{ref_services}->{$service_id}->{service_description} + my $alarm_timeout = $self->{centreontrapd_config}->{cmd_timeout}; + if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_timeout})) { + $alarm_timeout = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_timeout}; } + + local $SIG{ALRM} = sub { die "TIMEOUT"; }; + alarm($alarm_timeout); + $self->do_exec(); + alarm(0); + }; + if ($@) { + $self->{logger}->writeLogError("ERROR: Exec timeout"); + exit(0); } - $sth_st3->finish; + exit(1); } - return (@service); -} - - - -########################## -# GET SERVICE DESCRIPTION -# -sub getServiceInformations($$) { - my $self = shift; - my $status; - ($status, my $sth) = $self->{cdb}->query("SELECT `traps_id`, `traps_status`, `traps_submit_result_enable`, `traps_execution_command`, `traps_reschedule_svc_enable`, `traps_execution_command_enable`, `traps_advanced_treatment`, `traps_args` FROM `traps` WHERE `traps_oid` = '$_[0]'"); - my ($trap_id, $trap_status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output) = $sth->fetchrow_array(); - return(undef) if (!defined $trap_id); - $sth->finish(); - - ###################################################### - # getting all "services by host" for given host - my $st_query = "SELECT s.service_id, service_description, service_template_model_stm_id FROM service s, host_service_relation h"; - $st_query .= " where s.service_id = h.service_service_id and h.host_host_id='$_[1]'"; - ($status, my $sth_st) = $self->{cdb}->query($st_query); - my @service = $self->getServicesIncludeTemplate($sth_st, $_[1], $trap_id); - $sth_st->finish; - - ###################################################### - # getting all "services by hostgroup" for given host - my $query_hostgroup_services = "SELECT s.service_id, service_description, service_template_model_stm_id FROM hostgroup_relation hgr, service s, host_service_relation hsr"; - $query_hostgroup_services .= " WHERE hgr.host_host_id = '".$_[1]."' AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id"; - $query_hostgroup_services .= " AND s.service_id = hsr.service_service_id"; - ($status, $sth_st) = $self->{cdb}->query($query_hostgroup_services); - @service = (@service, $self->getServicesIncludeTemplate($sth_st, $_[1], $trap_id)); - $sth_st->finish; - - return $trap_id, $trap_status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, \@service; + $self->{logger}->writeLogInfo("CHLD command launched: $current_pid"); + $self->{running_processes}->{$current_pid} = 1; + $self->{last_time_exec}{oid}->{$self->{current_oid}} = $self->{trap_date_time_epoch}; + $self->{last_time_exec}{host}->{$self->{current_host_id} . ";" . $self->{current_oid}} = $self->{trap_date_time_epoch}; + return 1; } ###################################### ## Force a new check for selected services # -sub forceCheck($$$) { +sub forceCheck { my $self = shift; - my ($this_host, $this_service, $datetime) = @_; - my $result; + my $datetime = time(); + my $submit; - my $id = $self->get_hostNagiosServerID($this_host); - if (defined($id) && $id != 0) { - my $submit; - - if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { - $submit = "/bin/echo \"EXTERNALCMD:$id:[$datetime] SCHEDULE_FORCED_SVC_CHECK;$this_host;$this_service;$datetime\" >> " . $self->{centreontrapd_config}->{cmdFile}; - } else { - $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] SCHEDULE_FORCED_SVC_CHECK;$this_host;$this_service;$datetime\" >> " . $self->{centreontrapd_config}->{cmdFile} . "'"; - } - $result = $self->manage_exec($submit); + my $str = "SCHEDULE_FORCED_SVC_CHECK;$self->{current_hostname};$self->{current_service_desc};$datetime"; - $self->{logger}->writeLogInfo("FORCE: Reschedule linked service"); - $self->{logger}->writeLogInfo("FORCE: Launched command: $submit"); + if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { + $str =~ s/"/\\"/g; + $submit = "/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile}; + } else { + $str =~ s/'/'\\''/g; + $str =~ s/"/\\"/g; + $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile} . "' 2>&1"; + } + my $stdout = `$submit`; + + $self->{logger}->writeLogInfo("FORCE: Reschedule linked service"); + $self->{logger}->writeLogInfo("FORCE: Launched command: $submit"); + if (defined($stdout)) { + $self->{logger}->writeLogError("FORCE stdout: $stdout"); } - return $result; } ####################################### ## Submit result via external command # -sub submitResult($$$$$) { +sub submitResult { my $self = shift; - my ($this_host, $this_service, $datetime, $status, $traps_output) = @_; - my $result; - - # No matching rules - my $id = $self->get_hostNagiosServerID($this_host); - if (defined($id) && $id != 0) { - my $str = "PROCESS_SERVICE_CHECK_RESULT;$this_host;$this_service;$status;$traps_output"; - - my $submit; - if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { - $str =~ s/"/\\"/g; - $submit = "/bin/echo \"EXTERNALCMD:$id:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile}; - } else { - $str =~ s/'/'\\''/g; - $str =~ s/"/\\"/g; - $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$id:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile} . "'"; - } - $result = $self->manage_exec($submit); + my ($status, $traps_output) = @_; + my $datetime = time(); + + my $str = "PROCESS_SERVICE_CHECK_RESULT;$self->{current_hostname};$self->{current_service_desc};$status;$traps_output"; + + my $submit; + if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { + $str =~ s/"/\\"/g; + $submit = "/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile}; + } else { + $str =~ s/'/'\\''/g; + $str =~ s/"/\\"/g; + $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile} . "' 2>&1"; + } + my $stdout = `$submit`; - $self->{logger}->writeLogInfo("SUBMIT: Force service status via passive check update"); - $self->{logger}->writeLogInfo("SUBMIT: Launched command: $submit"); + $self->{logger}->writeLogInfo("SUBMIT: Force service status via passive check update"); + $self->{logger}->writeLogInfo("SUBMIT: Launched command: $submit"); + if (defined($stdout)) { + $self->{logger}->writeLogError("SUBMIT RESULT stdout: $stdout"); } - return $result; } ########################## @@ -457,13 +404,16 @@ sub substitute_string { ####################################### ## Check Advanced Matching Rules # -sub checkMatchingRules($$$$$$$$$) { +sub checkMatchingRules { my $self = shift; - my ($trap_id, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status) = @_; + my ($traps_output, $status) = @_; # Check matching options - my ($dstatus, $sth) = $self->{cdb}->query("SELECT tmo_regexp, tmo_status, tmo_string FROM traps_matching_properties WHERE trap_id = '".$trap_id."' ORDER BY tmo_order"); - while (my ($regexp, $tmoStatus, $tmoString) = $sth->fetchrow_array()) { + foreach my $tmo_id (keys %{$self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}}) { + my $tmoString = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_string}; + my $regexp = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_regexp}; + my $tmoStatus = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_status}; + $self->{logger}->writeLogDebug("[$tmoString][$regexp] => $tmoStatus"); my @temp = split(//, $regexp); @@ -481,7 +431,7 @@ sub checkMatchingRules($$$$$$$$$) { $i++; } - $tmoString = substitute_string($tmoString); + $tmoString = $self->substitute_string($tmoString); ########################## # REPLACE special Chars @@ -491,13 +441,13 @@ sub checkMatchingRules($$$$$$$$$) { $tmoString =~ s/\"\;/\"/g; $tmoString =~ s/\'\;\'\;/"/g; } - $tmoString =~ s/\@HOSTNAME\@/$this_host/g; - $tmoString =~ s/\@HOSTADDRESS\@/$ip/g; - $tmoString =~ s/\@HOSTADDRESS2\@/$hostname/g; - $tmoString =~ s/\@SERVICEDESC\@/$this_service/g; + $tmoString =~ s/\@HOSTNAME\@/$self->{current_hostname}/g; + $tmoString =~ s/\@HOSTADDRESS\@/$self->{current_ip}/g; + $tmoString =~ s/\@HOSTADDRESS2\@/$self->{agent_dns}/g; + $tmoString =~ s/\@SERVICEDESC\@/$self->{current_service_desc}/g; $tmoString =~ s/\@TRAPOUTPUT\@/$traps_output/g; $tmoString =~ s/\@OUTPUT\@/$traps_output/g; - $tmoString =~ s/\@TIME\@/$datetime/g; + $tmoString =~ s/\@TIME\@/$self->{trap_date_time_epoch}/g; # Integrate OID Matching if (defined($tmoString) && $tmoString =~ m/$regexp/g) { @@ -513,9 +463,11 @@ sub checkMatchingRules($$$$$$$$$) { ################################ ## Execute a specific command # -sub executeCommand($$$$$$$$) { +sub executeCommand { my $self = shift; - my ($traps_execution_command, $this_host, $this_service, $ip, $hostname, $traps_output, $datetime, $status) = @_; + my ($traps_output, $status) = @_; + my $datetime = time(); + my $traps_execution_command = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command}; $traps_execution_command = $self->substitute_string($traps_execution_command); @@ -528,10 +480,10 @@ sub executeCommand($$$$$$$$) { $traps_execution_command =~ s/\'\;\'\;/"/g; $traps_execution_command =~ s/\'\;/'/g; } - $traps_execution_command =~ s/\@HOSTNAME\@/$this_host/g; - $traps_execution_command =~ s/\@HOSTADDRESS\@/$_[1]/g; - $traps_execution_command =~ s/\@HOSTADDRESS2\@/$_[2]/g; - $traps_execution_command =~ s/\@SERVICEDESC\@/$this_service/g; + $traps_execution_command =~ s/\@HOSTNAME\@/$self->{current_hostname}/g; + $traps_execution_command =~ s/\@HOSTADDRESS\@/$self->{current_ip}/g; + $traps_execution_command =~ s/\@HOSTADDRESS2\@/$self->{agent_dns}/g; + $traps_execution_command =~ s/\@SERVICEDESC\@/$self->{current_service_desc}/g; $traps_execution_command =~ s/\@TRAPOUTPUT\@/$traps_output/g; $traps_execution_command =~ s/\@OUTPUT\@/$traps_output/g; $traps_execution_command =~ s/\@STATUS\@/$status/g; @@ -557,67 +509,59 @@ sub executeCommand($$$$$$$$) { ####################################### ## GET HOSTNAME AND SERVICE DESCRIPTION # -sub getTrapsInfos($) { +sub getTrapsInfos { my $self = shift; - my $hostname = shift; - my ($status, $dstatus); - my ($ref_oids); - + my ($fstatus); + $self->{current_ip} = ${$self->{var}}[1]; $self->{current_oid} = ${$self->{var}}[3]; + # Use $self->{agent_dns_name} (IP or HOSTNAME with split) ### Get OIDS - ($dstatus, $ref_oids) = centreon::trapd::lib::get_oids($self->{cdb}, $self->{current_oid}); - return 0 if ($dstatus == -1); - foreach (keys %$ref_oids) { - ##### Get Hosts - print Data::Dumper::Dumper($ref_oids); - } - - exit(1); - - my %host = $self->get_hostinfos($self->{current_ip}, $hostname); - foreach my $host_id (keys %host) { - $self->{current_host_id} = $host_id; - my $this_host = $host{$host_id}; - my ($trap_id, $status, $traps_submit_result_enable, $traps_execution_command, $traps_reschedule_svc_enable, $traps_execution_command_enable, $traps_advanced_treatment, $traps_output, $ref_servicename) = $self->getServiceInformations($self->{current_oid}, $host_id); - if (!defined($trap_id)) { - return ; - } - my @servicename = @{$ref_servicename}; - - foreach (@servicename) { - my $this_service = $_; - - $self->{logger}->writeLogDebug("Trap found on service \'$this_service\' for host \'$this_host\'."); - - my $datetime = `date +%s`; - chomp($datetime); - - $traps_output = $self->substitute_string($traps_output); - - ###################################################################### - # Advanced matching rules - if (defined($traps_advanced_treatment) && $traps_advanced_treatment eq 1) { - $status = $self->checkMatchingRules($trap_id, $this_host, $this_service, $self->{current_ip}, $hostname, $traps_output, $datetime, $status); + ($fstatus, $self->{ref_oids}) = centreon::trapd::lib::get_oids($self->{cdb}, $self->{current_oid}); + return 0 if ($fstatus == -1); + foreach my $trap_id (keys %$self->{ref_oids}) { + $self->{current_trap_id} = $trap_id; + ($fstatus, $self->{ref_hosts}) = centreon::trapd::lib::get_hosts(logger => $self->{logger}, + cdb => $self->{cdb}, + trap_info => $self->{ref_oids}->{$trap_id}, + agent_dns_name => $self->{agent_dns}, + ip_address => $self->{current_ip}, + entvar => \@{$self->{entvar}}, + entvarname => \@{$self->{entvarname}}); + return 0 if ($fstatus == -1); + foreach my $host_id (keys %$self->{ref_hosts}) { + if (!defined($self->{ref_hosts}->{$host_id}->{nagios_server_id})) { + $self->{logger}->writeLogError("Cant get server associated for host '" . $self->{ref_hosts}->{$host_id}->{host_name} . "'"); + next; } + $self->{current_host_id} = $host_id; + $self->{current_server_id} = $self->{ref_hosts}->{$host_id}->{nagios_server_id}; + $self->{current_hostname} = $self->{ref_hosts}->{$host_id}->{host_name}; - ##################################################################### - # Submit value to passive service - if (defined($traps_submit_result_enable) && $traps_submit_result_enable eq 1) { - $self->submitResult($this_host, $this_service, $datetime, $status, $traps_output); + #### Get Services #### + ($fstatus, $self->{ref_services}) = centreon::trapd::lib::get_services($self->[cdb}, $trap_id, $host_id); + return 0 if ($fstatus == -1); + + #### If none, we stop #### + my $size = keys %$self->{ref_services}; + if ($size < 1) { + $self->{logger}->writeLogDebug("Trap without service associated. Skipping..."); + return 1; } - - ###################################################################### - # Force service execution with external command - if (defined($traps_reschedule_svc_enable) && $traps_reschedule_svc_enable eq 1) { - $self->forceCheck($this_host, $this_service, $datetime); + + #### Check if macro $_HOST*$ needed + if (defined($self->{ref_oids}->{$trap_id}->{traps_execution_command_enable}) && $self->{ref_oids}->{$trap_id}->{traps_execution_command_enable} == 1 && + defined($self->{ref_oids}->{$trap_id}->{traps_execution_command}) && $self->{ref_oids}->{$trap_id}->{traps_execution_command} =~ /\$_HOST*?\$/) { + ($fstatus, $ref_macro_hosts) = centreon::trapd::lib::get_macros_host($self->{cdb}, $host_id); + return 0 if ($fstatus == -1); } - - ###################################################################### - # Execute special command - if (defined($traps_execution_command_enable) && $traps_execution_command_enable) { - $self->executeCommand($traps_execution_command, $this_host, $this_service, $self->{current_ip}, $hostname, $traps_output, $datetime, $status); + + foreach my $service_id (keys %$self->{ref_services}) { + $self->{current_service_id} = $service_id; + $self->{current_service_desc} = $self->{ref_services}->{$service_id}->{service_description}; + $self->{logger}->writeLogDebug("Trap found on service '" . $self->{ref_services}->{$service_id}->{service_description} . "' for host '" . $self->{ref_hosts}->{$host_id}->{host_name} . "'."); + $self->manage_exec(); } } } @@ -652,9 +596,6 @@ sub run { $self->{cmdFile} = $conf[0]; } $self->{whoami} = getpwuid($<); - - centreon::trapd::lib::get_macros_host(14); - exit(1); if ($self->{centreontrapd_config}->{daemon} == 1) { while (1) { @@ -699,7 +640,7 @@ sub run { cdb => $self->{cdb}, last_cache_time => \$self->{last_cache_time}, oids_cache => \$self->{oids_cache}) == 1) { - $unlink_trap = $self->getTrapsInfos(${$self->{var}}[2]); + $unlink_trap = $self->getTrapsInfos(); } } elsif ($readtrap_result == 0) { $self->{logger}->writeLogDebug("Error processing trap file $file. Skipping..."); @@ -764,7 +705,7 @@ sub run { cdb => $self->{cdb}, last_cache_time => \$self->{last_cache_time}, oids_cache => \$self->{oids_cache}) == 1) { - $self->getTrapsInfos(${$self->{var}}[2]); + $self->getTrapsInfos(); } } elsif ($readtrap_result == 0) { $self->{logger}->writeLogDebug("Error processing trap file. Skipping..."); diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 314984b5e89..550af32f3c2 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -90,12 +90,105 @@ sub manage_params_conf { # DB Request ############## +# We get All datas for a TRAP sub get_oids { my ($cdb, $oid) = @_; + my $ref_result; - ($dstatus, $sth) = $cdb->query("SELECT * FROM traps WHERE traps_oid = " . $cdb->quote($oid)); + my ($dstatus, $sth) = $cdb->query("SELECT traps_execution_command, traps_reschedule_svc_enable, traps_id, traps_args, + traps_oid, traps_name, traps_advanced_treatment, traps_execution_command_enable, traps_submit_result_enable, traps_status, + traps_timeout, traps_exec_interval, traps_exec_interval_type FROM traps WHERE traps_oid = " . $cdb->quote($oid)); return -1 if ($dstatus == -1); - return (0, $cdb->fetchall_hashref('traps_id')); + $ref_result = $sth->fetchall_hashref('traps_id'); + + foreach (keys %$ref_result) { + # Get Matching Status Rules + if (defined($ref_result->{$_}->{traps_advanced_treatment}) && $ref_result->{$_}->{traps_advanced_treatment} == 1) { + ($dstatus, $sth) = $cdb->query("SELECT * FROM traps_matching_properties WHERE trap_id = " . $_ . " ORDER BY id ASC"); + return -1 if ($dstatus == -1); + $ref_result->{$_}->{traps_matching_properties} = $sth->fetchall_hashref("tmo_id"); + } + + # Get Trap PREEXEC Commands + #($dstatus, $sth) = $cdb->query(""); + + # Get Associated Host + # TODO + } + return (0, $ref_result); +} + +sub get_hosts { + # logger => obj + # cbd => obj + # trap_info => ref + # agent_dns_name => value + # ip_address => value + # entvar => ref array + # entvarname => ref array + my %args = @_; + my ($dstatus, $sth); + my $ref_result; + + ($dstatus, $sth) = $args{cbd}->query("SELECT host_id, host_name FROM host WHERE + host_address=" . $args{cbd}->quote($args{agent_dns_name}) . " OR host_address=" . $args{cbd}->quote($args{ip_address})); + return -1 if ($dstatus == -1); + $ref_result = $sth->fetchall_hashref('host_id'); + + # Get server_id + foreach (keys %$ref_result) { + ($dstatus, $sth) = $args{cbd}->query("SELECT nagios_server_id FROM ns_host_relation WHERE + host_host_id = " . $ref_result->{$_}->{host_id} . " LIMIT 1"); + return -1 if ($dstatus == -1); + my $data = $sth->fetchrow_hashref(); + $ref_result->{$_}->{nagios_server_id} = $data->{nagios_server_id}; + } + + return (0, $ref_result); +} + +sub get_services { + my ($cdb, $trap_id, $host_id, $result) = @_; + my $services_do = {}; + + ### Get service List for the Host + ($dstatus, $sth) = $args{cbd}->query("(SELECT s.service_id, s.service_description FROM host h, host_service_relation hsr, service s WHERE + h.host_id = " . $host_id . " h.host_activate = '1' AND h.host_id = hsrc.host_host_id AND hsr.service_service_id = s.service_id AND s.service_activate = '1' + ) UNION ALL (SELECT s.service_id, s.service_description FROM + host h, host_service_relation hsr, hostgroup_relation hgr, service s WHERE h.host_id = " . $host_id . " h.host_activate = '1' AND + h.host_id = hgr.host_host_id AND hgr.hostgroup_hg_id = hsr.hostgroup_hg_id AND hsr.service_service_id = s.service_id AND s.service_activate = '1')"); + return -1 if ($dstatus == -1); + $result = $sth->fetchall_hashref('service_id'); + foreach my $service_id (keys %$result) { + # Search Template trap_id + my %loop_stop = (); + my @stack = ($service_id); + + while ((my $lservice_id = shift(@stack))) { + if (defined($loop_stop{$lservice_id})) { + # Already done + last; + } + $loop_stop{$lservice_id} = 1; + + ($dstatus, $sth) = $args{cbd}->query("SELECT traps_id FROM traps_service_relation WHERE service_id = '" . $lservice_id . "' AND traps_id = '" . $trap_id . "' LIMIT 1"); + return -1 if ($dstatus == -1); + my $data = $sth->fetchrow_hashref(); + if (defined($data)) { + $services_do->{$service_id} = $result->{$service_id}; + last; + } + + ($dstatus, $sth) = $args{cbd}->query("SELECT service_template_model_stm_id FROM service WHERE service_id = " . $lservice_id . " LIMIT 1"); + return -1 if ($dstatus == -1); + $data = $sth->fetchrow_hashref(); + if (defined($data) && defined($data->{service_template_model_stm_id})) { + unshift @stack, $data->{service_template_model_stm_id}; + } + } + } + + return (0, $service_do); } sub set_macro { From 374c139febb346012343ab083975c94c64876903 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 11 Apr 2013 17:52:53 +0200 Subject: [PATCH 053/458] Fix compil errors --- .../lib/perl/centreon/script/centreontrapd.pm | 24 +++++++++++-------- centreon/lib/perl/centreon/trapd/lib.pm | 14 ++++++----- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 8c7a6992ea8..6fdd82011ea 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -91,6 +91,7 @@ sub new { # For policy_trap = 1 (temp). To avoid doing the same thing twice # ID oid ===> Host ID ===> Service ID %{$self->{policy_trap_skip}} = (); + $self->{digest_trap} = undef; $self->{cmdFile} = undef; @@ -276,8 +277,7 @@ sub manage_exec { #### Fork And manage exec #### ####### Check Interval ###### if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type}) && - defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval})) && - ) { + defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval})) { # OID type if ($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type} == 1 && defined($self->{last_time_exec}{oid}->{$self->{current_oid}}) && @@ -298,7 +298,6 @@ sub manage_exec { my $current_pid = fork(); if (!$current_pid) { eval { - $self->{ref_services}->{$service_id}->{service_description} my $alarm_timeout = $self->{centreontrapd_config}->{cmd_timeout}; if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_timeout})) { $alarm_timeout = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_timeout}; @@ -520,7 +519,7 @@ sub getTrapsInfos { ### Get OIDS ($fstatus, $self->{ref_oids}) = centreon::trapd::lib::get_oids($self->{cdb}, $self->{current_oid}); return 0 if ($fstatus == -1); - foreach my $trap_id (keys %$self->{ref_oids}) { + foreach my $trap_id (keys %{$self->{ref_oids}}) { $self->{current_trap_id} = $trap_id; ($fstatus, $self->{ref_hosts}) = centreon::trapd::lib::get_hosts(logger => $self->{logger}, cdb => $self->{cdb}, @@ -530,7 +529,7 @@ sub getTrapsInfos { entvar => \@{$self->{entvar}}, entvarname => \@{$self->{entvarname}}); return 0 if ($fstatus == -1); - foreach my $host_id (keys %$self->{ref_hosts}) { + foreach my $host_id (keys %{$self->{ref_hosts}}) { if (!defined($self->{ref_hosts}->{$host_id}->{nagios_server_id})) { $self->{logger}->writeLogError("Cant get server associated for host '" . $self->{ref_hosts}->{$host_id}->{host_name} . "'"); next; @@ -540,11 +539,11 @@ sub getTrapsInfos { $self->{current_hostname} = $self->{ref_hosts}->{$host_id}->{host_name}; #### Get Services #### - ($fstatus, $self->{ref_services}) = centreon::trapd::lib::get_services($self->[cdb}, $trap_id, $host_id); + ($fstatus, $self->{ref_services}) = centreon::trapd::lib::get_services($self->{cdb}, $trap_id, $host_id); return 0 if ($fstatus == -1); #### If none, we stop #### - my $size = keys %$self->{ref_services}; + my $size = keys %{$self->{ref_services}}; if ($size < 1) { $self->{logger}->writeLogDebug("Trap without service associated. Skipping..."); return 1; @@ -553,11 +552,11 @@ sub getTrapsInfos { #### Check if macro $_HOST*$ needed if (defined($self->{ref_oids}->{$trap_id}->{traps_execution_command_enable}) && $self->{ref_oids}->{$trap_id}->{traps_execution_command_enable} == 1 && defined($self->{ref_oids}->{$trap_id}->{traps_execution_command}) && $self->{ref_oids}->{$trap_id}->{traps_execution_command} =~ /\$_HOST*?\$/) { - ($fstatus, $ref_macro_hosts) = centreon::trapd::lib::get_macros_host($self->{cdb}, $host_id); + ($fstatus, $self->{ref_macro_hosts}) = centreon::trapd::lib::get_macros_host($self->{cdb}, $host_id); return 0 if ($fstatus == -1); } - foreach my $service_id (keys %$self->{ref_services}) { + foreach my $service_id (keys %{$self->{ref_services}}) { $self->{current_service_id} = $service_id; $self->{current_service_desc} = $self->{ref_services}->{$service_id}->{service_description}; $self->{logger}->writeLogDebug("Trap found on service '" . $self->{ref_services}->{$service_id}->{service_description} . "' for host '" . $self->{ref_hosts}->{$host_id}->{host_name} . "'."); @@ -629,6 +628,7 @@ sub run { trap_date_time => \$self->{trap_date_time}, trap_date_time_epoch => \$self->{trap_date_time_epoch}, duplicate_traps => \%{$self->{duplicate_traps}}, + digest_trap => \$self->{digest_trap}, var => \@{$self->{var}}, entvar => \@{$self->{entvar}}, entvarname => \@{$self->{entvarname}}); @@ -656,8 +656,11 @@ sub run { } } else { $self->{logger}->writeLogError("Dont skip trap. Need to solve the error."); - # we reput in + # we reput in AND we delete trap_digest (avoid skipping duplicate trap) unshift @{$self->{filenames}}, $file; + if ($self->{centreontrapd_config}->{duplicate_trap_window}) { + delete $self->{duplicate_traps}->{$self->{digest_trap}}; + } } } else { $self->{logger}->writeLogError("Could not open trap file " . $self->{centreontrapd_config}->{spool_directory} . "$file: ($!)"); @@ -695,6 +698,7 @@ sub run { trap_date_time => \$self->{trap_date_time}, trap_date_time_epoch => \$self->{trap_date_time_epoch}, duplicate_traps => \%{$self->{duplicate_traps}}, + digest_trap => \$self->{digest_trap}, var => \@{$self->{var}}, entvar => \@{$self->{entvar}}, entvarname => \@{$self->{entvarname}}); diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 550af32f3c2..a07c31044d9 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -130,14 +130,14 @@ sub get_hosts { my ($dstatus, $sth); my $ref_result; - ($dstatus, $sth) = $args{cbd}->query("SELECT host_id, host_name FROM host WHERE + ($dstatus, $sth) = $args{cdb}->query("SELECT host_id, host_name FROM host WHERE host_address=" . $args{cbd}->quote($args{agent_dns_name}) . " OR host_address=" . $args{cbd}->quote($args{ip_address})); return -1 if ($dstatus == -1); $ref_result = $sth->fetchall_hashref('host_id'); # Get server_id foreach (keys %$ref_result) { - ($dstatus, $sth) = $args{cbd}->query("SELECT nagios_server_id FROM ns_host_relation WHERE + ($dstatus, $sth) = $args{cdb}->query("SELECT nagios_server_id FROM ns_host_relation WHERE host_host_id = " . $ref_result->{$_}->{host_id} . " LIMIT 1"); return -1 if ($dstatus == -1); my $data = $sth->fetchrow_hashref(); @@ -152,7 +152,7 @@ sub get_services { my $services_do = {}; ### Get service List for the Host - ($dstatus, $sth) = $args{cbd}->query("(SELECT s.service_id, s.service_description FROM host h, host_service_relation hsr, service s WHERE + my ($dstatus, $sth) = $cdb->query("(SELECT s.service_id, s.service_description FROM host h, host_service_relation hsr, service s WHERE h.host_id = " . $host_id . " h.host_activate = '1' AND h.host_id = hsrc.host_host_id AND hsr.service_service_id = s.service_id AND s.service_activate = '1' ) UNION ALL (SELECT s.service_id, s.service_description FROM host h, host_service_relation hsr, hostgroup_relation hgr, service s WHERE h.host_id = " . $host_id . " h.host_activate = '1' AND @@ -171,7 +171,7 @@ sub get_services { } $loop_stop{$lservice_id} = 1; - ($dstatus, $sth) = $args{cbd}->query("SELECT traps_id FROM traps_service_relation WHERE service_id = '" . $lservice_id . "' AND traps_id = '" . $trap_id . "' LIMIT 1"); + ($dstatus, $sth) = $cdb->query("SELECT traps_id FROM traps_service_relation WHERE service_id = '" . $lservice_id . "' AND traps_id = '" . $trap_id . "' LIMIT 1"); return -1 if ($dstatus == -1); my $data = $sth->fetchrow_hashref(); if (defined($data)) { @@ -179,7 +179,7 @@ sub get_services { last; } - ($dstatus, $sth) = $args{cbd}->query("SELECT service_template_model_stm_id FROM service WHERE service_id = " . $lservice_id . " LIMIT 1"); + ($dstatus, $sth) = $cdb->query("SELECT service_template_model_stm_id FROM service WHERE service_id = " . $lservice_id . " LIMIT 1"); return -1 if ($dstatus == -1); $data = $sth->fetchrow_hashref(); if (defined($data) && defined($data->{service_template_model_stm_id})) { @@ -188,7 +188,7 @@ sub get_services { } } - return (0, $service_do); + return (0, $services_do); } sub set_macro { @@ -414,6 +414,7 @@ sub readtrap { # trap_date_time => ref # trap_date_time_epoch => ref # duplicate_traps => ref hash + # digest_trap => ref, # var => ref array # entvar => ref array # entvarname => ref array @@ -759,6 +760,7 @@ sub readtrap { $md5->add(${$args{var}}[0],${$args{var}}[1].${$args{var}}[3].${$args{var}}[4].${$args{var}}[5].${$args{var}}[6].${$args{var}}[7].${$args{var}}[8].${$args{var}}[9].${$args{var}}[10]."@{$args{entvar}}"); my $trap_digest = $md5->hexdigest; + ${$args{trap_date_time}} = $trap_digest; $args{logger}->writeLogDebug("Trap digest: $trap_digest"); From ea0c3947b135e85578398eb0fafafc441b03b5ba Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 11 Apr 2013 18:10:03 +0200 Subject: [PATCH 054/458] Fix compil --- centreon/lib/perl/centreon/script/centreontrapd.pm | 1 + centreon/lib/perl/centreon/trapd/lib.pm | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 6fdd82011ea..d5f4475d1c4 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -661,6 +661,7 @@ sub run { if ($self->{centreontrapd_config}->{duplicate_trap_window}) { delete $self->{duplicate_traps}->{$self->{digest_trap}}; } + sleep $self->{centreontrapd_config}->{sleep}; } } else { $self->{logger}->writeLogError("Could not open trap file " . $self->{centreontrapd_config}->{spool_directory} . "$file: ($!)"); diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index a07c31044d9..53837c8924a 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -760,7 +760,7 @@ sub readtrap { $md5->add(${$args{var}}[0],${$args{var}}[1].${$args{var}}[3].${$args{var}}[4].${$args{var}}[5].${$args{var}}[6].${$args{var}}[7].${$args{var}}[8].${$args{var}}[9].${$args{var}}[10]."@{$args{entvar}}"); my $trap_digest = $md5->hexdigest; - ${$args{trap_date_time}} = $trap_digest; + ${$args{digest_trap}} = $trap_digest; $args{logger}->writeLogDebug("Trap digest: $trap_digest"); From f74d91dfdcd28010a2a0aefcba96ec4cf968e385 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 12 Apr 2013 10:54:28 +0200 Subject: [PATCH 055/458] Continue manage centreontrapd --- .../lib/perl/centreon/script/centreontrapd.pm | 37 ++++++++++++++++--- centreon/lib/perl/centreon/trapd/lib.pm | 8 ++-- 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index d5f4475d1c4..a78fe5c5394 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -3,6 +3,7 @@ package centreon::script::centreontrapd; use strict; use warnings; +use POSIX; use centreon::script; use centreon::common::db; use centreon::trapd::lib; @@ -27,6 +28,7 @@ sub new { %{$self->{centreontrapd_default_config}} = ( daemon => 1, + timeout_end => 30, spool_directory => "/var/spool/centreontrapd/", sleep => 2, use_trap_time => 1, @@ -180,9 +182,25 @@ sub handle_DIE { my $self = shift; my $msg = shift; - # We get SIGCHLD signals $self->{logger}->writeLogInfo($msg); - + + # We're waiting n seconds + for (my $i = 0; $i < $self->{centreontrapd_config}->{timeout_end}; $i++) { + $self->manage_pool(); + if (keys %{$self->{running_processes}} == 0) { + $self->{logger}->writeLogInfo("Main process exit."); + exit(0); + } + sleep 1; + } + + $self->{logger}->writeLogInfo("Dont handle gently. Send KILl Signals to childs"); + # We are killing + foreach (keys %{$self->{running_processes}}) { + kill('KILL', $_); + $self->{logger}->writeLogInfo("Send -KILL signal to child process '$_'.."); + } + exit(0); } @@ -297,6 +315,10 @@ sub manage_exec { my $current_pid = fork(); if (!$current_pid) { + # Unhandle die in child + $SIG{CHLD} = undef; + $SIG{__DIE__} = undef; + $self->{cdb}->set_inactive_destroy(); eval { my $alarm_timeout = $self->{centreontrapd_config}->{cmd_timeout}; if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_timeout})) { @@ -392,7 +414,7 @@ sub substitute_string { } # Substitute $* - my $sub_str = join($self->{centreontrapd_config}->{seperator}, @{$self->{entvar}}); + my $sub_str = join($self->{centreontrapd_config}->{separator}, @{$self->{entvar}}); $str =~ s/\$\*/$sub_str/g; # Clean OID @@ -495,10 +517,13 @@ sub executeCommand { $self->{logger}->writeLogInfo("EXEC: Launched command: $traps_execution_command"); my $output = `$traps_execution_command`; - if ($?) { + if ($? == -1) { $self->{logger}->writeLogError("EXEC: Execution error: $!"); + } elsif (($? >> 8) != 0) { + $self->{logger}->writeLogInfo("EXEC: Exit command: " . ($? >> 8)); } - if ($output) { + if (defined($output)) { + chomp $output; $self->{logger}->writeLogInfo("EXEC: Output : $output"); } } @@ -550,6 +575,7 @@ sub getTrapsInfos { } #### Check if macro $_HOST*$ needed + $self->{ref_macro_hosts} = undef; if (defined($self->{ref_oids}->{$trap_id}->{traps_execution_command_enable}) && $self->{ref_oids}->{$trap_id}->{traps_execution_command_enable} == 1 && defined($self->{ref_oids}->{$trap_id}->{traps_execution_command}) && $self->{ref_oids}->{$trap_id}->{traps_execution_command} =~ /\$_HOST*?\$/) { ($fstatus, $self->{ref_macro_hosts}) = centreon::trapd::lib::get_macros_host($self->{cdb}, $host_id); @@ -584,7 +610,6 @@ sub run { password => $self->{centreon_config}->{db_passwd}, force => 0, logger => $self->{logger}); - $self->{cdb}->set_inactive_destroy(); if ($self->{centreontrapd_config}->{mode} == 0) { $self->{cmdFile} = $self->{centreon_config}->{cmdFile}; diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 53837c8924a..da8b556d07d 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -104,7 +104,7 @@ sub get_oids { foreach (keys %$ref_result) { # Get Matching Status Rules if (defined($ref_result->{$_}->{traps_advanced_treatment}) && $ref_result->{$_}->{traps_advanced_treatment} == 1) { - ($dstatus, $sth) = $cdb->query("SELECT * FROM traps_matching_properties WHERE trap_id = " . $_ . " ORDER BY id ASC"); + ($dstatus, $sth) = $cdb->query("SELECT * FROM traps_matching_properties WHERE trap_id = " . $_ . " ORDER BY tmo_id ASC"); return -1 if ($dstatus == -1); $ref_result->{$_}->{traps_matching_properties} = $sth->fetchall_hashref("tmo_id"); } @@ -131,7 +131,7 @@ sub get_hosts { my $ref_result; ($dstatus, $sth) = $args{cdb}->query("SELECT host_id, host_name FROM host WHERE - host_address=" . $args{cbd}->quote($args{agent_dns_name}) . " OR host_address=" . $args{cbd}->quote($args{ip_address})); + host_address=" . $args{cdb}->quote($args{agent_dns_name}) . " OR host_address=" . $args{cdb}->quote($args{ip_address})); return -1 if ($dstatus == -1); $ref_result = $sth->fetchall_hashref('host_id'); @@ -153,9 +153,9 @@ sub get_services { ### Get service List for the Host my ($dstatus, $sth) = $cdb->query("(SELECT s.service_id, s.service_description FROM host h, host_service_relation hsr, service s WHERE - h.host_id = " . $host_id . " h.host_activate = '1' AND h.host_id = hsrc.host_host_id AND hsr.service_service_id = s.service_id AND s.service_activate = '1' + h.host_id = " . $host_id . " AND h.host_activate = '1' AND h.host_id = hsr.host_host_id AND hsr.service_service_id = s.service_id AND s.service_activate = '1' ) UNION ALL (SELECT s.service_id, s.service_description FROM - host h, host_service_relation hsr, hostgroup_relation hgr, service s WHERE h.host_id = " . $host_id . " h.host_activate = '1' AND + host h, host_service_relation hsr, hostgroup_relation hgr, service s WHERE h.host_id = " . $host_id . " AND h.host_activate = '1' AND h.host_id = hgr.host_host_id AND hgr.hostgroup_hg_id = hsr.hostgroup_hg_id AND hsr.service_service_id = s.service_id AND s.service_activate = '1')"); return -1 if ($dstatus == -1); $result = $sth->fetchall_hashref('service_id'); From e55d8550f7691a232b72aaf38b05e8e6e64bfab2 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 12 Apr 2013 11:26:12 +0200 Subject: [PATCH 056/458] Host macro test --- centreon/lib/perl/centreon/script/centreontrapd.pm | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index a78fe5c5394..f508c311acd 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -402,6 +402,19 @@ sub submitResult { ########################## ## REPLACE # +sub substitute_host_macro { + my $self = shift; + my $str = $_[0]; + + if (defined($self->{ref_macro_hosts})) { + foreach my $macro_name (keys %{$self->{ref_macro_hosts}}) { + $str =~ s/$macro_name/$self->{ref_macro_hosts}->{$macro_name}/g; + } + } + + return $str; +} + sub substitute_string { my $self = shift; my $str = $_[0]; @@ -491,6 +504,7 @@ sub executeCommand { my $traps_execution_command = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command}; $traps_execution_command = $self->substitute_string($traps_execution_command); + $traps_execution_command = $self->substitute_host_macro($traps_execution_command); ########################## # REPLACE MACROS From 95fe6c3e112ca00b0ba9413ee1d85cd2c8ceaee2 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 12 Apr 2013 17:37:06 +0200 Subject: [PATCH 057/458] Fix HOST macro --- centreon/lib/perl/centreon/script/centreontrapd.pm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index f508c311acd..65297c31a4c 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -408,7 +408,7 @@ sub substitute_host_macro { if (defined($self->{ref_macro_hosts})) { foreach my $macro_name (keys %{$self->{ref_macro_hosts}}) { - $str =~ s/$macro_name/$self->{ref_macro_hosts}->{$macro_name}/g; + $str =~ s/\Q$macro_name\E/\Q$self->{ref_macro_hosts}->{$macro_name}\E/g; } } @@ -591,7 +591,7 @@ sub getTrapsInfos { #### Check if macro $_HOST*$ needed $self->{ref_macro_hosts} = undef; if (defined($self->{ref_oids}->{$trap_id}->{traps_execution_command_enable}) && $self->{ref_oids}->{$trap_id}->{traps_execution_command_enable} == 1 && - defined($self->{ref_oids}->{$trap_id}->{traps_execution_command}) && $self->{ref_oids}->{$trap_id}->{traps_execution_command} =~ /\$_HOST*?\$/) { + defined($self->{ref_oids}->{$trap_id}->{traps_execution_command}) && $self->{ref_oids}->{$trap_id}->{traps_execution_command} =~ /\$_HOST.*?\$/) { ($fstatus, $self->{ref_macro_hosts}) = centreon::trapd::lib::get_macros_host($self->{cdb}, $host_id); return 0 if ($fstatus == -1); } From 60920bd01df4217e4ef9596aed27b62e5ccb3e19 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 15 Apr 2013 15:19:16 +0200 Subject: [PATCH 058/458] Fix centstorage rebuild --- centreon/lib/perl/centreon/centstorage/CentstoragePool.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index 86df5ace468..a5964a39528 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -992,7 +992,7 @@ sub rebuild { $self->{'dbcentstorage'}->set_inactive_destroy(); $self->{'dbcentreon'}->set_inactive_destroy(); - my $centreon_db_centstorage = centreon::common::db(logger => $self->{'logger'}, + my $centreon_db_centstorage = centreon::common::db->new(logger => $self->{'logger'}, db => $self->{'dbcentstorage'}->db(), host => $self->{'dbcentstorage'}->host(), user => $self->{'dbcentstorage'}->user(), From 19ee73f2d4622d994d8b523fa401a7b36bd87aae Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 16 Apr 2013 15:59:37 +0200 Subject: [PATCH 059/458] Add maccro for special command --- centreon/lib/perl/centreon/script/centreontrapd.pm | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 65297c31a4c..7d5d34426b7 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -46,8 +46,8 @@ sub new { cache_unknown_traps_enable => 1, cache_unknown_traps_retention => 600, cache_unknown_traps_file => "/tmp/centreontrapd.cache", + # 0 = central, 1 = poller mode => 0, - cmdFile => "/var/lib/centreon/centcore.cmd", cmd_timeout => 10, centreon_user => "centreon", # 0 => skip if MySQL error | 1 => dont skip (block) if MySQL error (and keep order) @@ -356,11 +356,11 @@ sub forceCheck { if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { $str =~ s/"/\\"/g; - $submit = "/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile}; + $submit = "/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{cmdFile}; } else { $str =~ s/'/'\\''/g; $str =~ s/"/\\"/g; - $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile} . "' 2>&1"; + $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; } my $stdout = `$submit`; @@ -384,11 +384,11 @@ sub submitResult { my $submit; if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { $str =~ s/"/\\"/g; - $submit = "/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile}; + $submit = "/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{cmdFile}; } else { $str =~ s/'/'\\''/g; $str =~ s/"/\\"/g; - $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{centreontrapd_config}->{cmdFile} . "' 2>&1"; + $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; } my $stdout = `$submit`; @@ -523,6 +523,8 @@ sub executeCommand { $traps_execution_command =~ s/\@OUTPUT\@/$traps_output/g; $traps_execution_command =~ s/\@STATUS\@/$status/g; $traps_execution_command =~ s/\@TIME\@/$datetime/g; + $traps_execution_command =~ s/\@POLLERID\@/$self->{current_server_id}/g; + $traps_execution_command =~ s/\@CMDFILE\@/$self->{cmdFile}/g; ########################## # SEND COMMAND @@ -626,7 +628,7 @@ sub run { logger => $self->{logger}); if ($self->{centreontrapd_config}->{mode} == 0) { - $self->{cmdFile} = $self->{centreon_config}->{cmdFile}; + $self->{cmdFile} = $self->{centreon_config}->{VarLib} . "/centcore.cmd"; } else { # Dirty!!! Need to know the poller my ($status, $sth) = $self->{cdb}->query("SELECT `command_file` FROM `cfg_nagios` WHERE `nagios_activate` = '1' LIMIT 1"); From 1f773c77c95cda9871c2d228c5b7bca67ae20327 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 30 May 2013 17:27:35 +0200 Subject: [PATCH 060/458] Working logdb system for traps --- .../centreon/centstorage/CentstorageAction.pm | 3 +- .../centreon/centstorage/CentstorageLib.pm | 55 --------- .../centstorage/CentstoragePerfdataFile.pm | 5 +- .../centreon/centstorage/CentstoragePool.pm | 4 +- centreon/lib/perl/centreon/common/misc.pm | 55 +++++++++ .../lib/perl/centreon/script/centreontrapd.pm | 85 ++++++++++++- centreon/lib/perl/centreon/trapd/Log.pm | 114 ++++++++++++++++++ 7 files changed, 254 insertions(+), 67 deletions(-) create mode 100644 centreon/lib/perl/centreon/trapd/Log.pm diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm index 04badd6aabf..d39af63c5a1 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm @@ -4,7 +4,6 @@ package centreon::centstorage::CentstorageAction; use strict; use warnings; use centreon::common::misc; -use centreon::centstorage::CentstorageLib; my %handlers = ('TERM' => {}, 'HUP' => {}); sub new { @@ -307,7 +306,7 @@ sub main { if (scalar(@rh_set) > 0) { foreach my $rh (@rh_set) { my $read_done = 0; - while ((my ($status_line, $readline) = centreon::centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + while ((my ($status_line, $readline) = centreon::common::misc::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { class_handle_TERM() if ($status_line == -1); last if ($status_line == 0); my ($method, @fields) = split(/\t/, $readline); diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm b/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm index 18b45d8c208..33dccce234e 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm @@ -137,59 +137,4 @@ sub can_write { return 1; } -sub get_line_file { - my ($fh, $datas, $readed) = @_; - my $line; - my $size = scalar(@$datas); - - return (1, shift(@$datas)) if ($size > 1); - while ((my $eof = sysread($fh, $line, $read_size))) { - my @result = split("\n", $line); - if ($line =~ /\n$/) { - push @result, ""; - } - if ($size == 1) { - $$datas[0] .= shift(@result); - } - push @$datas, @result; - $$readed += $eof; - $size = scalar(@$datas); - if ($size > 1) { - return (1, shift(@$datas)); - } - } - return (1, shift(@$datas)) if ($size > 1); - return -1; -} - -sub get_line_pipe { - my ($fh, $datas, $read_done) = @_; - my $line; - my $size = scalar(@$datas); - - if ($size > 1) { - return (1, shift(@$datas)); - } elsif ($size == 1 && $$read_done == 1) { - return 0; - } - while ((my $eof = sysread($fh, $line, 10000))) { - $$read_done = 1; - my @result = split("\n", $line); - if ($line =~ /\n$/) { - push @result, ""; - } - if ($size == 1) { - $$datas[0] .= shift(@result); - } - push @$datas, @result; - $size = scalar(@$datas); - if ($size > 1) { - return (1, shift(@$datas)); - } else { - return 0; - } - } - return -1; -} - 1; diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm index c74ebc08d53..cfd8709632f 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm @@ -4,8 +4,7 @@ use warnings; use File::Copy; package centreon::centstorage::CentstoragePerfdataFile; -use centreon::centstorage::CentstorageLib; -my $end_size_buffer = 1*1024*1024*10; # 10Mo +use centreon::common::misc; sub new { my $class = shift; @@ -60,7 +59,7 @@ sub compute { } my $fh = $self->{"filehandler"}; - while ((my ($status, $readline) = centreon::centstorage::CentstorageLib::get_line_file($fh, \@{$self->{"buffer"}}, \$self->{"readed"}))) { + while ((my ($status, $readline) = centreon::common::misc::get_line_file($fh, \@{$self->{"buffer"}}, \$self->{"readed"}))) { last if ($status == -1); $readline =~ /([0-9]+?)\t+?([^\t]+?)\t+?([^\t]+?)\t/; if (defined($1) && defined($2) && defined($3)) { diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index a5964a39528..f7eeb084d3e 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -161,7 +161,7 @@ sub handle_TERM { if (scalar(@rh_set) > 0) { foreach my $rh (@rh_set) { my $read_done = 0; - while ((my ($status_line, $readline) = centreon::centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + while ((my ($status_line, $readline) = centreon::common::misc::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { last if ($status_line <= 0); if ($readline =~ /^UPDATE/) { $readline =~ s/^UPDATE\t//; @@ -1119,7 +1119,7 @@ sub main { } foreach my $rh (@rh_set) { my $read_done = 0; - while ((my ($status_line, $readline) = centreon::centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + while ((my ($status_line, $readline) = centreon::common::misc::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { class_handle_TERM() if ($status_line == -1); last if ($status_line == 0); my ($method, @fields) = split(/\t/, $readline); diff --git a/centreon/lib/perl/centreon/common/misc.pm b/centreon/lib/perl/centreon/common/misc.pm index 7591a5bdda8..1d789a8b4c4 100644 --- a/centreon/lib/perl/centreon/common/misc.pm +++ b/centreon/lib/perl/centreon/common/misc.pm @@ -69,4 +69,59 @@ sub check_debug { return 0; } +sub get_line_file { + my ($fh, $datas, $readed) = @_; + my $line; + my $size = scalar(@$datas); + + return (1, shift(@$datas)) if ($size > 1); + while ((my $eof = sysread($fh, $line, $read_size))) { + my @result = split("\n", $line); + if ($line =~ /\n$/) { + push @result, ""; + } + if ($size == 1) { + $$datas[0] .= shift(@result); + } + push @$datas, @result; + $$readed += $eof; + $size = scalar(@$datas); + if ($size > 1) { + return (1, shift(@$datas)); + } + } + return (1, shift(@$datas)) if ($size > 1); + return -1; +} + +sub get_line_pipe { + my ($fh, $datas, $read_done) = @_; + my $line; + my $size = scalar(@$datas); + + if ($size > 1) { + return (1, shift(@$datas)); + } elsif ($size == 1 && $$read_done == 1) { + return 0; + } + while ((my $eof = sysread($fh, $line, 10000))) { + $$read_done = 1; + my @result = split("\n", $line); + if ($line =~ /\n$/) { + push @result, ""; + } + if ($size == 1) { + $$datas[0] .= shift(@result); + } + push @$datas, @result; + $size = scalar(@$datas); + if ($size > 1) { + return (1, shift(@$datas)); + } else { + return 0; + } + } + return -1; +} + 1; diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 7d5d34426b7..6235154e260 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -7,6 +7,7 @@ use POSIX; use centreon::script; use centreon::common::db; use centreon::trapd::lib; +use centreon::trapd::Log; use base qw(centreon::script); use vars qw(%centreontrapd_config); @@ -51,7 +52,9 @@ sub new { cmd_timeout => 10, centreon_user => "centreon", # 0 => skip if MySQL error | 1 => dont skip (block) if MySQL error (and keep order) - policy_trap => 1 + policy_trap => 1, + # Log DB + log_trap_db => 0 ); $self->{htmlentities} = 0; @@ -97,6 +100,10 @@ sub new { $self->{cmdFile} = undef; + # Pipe for log DB + %{$self->{logdb_pipes}} = (running => 0); + $self->{pid_logdb_child} = undef; + # redefine to avoid out when we try modules $SIG{__DIE__} = undef; return $self; @@ -184,22 +191,37 @@ sub handle_DIE { $self->{logger}->writeLogInfo($msg); + ### + # Send -TERM signal + ### + if (defined($self->{logdb_pipes}{'running'}) && $self->{logdb_pipes}{'running'} == 1) { + $self->{logger}->writeLogInfo("Send -TERM signal to logdb process.."); + kill('TERM', $self->{pid_logdb_child}); + } + # We're waiting n seconds for (my $i = 0; $i < $self->{centreontrapd_config}->{timeout_end}; $i++) { - $self->manage_pool(); - if (keys %{$self->{running_processes}} == 0) { + $self->manage_pool(0); + if (keys %{$self->{running_processes}} == 0 && $self->{logdb_pipes}{'running'} == 0) { $self->{logger}->writeLogInfo("Main process exit."); exit(0); } sleep 1; } - $self->{logger}->writeLogInfo("Dont handle gently. Send KILl Signals to childs"); + $self->{logger}->writeLogInfo("Dont handle gently. Send KILL Signals to childs"); + # Last check before + $self->manage_pool(0); + # We are killing foreach (keys %{$self->{running_processes}}) { kill('KILL', $_); $self->{logger}->writeLogInfo("Send -KILL signal to child process '$_'.."); } + if ($self->{logdb_pipes}{'running'} == 1) { + kill('KILL', $self->{pid_logdb_child}); + $self->{logger}->writeLogInfo("Send -KILL signal to logdb process.."); + } exit(0); } @@ -226,14 +248,63 @@ sub reload_config { } } +sub create_logdb_child { + my $self = shift; + my ($reader_pipe, $writer_pipe); + + pipe($reader_pipe, $writer_pipe); + $writer_pipe->autoflush(1); + + $self->{logdb_pipes}{'reader'} = \*$reader_pipe; + $self->{logdb_pipes}{'writer'} = \*$writer_pipe; + + $self->{logger}->writeLogInfo("Create delete child"); + my $current_pid = fork(); + if (!$current_pid) { + # Unhandle die in child + $SIG{CHLD} = undef; + $SIG{__DIE__} = undef; + $self->{cdb}->set_inactive_destroy(); + + close $self->{logdb_pipes}{'writer'}; + my $centreon_db_centstorage = centreon::common::db->new(db => $self->{centreon_config}->{centstorage_db}, + host => $self->{centreon_config}->{db_host}, + port => $self->{centreon_config}->{db_port}, + user => $self->{centreon_config}->{db_user}, + password => $self->{centreon_config}->{db_passwd}, + force => 1, + logger => $self->{logger}); + $centreon_db_centstorage->connect(); + + my $centreontrapd_log = centreon::trapd::Log->new($self->{logger}); + $centreontrapd_log->main($centreon_db_centstorage, + $self->{logdb_pipes}{'reader'}, $self->{config_file}); + exit(0); + } + $self->{pid_logdb_child} = $current_pid; + close $self->{logdb_pipes}{'reader'}; + close $self->{logdb_pipes}{'writer'}; + $self->{logdb_pipes}{'running'} = 1; +} + sub manage_pool { my $self = shift; + my ($create_pool) = @_; foreach my $child_pid (keys %{$self->{return_child}}) { if (defined($self->{running_processes}->{$child_pid})) { delete $self->{running_processes}->{$child_pid}; delete $self->{return_child}->{$child_pid}; } + + if (defined($self->{pid_logdb_child}) && $child_pid == $self->{pid_logdb_child}) { + $self->{logger}->writeLogInfo("Logdb child is dead"); + $self->{logdb_pipes}{'running'} = 0; + if ($self->{centreontrapd_config}->{log_trap_db} == 1 && defined($create_pool) && $create_pool == 1) { + $self->create_logdb_child(); + } + delete $self->{return_child}{$child_pid}; + } } } @@ -638,6 +709,10 @@ sub run { $self->{whoami} = getpwuid($<); if ($self->{centreontrapd_config}->{daemon} == 1) { + if ($self->{centreontrapd_config}->{log_trap_db} == 1) { + $self->create_logdb_child(); + } + while (1) { centreon::trapd::lib::purge_duplicate_trap(config => $self->{centreontrapd_config}, duplicate_traps => \%{$self->{duplicate_traps}}); @@ -728,7 +803,7 @@ sub run { $self->{logger}->writeLogDebug("Sleeping for " . $self->{centreontrapd_config}->{sleep} . " seconds"); sleep $self->{centreontrapd_config}->{sleep}; - $self->manage_pool(); + $self->manage_pool(1); } } else { my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, diff --git a/centreon/lib/perl/centreon/trapd/Log.pm b/centreon/lib/perl/centreon/trapd/Log.pm new file mode 100644 index 00000000000..fe4b322cee1 --- /dev/null +++ b/centreon/lib/perl/centreon/trapd/Log.pm @@ -0,0 +1,114 @@ + +package centreon::trapd::Log; + +use strict; +use warnings; +use centreon::common::misc; +my %handlers = ('TERM' => {}, 'HUP' => {}); + +sub new { + my $class = shift; + my $self = {}; + + # reload flag + $self->{reload} = 1; + $self->{config_file} = undef; + + bless $self, $class; + $self->set_signal_handlers; + return $self; +} + +sub set_signal_handlers { + my $self = shift; + + $SIG{TERM} = \&class_handle_TERM; + $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; + $SIG{HUP} = \&class_handle_HUP; + $handlers{HUP}->{$self} = sub { $self->handle_HUP() }; +} + +sub handle_HUP { + my $self = shift; + $self->{reload} = 0; +} + +sub handle_TERM { + my $self = shift; + $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); + + $self->{'dbcentstorage'}->disconnect() if (defined($self->{'dbcentstorage'})); +} + +sub class_handle_TERM { + foreach (keys %{$handlers{'TERM'}}) { + &{$handlers{'TERM'}->{$_}}(); + } + exit(0); +} + +sub class_handle_HUP { + foreach (keys %{$handlers{HUP}}) { + &{$handlers{HUP}->{$_}}(); + } +} + +sub reload { + my $self = shift; + + $self->{logger}->writeLogInfo("Reload in progress for logdb process..."); + # reopen file + if ($self->{logger}->is_file_mode()) { + $self->{logger}->file_mode($self->{logger}->{file_name}); + } + $self->{logger}->redirect_output(); + + my ($status, $status_cdb, $status_csdb) = centreon::common::misc::reload_db_config($self->{logger}, $self->{config_file}, + $self->{dbcentreon}, $self->{dbcentstorage}); + + if ($status_csdb == 1) { + $self->{dbcentstorage}->disconnect(); + $self->{dbcentstorage}->connect(); + } + centreon::common::misc::check_debug($self->{logger}, "debug_centstorage", $self->{dbcentreon}, "centstorage delete process"); + + $self->{reload} = 1; +} + +sub main { + my $self = shift; + my ($dbcentstorage, $pipe_read, $config_file) = @_; + my $status; + + $self->{dbcentstorage} = $dbcentstorage; + $self->{config_file} = $config_file; + + # We have to manage if you don't need infos + $self->{'dbcentstorage'}->force(0); + + my $read_select = new IO::Select(); + $read_select->add($pipe_read); + while (1) { + my @rh_set = $read_select->can_read(5); + if (scalar(@rh_set) > 0) { + foreach my $rh (@rh_set) { + my $read_done = 0; + while ((my ($status_line, $readline) = centreon::common::misc::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + class_handle_TERM() if ($status_line == -1); + last if ($status_line == 0); + $self->{logger}->writeLogInfo("=== test $readline"); + + + } + } + } else { + # Here we have to check if we do transaction + } + + if ($self->{reload} == 0) { + $self->reload(); + } + } +} + +1; From b18464b348e71f25a17046d2fc6d1db6bf3a31ec Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 31 May 2013 11:26:48 +0200 Subject: [PATCH 061/458] Continue working on logdb --- .../lib/perl/centreon/script/centreontrapd.pm | 27 ++++++++++++- centreon/lib/perl/centreon/trapd/Log.pm | 7 +++- centreon/lib/perl/centreon/trapd/lib.pm | 38 ++++++++++++++++++- 3 files changed, 67 insertions(+), 5 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 6235154e260..99ab7ea8d2e 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -92,6 +92,9 @@ sub new { $self->{current_trap_id} = undef; $self->{current_ip} = undef; $self->{current_oid} = undef; + # From centreon DB + $self->{current_trap_name} = undef; + $self->{current_vendor_name} = undef; # For policy_trap = 1 (temp). To avoid doing the same thing twice # ID oid ===> Host ID ===> Service ID @@ -103,6 +106,8 @@ sub new { # Pipe for log DB %{$self->{logdb_pipes}} = (running => 0); $self->{pid_logdb_child} = undef; + # For protocol + $self->{id_logdb} = 0; # redefine to avoid out when we try modules $SIG{__DIE__} = undef; @@ -283,7 +288,6 @@ sub create_logdb_child { } $self->{pid_logdb_child} = $current_pid; close $self->{logdb_pipes}{'reader'}; - close $self->{logdb_pipes}{'writer'}; $self->{logdb_pipes}{'running'} = 1; } @@ -344,11 +348,30 @@ sub do_exec { $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command_enable} == 1) { $self->executeCommand($traps_output, $status); } + + if ($self->{centreontrapd_config}->{log_trap_db} == 1) { + centreon::trapd::lib::send_logdb(pipe => $self->{logdb_pipes}{'writer'}, + id => $self->{id_logdb}, + cdb => $self->{cdb}, + trap_time => $self->{trap_date_time_epoch}, + host_name => ${$self->{var}}[0], + ip_address => $self->{current_ip}, + agent_host_name => $self->{agent_dns_name}, + agent_ip_address => ${$self->{var}}[4], + trap_oid => $self->{current_oid}, + trap_name => $self->{current_trap_name}, + vendor => $self->{current_vendor_name}, + severity => $status, + output_message => $traps_output, + arguments => \@{$self->{entvar}}, + arguments_name => \@{$self->{entvarname}}); + } } sub manage_exec { my $self = shift; + $self->{id_logdb}++; if ($self->{centreontrapd_config}->{daemon} == 0) { eval { local $SIG{ALRM} = sub { die "TIMEOUT"; }; @@ -633,6 +656,8 @@ sub getTrapsInfos { return 0 if ($fstatus == -1); foreach my $trap_id (keys %{$self->{ref_oids}}) { $self->{current_trap_id} = $trap_id; + $self->{current_trap_name} = $self->{ref_oids}->{$trap_id}->{traps_name}; + $self->{current_vendor_name} = $self->{ref_oids}->{$trap_id}->{name}; ($fstatus, $self->{ref_hosts}) = centreon::trapd::lib::get_hosts(logger => $self->{logger}, cdb => $self->{cdb}, trap_info => $self->{ref_oids}->{$trap_id}, diff --git a/centreon/lib/perl/centreon/trapd/Log.pm b/centreon/lib/perl/centreon/trapd/Log.pm index fe4b322cee1..a2860c06eb0 100644 --- a/centreon/lib/perl/centreon/trapd/Log.pm +++ b/centreon/lib/perl/centreon/trapd/Log.pm @@ -4,15 +4,20 @@ package centreon::trapd::Log; use strict; use warnings; use centreon::common::misc; +use IO::Select; my %handlers = ('TERM' => {}, 'HUP' => {}); sub new { my $class = shift; my $self = {}; + $self->{logger} = shift; + # reload flag $self->{reload} = 1; $self->{config_file} = undef; + + $self->{"save_read"} = []; bless $self, $class; $self->set_signal_handlers; @@ -97,8 +102,6 @@ sub main { class_handle_TERM() if ($status_line == -1); last if ($status_line == 0); $self->{logger}->writeLogInfo("=== test $readline"); - - } } } else { diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index da8b556d07d..578c690df59 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -95,9 +95,10 @@ sub get_oids { my ($cdb, $oid) = @_; my $ref_result; - my ($dstatus, $sth) = $cdb->query("SELECT traps_execution_command, traps_reschedule_svc_enable, traps_id, traps_args, + my ($dstatus, $sth) = $cdb->query("SELECT name, traps_execution_command, traps_reschedule_svc_enable, traps_id, traps_args, traps_oid, traps_name, traps_advanced_treatment, traps_execution_command_enable, traps_submit_result_enable, traps_status, - traps_timeout, traps_exec_interval, traps_exec_interval_type FROM traps WHERE traps_oid = " . $cdb->quote($oid)); + traps_timeout, traps_exec_interval, traps_exec_interval_type + FROM traps LEFT JOIN traps_vendor ON (traps_vendor.id = traps.manufacturer_id) WHERE traps_oid = " . $cdb->quote($oid)); return -1 if ($dstatus == -1); $ref_result = $sth->fetchall_hashref('traps_id'); @@ -239,6 +240,39 @@ sub get_macros_host { return (0, \%macros); } +############## +# Protocol with logdb +############## + +sub send_logdb { + my %args = @_; + my $pipe = $args{pipe}; + my $num_args = $#{$args{entvar}}; + + # Need atomic write (Limit to 4096 with Linux) + $args{output_message} =~ s/\n/\\n/g; + print $pipe $args{id} . ":0:$num_args:" . + $args{trap_time} . "," . + $self->{cdb}->quote($args{host_name}) . "," . + $self->{cdb}->quote($args{ip_address}) . "," . + $self->{cdb}->quote($args{agent_host_name}) . "," . + $self->{cdb}->quote($args{agent_ip_address}) . "," . + $self->{cdb}->quote($args{trap_oid}) . "," . + $self->{cdb}->quote($args{trap_name}) . "," . + $self->{cdb}->quote($args{vendor}) . "," . + $self->{cdb}->quote($args{severity}) . "," . + $self->{cdb}->quote($args{output_message}) . "\n"; + for (my $i=0; $i <= $#{$args{entvar}}; $i++) { + my $value = ${$args{entvar}}[$i]; + $value =~ s/\n/\\n/g; + print $pipe $args{id} . ":1:$i:" . + $i . "," . + $self->{cdb}->quote(${$args{entvarname}}[$i]) . "," . + $self->{cdb}->quote($value) . "," . + $args{trap_time} . "\n"; + } +} + ############## # CACHE MANAGEMENT ############## From 23ed78eaed76cac480e060d1a05985e4d08af963 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 31 May 2013 12:04:14 +0200 Subject: [PATCH 062/458] Fix centreontrapd --- .../lib/perl/centreon/script/centreontrapd.pm | 35 ++++++++++++++----- centreon/lib/perl/centreon/trapd/lib.pm | 25 ++++++------- 2 files changed, 40 insertions(+), 20 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 99ab7ea8d2e..56950c5814a 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -325,7 +325,7 @@ sub do_exec { # Advanced matching rules if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment}) && $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment} == 1) { - $status = $self->checkMatchingRules($traps_output); + $status = $self->checkMatchingRules($traps_output, $status); } ##################################################################### @@ -354,6 +354,7 @@ sub do_exec { id => $self->{id_logdb}, cdb => $self->{cdb}, trap_time => $self->{trap_date_time_epoch}, + timeout => 0, host_name => ${$self->{var}}[0], ip_address => $self->{current_ip}, agent_host_name => $self->{agent_dns_name}, @@ -363,8 +364,8 @@ sub do_exec { vendor => $self->{current_vendor_name}, severity => $status, output_message => $traps_output, - arguments => \@{$self->{entvar}}, - arguments_name => \@{$self->{entvarname}}); + entvar => \@{$self->{entvar}}, + entvarname => \@{$self->{entvarname}}); } } @@ -425,6 +426,24 @@ sub manage_exec { alarm(0); }; if ($@) { + if ($self->{centreontrapd_config}->{log_trap_db} == 1) { + centreon::trapd::lib::send_logdb(pipe => $self->{logdb_pipes}{'writer'}, + id => $self->{id_logdb}, + cdb => $self->{cdb}, + trap_time => $self->{trap_date_time_epoch}, + timeout => 1, + host_name => ${$self->{var}}[0], + ip_address => $self->{current_ip}, + agent_host_name => $self->{agent_dns_name}, + agent_ip_address => ${$self->{var}}[4], + trap_oid => $self->{current_oid}, + trap_name => $self->{current_trap_name}, + vendor => $self->{current_vendor_name}, + severity => $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_status}, + output_message => $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_args}, + entvar => \@{$self->{entvar}}, + entvarname => \@{$self->{entvarname}}); + } $self->{logger}->writeLogError("ERROR: Exec timeout"); exit(0); } @@ -571,7 +590,7 @@ sub checkMatchingRules { } $tmoString =~ s/\@HOSTNAME\@/$self->{current_hostname}/g; $tmoString =~ s/\@HOSTADDRESS\@/$self->{current_ip}/g; - $tmoString =~ s/\@HOSTADDRESS2\@/$self->{agent_dns}/g; + $tmoString =~ s/\@HOSTADDRESS2\@/$self->{agent_dns_name}/g; $tmoString =~ s/\@SERVICEDESC\@/$self->{current_service_desc}/g; $tmoString =~ s/\@TRAPOUTPUT\@/$traps_output/g; $tmoString =~ s/\@OUTPUT\@/$traps_output/g; @@ -611,7 +630,7 @@ sub executeCommand { } $traps_execution_command =~ s/\@HOSTNAME\@/$self->{current_hostname}/g; $traps_execution_command =~ s/\@HOSTADDRESS\@/$self->{current_ip}/g; - $traps_execution_command =~ s/\@HOSTADDRESS2\@/$self->{agent_dns}/g; + $traps_execution_command =~ s/\@HOSTADDRESS2\@/$self->{agent_dns_name}/g; $traps_execution_command =~ s/\@SERVICEDESC\@/$self->{current_service_desc}/g; $traps_execution_command =~ s/\@TRAPOUTPUT\@/$traps_output/g; $traps_execution_command =~ s/\@OUTPUT\@/$traps_output/g; @@ -661,7 +680,7 @@ sub getTrapsInfos { ($fstatus, $self->{ref_hosts}) = centreon::trapd::lib::get_hosts(logger => $self->{logger}, cdb => $self->{cdb}, trap_info => $self->{ref_oids}->{$trap_id}, - agent_dns_name => $self->{agent_dns}, + agent_dns_name => $self->{agent_dns_name}, ip_address => $self->{current_ip}, entvar => \@{$self->{entvar}}, entvarname => \@{$self->{entvarname}}); @@ -763,7 +782,7 @@ sub run { my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, config => $self->{centreontrapd_config}, handle => \*FILE, - agent_dns => \$self->{agent_dns}, + agent_dns_name => \$self->{agent_dns_name}, trap_date => \$self->{trap_date}, trap_time => \$self->{trap_time}, trap_date_time => \$self->{trap_date_time}, @@ -834,7 +853,7 @@ sub run { my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, config => $self->{centreontrapd_config}, handle => \*STDIN, - agent_dns => \$self->{agent_dns}, + agent_dns_name => \$self->{agent_dns_name}, trap_date => \$self->{trap_date}, trap_time => \$self->{trap_time}, trap_date_time => \$self->{trap_date_time}, diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 578c690df59..c82b0128094 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -247,28 +247,29 @@ sub get_macros_host { sub send_logdb { my %args = @_; my $pipe = $args{pipe}; - my $num_args = $#{$args{entvar}}; + my $num_args = $#{$args{entvar}} + 1; # Need atomic write (Limit to 4096 with Linux) $args{output_message} =~ s/\n/\\n/g; print $pipe $args{id} . ":0:$num_args:" . $args{trap_time} . "," . - $self->{cdb}->quote($args{host_name}) . "," . - $self->{cdb}->quote($args{ip_address}) . "," . - $self->{cdb}->quote($args{agent_host_name}) . "," . - $self->{cdb}->quote($args{agent_ip_address}) . "," . - $self->{cdb}->quote($args{trap_oid}) . "," . - $self->{cdb}->quote($args{trap_name}) . "," . - $self->{cdb}->quote($args{vendor}) . "," . - $self->{cdb}->quote($args{severity}) . "," . - $self->{cdb}->quote($args{output_message}) . "\n"; + $args{cdb}->quote($args{timeout}) . "," . + $args{cdb}->quote($args{host_name}) . "," . + $args{cdb}->quote($args{ip_address}) . "," . + $args{cdb}->quote($args{agent_host_name}) . "," . + $args{cdb}->quote($args{agent_ip_address}) . "," . + $args{cdb}->quote($args{trap_oid}) . "," . + $args{cdb}->quote($args{trap_name}) . "," . + $args{cdb}->quote($args{vendor}) . "," . + $args{cdb}->quote($args{severity}) . "," . + $args{cdb}->quote($args{output_message}) . "\n"; for (my $i=0; $i <= $#{$args{entvar}}; $i++) { my $value = ${$args{entvar}}[$i]; $value =~ s/\n/\\n/g; print $pipe $args{id} . ":1:$i:" . $i . "," . - $self->{cdb}->quote(${$args{entvarname}}[$i]) . "," . - $self->{cdb}->quote($value) . "," . + $args{cdb}->quote(${$args{entvarname}}[$i]) . "," . + $args{cdb}->quote($value) . "," . $args{trap_time} . "\n"; } } From 0ead619e476990b30ee731ea2b5707b2efedbff8 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 31 May 2013 15:08:44 +0200 Subject: [PATCH 063/458] Continue logdb system --- .../lib/perl/centreon/script/centreontrapd.pm | 49 +++++++++--- centreon/lib/perl/centreon/trapd/Log.pm | 78 +++++++++++++++++-- centreon/lib/perl/centreon/trapd/lib.pm | 2 +- 3 files changed, 109 insertions(+), 20 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 56950c5814a..e396f1fedad 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -54,7 +54,10 @@ sub new { # 0 => skip if MySQL error | 1 => dont skip (block) if MySQL error (and keep order) policy_trap => 1, # Log DB - log_trap_db => 0 + log_trap_db => 0, + log_transaction_request_max => 500, + log_transaction_timeout => 10, + log_purge_time => 600 ); $self->{htmlentities} = 0; @@ -94,6 +97,7 @@ sub new { $self->{current_oid} = undef; # From centreon DB $self->{current_trap_name} = undef; + $self->{current_trap_log} = undef; $self->{current_vendor_name} = undef; # For policy_trap = 1 (temp). To avoid doing the same thing twice @@ -253,6 +257,33 @@ sub reload_config { } } +sub reload { + my $self = shift; + + $self->{logger}->writeLogInfo("Reload in progress for main process..."); + # reopen file + if ($self->{logger}->is_file_mode()) { + $self->{logger}->file_mode($self->{logger}->{file_name}); + } + $self->{logger}->redirect_output(); + + centreon::common::misc::reload_db_config($self->{logger}, $self->{config_file}, $self->{cdb}); + centreon::common::misc::check_debug($self->{logger}, "debug_centreontrapd", $self->{cdb}, "centreontrapd main process"); + + if ($self->{logdb_pipes}{'running'} == 1) { + kill('HUP', $self->{pid_logdb_child}); + $self->{logger}->writeLogInfo("Send -HUP signal to logdb process.."); + } + + $self->reload_config($self->{opt_extra}); + ($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}) = + centreon::trapd::lib::manage_params_conf($self->{centreontrapd_config}->{date_format}, + $self->{centreontrapd_config}->{time_format}); + centreon::trapd::lib::init_modules(); + centreon::trapd::lib::get_cache_oids(); + $self->{timetoreload} = 0; +} + sub create_logdb_child { my $self = shift; my ($reader_pipe, $writer_pipe); @@ -283,7 +314,7 @@ sub create_logdb_child { my $centreontrapd_log = centreon::trapd::Log->new($self->{logger}); $centreontrapd_log->main($centreon_db_centstorage, - $self->{logdb_pipes}{'reader'}, $self->{config_file}); + $self->{logdb_pipes}{'reader'}, $self->{config_file}, $self->{centreontrapd_config}); exit(0); } $self->{pid_logdb_child} = $current_pid; @@ -349,7 +380,7 @@ sub do_exec { $self->executeCommand($traps_output, $status); } - if ($self->{centreontrapd_config}->{log_trap_db} == 1) { + if ($self->{centreontrapd_config}->{log_trap_db} == 1 && $self->{current_trap_log} == 1) { centreon::trapd::lib::send_logdb(pipe => $self->{logdb_pipes}{'writer'}, id => $self->{id_logdb}, cdb => $self->{cdb}, @@ -426,7 +457,7 @@ sub manage_exec { alarm(0); }; if ($@) { - if ($self->{centreontrapd_config}->{log_trap_db} == 1) { + if ($self->{centreontrapd_config}->{log_trap_db} == 1 && $self->{current_trap_log} == 1) { centreon::trapd::lib::send_logdb(pipe => $self->{logdb_pipes}{'writer'}, id => $self->{id_logdb}, cdb => $self->{cdb}, @@ -675,6 +706,7 @@ sub getTrapsInfos { return 0 if ($fstatus == -1); foreach my $trap_id (keys %{$self->{ref_oids}}) { $self->{current_trap_id} = $trap_id; + $self->{current_trap_log} = $self->{ref_oids}->{$trap_id}->{traps_log}; $self->{current_trap_name} = $self->{ref_oids}->{$trap_id}->{traps_name}; $self->{current_vendor_name} = $self->{ref_oids}->{$trap_id}->{name}; ($fstatus, $self->{ref_hosts}) = centreon::trapd::lib::get_hosts(logger => $self->{logger}, @@ -833,14 +865,7 @@ sub run { } if ($self->{timetoreload} == 1) { - $self->{logger}->writeLogDebug("Reloading configuration file"); - $self->reload_config($self->{opt_extra}); - ($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}) = - centreon::trapd::lib::manage_params_conf($self->{centreontrapd_config}->{date_format}, - $self->{centreontrapd_config}->{time_format}); - centreon::trapd::lib::init_modules(); - centreon::trapd::lib::get_cache_oids(); - $self->{timetoreload} = 0; + $self->reload(); } } diff --git a/centreon/lib/perl/centreon/trapd/Log.pm b/centreon/lib/perl/centreon/trapd/Log.pm index a2860c06eb0..f4ad6afeaee 100644 --- a/centreon/lib/perl/centreon/trapd/Log.pm +++ b/centreon/lib/perl/centreon/trapd/Log.pm @@ -16,6 +16,10 @@ sub new { # reload flag $self->{reload} = 1; $self->{config_file} = undef; + $self->{centreontrapd_config} = undef; + $self->{construct_log} = {}; + $self->{request_log} = {}; + $self->{last_transaction} = time; $self->{"save_read"} = []; @@ -43,6 +47,7 @@ sub handle_TERM { $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); $self->{'dbcentstorage'}->disconnect() if (defined($self->{'dbcentstorage'})); + $self->{'cdb'}->disconnect() if (defined($self->{'cdb'})); } sub class_handle_TERM { @@ -69,24 +74,63 @@ sub reload { $self->{logger}->redirect_output(); my ($status, $status_cdb, $status_csdb) = centreon::common::misc::reload_db_config($self->{logger}, $self->{config_file}, - $self->{dbcentreon}, $self->{dbcentstorage}); + $self->{dbcentstorage}, $self->{cdb}); if ($status_csdb == 1) { $self->{dbcentstorage}->disconnect(); $self->{dbcentstorage}->connect(); } - centreon::common::misc::check_debug($self->{logger}, "debug_centstorage", $self->{dbcentreon}, "centstorage delete process"); + if ($status_cdb == 1) { + $self->{cdb}->disconnect(); + $self->{cdb}->connect(); + } + centreon::common::misc::check_debug($self->{logger}, "debug_centreontrapd", $self->{cdb}, "centreontrapd logdb process"); $self->{reload} = 1; } +sub compute_request { + my $self = shift; + + if (scalar(keys(%{$self->{request_log}})) > $self->{centreontrapd_config}->{log_transaction_request_max} || + (time() - $self->{last_transaction}) > $self->{centreontrapd_config}->{log_transaction_timeout}) { + $self->{dbcentstorage}->transaction_mode(1); + eval { + foreach my $id (keys %{$self->{request_log}}) { + $self->{dbcentstorage}->query("INSERT INTO log_traps VALUES (" . $self->{request_log}->{$id}->{value} . ")"); + $self->{dbcentstorage}->query("SET @last_id_trap = LAST_INSERT_ID();"); + if (defined($self->{request_log}->{$id}->{args})) { + foreach (@{$self->{request_log}->{$id}->{args}}) { + $self->{dbcentstorage}->query("INSERT INTO log_traps_args VALUES (@last_id_trap, " . $_ ")"); + } + } + } + $self->{dbcentstorage}->commit; + }; + if ($@) { + $self->{dbcentstorage}->rollback; + } else { + $self->{request_log} = {}; + } + $self->{last_transaction} = time; + } + + # Check time purge + foreach my $id (keys %{$self->{construct_log}}) { + if ((time() - $self->{construct_log}->{$id}->{time}) > $self->{centreontrapd_config}->{log_purge_time}) { + delete $self->{construct_log}->{$id}; + } + } +} + sub main { my $self = shift; - my ($dbcentstorage, $pipe_read, $config_file) = @_; + my ($dbcentstorage, $pipe_read, $config_file, $centreontrapd_config) = @_; my $status; $self->{dbcentstorage} = $dbcentstorage; $self->{config_file} = $config_file; + $self->{centreontrapd_config} = $centreontrapd_config; # We have to manage if you don't need infos $self->{'dbcentstorage'}->force(0); @@ -101,13 +145,33 @@ sub main { while ((my ($status_line, $readline) = centreon::common::misc::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { class_handle_TERM() if ($status_line == -1); last if ($status_line == 0); - $self->{logger}->writeLogInfo("=== test $readline"); + $readline =~ /^(.*?):(.*?):(.*?):(.*)/; + my ($id, $type, $num, $value) = ($1, $2, $3, $4); + $value =~ s/\\n/\n/g; + + if ($type == 0) { + if ($num <= 0) { + $self->{request_log}->{$id} = { value => $value }; + } else { + $self->{construct_log}->{$id} = { time => time(), value => $value, current_args => 0, num_args => $num, args => [] }; + } + } else if ($type == 1) { + if (defined($self->{construct_log}->{$id})) { + if ($self->{construct_log}->{$id}->{current_args} + 1 == $self->{construct_log}->{$id}->{num_args}) { + $self->{request_log}->{$id} = { value => $self->{construct_log}->{$id}->{value}, args => $self->{construct_log}->{$id}->{args} }; + delete $self->{construct_log}->{$id}; + } else { + push @{$self->{construct_log}->{$id}->{args}}, $value; + $self->{construct_log}->{$id}->{current_args}++; + } + } + } } } - } else { - # Here we have to check if we do transaction - } + } + $self->compute_request(); + if ($self->{reload} == 0) { $self->reload(); } diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index c82b0128094..53d48c2b8b7 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -95,7 +95,7 @@ sub get_oids { my ($cdb, $oid) = @_; my $ref_result; - my ($dstatus, $sth) = $cdb->query("SELECT name, traps_execution_command, traps_reschedule_svc_enable, traps_id, traps_args, + my ($dstatus, $sth) = $cdb->query("SELECT name, traps_log, traps_execution_command, traps_reschedule_svc_enable, traps_id, traps_args, traps_oid, traps_name, traps_advanced_treatment, traps_execution_command_enable, traps_submit_result_enable, traps_status, traps_timeout, traps_exec_interval, traps_exec_interval_type FROM traps LEFT JOIN traps_vendor ON (traps_vendor.id = traps.manufacturer_id) WHERE traps_oid = " . $cdb->quote($oid)); From de07056c828367fa15af35bce6d4caa06ab6f966 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 31 May 2013 15:48:36 +0200 Subject: [PATCH 064/458] trap log db finished --- centreon/lib/perl/centreon/trapd/Log.pm | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/centreon/trapd/Log.pm b/centreon/lib/perl/centreon/trapd/Log.pm index f4ad6afeaee..2c8ab5c66dd 100644 --- a/centreon/lib/perl/centreon/trapd/Log.pm +++ b/centreon/lib/perl/centreon/trapd/Log.pm @@ -97,11 +97,11 @@ sub compute_request { $self->{dbcentstorage}->transaction_mode(1); eval { foreach my $id (keys %{$self->{request_log}}) { - $self->{dbcentstorage}->query("INSERT INTO log_traps VALUES (" . $self->{request_log}->{$id}->{value} . ")"); - $self->{dbcentstorage}->query("SET @last_id_trap = LAST_INSERT_ID();"); + $self->{dbcentstorage}->query("INSERT INTO log_traps (`trap_time`, `timeout`, `host_name`, `ip_address`, `agent_host_name`, `agent_ip_address`, `trap_oid`, `trap_name`, `vendor`, `severity`, `output_message`) VALUES (" . $self->{request_log}->{$id}->{value} . ")"); + $self->{dbcentstorage}->query("SET \@last_id_trap = LAST_INSERT_ID();"); if (defined($self->{request_log}->{$id}->{args})) { foreach (@{$self->{request_log}->{$id}->{args}}) { - $self->{dbcentstorage}->query("INSERT INTO log_traps_args VALUES (@last_id_trap, " . $_ ")"); + $self->{dbcentstorage}->query("INSERT INTO log_traps_args (`fk_log_traps`, `arg_number`, `arg_oid`, `arg_value`, `trap_time`) VALUES (\@last_id_trap, " . $_ . ")"); } } } @@ -155,7 +155,7 @@ sub main { } else { $self->{construct_log}->{$id} = { time => time(), value => $value, current_args => 0, num_args => $num, args => [] }; } - } else if ($type == 1) { + } elsif ($type == 1) { if (defined($self->{construct_log}->{$id})) { if ($self->{construct_log}->{$id}->{current_args} + 1 == $self->{construct_log}->{$id}->{num_args}) { $self->{request_log}->{$id} = { value => $self->{construct_log}->{$id}->{value}, args => $self->{construct_log}->{$id}->{args} }; From 29181f80685d9a18505b1185acae466900f6f679 Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Tue, 4 Jun 2013 11:17:47 +0200 Subject: [PATCH 065/458] fixes #4504; set timeout on centcore --- centreon/lib/perl/centreon/script/centcore.pm | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index 0df69cd38e7..28da88a8419 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -213,7 +213,16 @@ sub getBrokerStats($) { $port = checkSSHPort($server_info->{'ssh_port'}); # Copy the stat file into a buffer - my $stdout = `$self->{ssh} -q $server_info->{'ns_ip_address'} -p $port 'cat \"$data->{'config_value'}" > $statPipe'`; + my $stdout; + eval { + local $SIG{ALRM} = sub { die "alarm\n" }; + alarm $timeout; + $stdout = `$ssh -q $server_info->{'ns_ip_address'} -p $port 'cat \"$data->{'config_value'}" > $statPipe'`; + alarm 0; + }; + if ($@) { + writeLogFile("Could not read pipe ".$data->{'config_value'}." on poller ".$server_info->{'ns_ip_address'}."\n"); + } if (defined($stdout) && $stdout) { $self->{logger}->writeLogInfo("Result : $stdout"); } From 808303147fcb1a701075fe73c6e0a4cdd7d9b4fb Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 5 Jun 2013 11:47:52 +0200 Subject: [PATCH 066/458] Fix in perl refactoring --- centreon/lib/perl/centreon/centstorage/CentstorageLib.pm | 2 -- centreon/lib/perl/centreon/common/misc.pm | 2 ++ centreon/lib/perl/centreon/script/centstorage.pm | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm b/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm index 33dccce234e..bf183f10e14 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm @@ -2,8 +2,6 @@ package centreon::centstorage::CentstorageLib; use File::Basename; -my $read_size = 1*1024*1024*10; # 10Mo - sub start_or_not { my ($centreon_db_centreon) = @_; my $status = 1; diff --git a/centreon/lib/perl/centreon/common/misc.pm b/centreon/lib/perl/centreon/common/misc.pm index 1d789a8b4c4..901b3b11c93 100644 --- a/centreon/lib/perl/centreon/common/misc.pm +++ b/centreon/lib/perl/centreon/common/misc.pm @@ -2,6 +2,8 @@ package centreon::common::misc; use vars qw($centreon_config); +my $read_size = 1*1024*1024*10; # 10Mo + sub reload_db_config { my ($logger, $config_file, $cdb, $csdb) = @_; my ($cdb_mod, $csdb_mod) = (0, 0); diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index 5667b5bf422..15169734862 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -461,7 +461,7 @@ sub run { my @rh_set = $self->{read_select}->can_read(10); foreach my $rh (@rh_set) { my $read_done = 0; - while ((my ($status_line, $data_element) = centreon::centstorage::CentstorageLib::get_line_pipe($rh, \@{$self->{fileno_save_read}{fileno($rh)}}, \$read_done))) { + while ((my ($status_line, $data_element) = centreon::common::misc::get_line_pipe($rh, \@{$self->{fileno_save_read}{fileno($rh)}}, \$read_done))) { last if ($status_line <= 0); if ($data_element =~ /^REBUILDBEGIN/) { centreon::centstorage::CentstorageLib::call_pool_rebuild($data_element, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}, \$self->{rebuild_progress}, \$self->{rebuild_pool_choosen}); From 0f8e2bc980e531a10f7e664e884ef49552e0e930 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 5 Jun 2013 17:30:14 +0200 Subject: [PATCH 067/458] Ref #3768 --- .../lib/perl/centreon/script/centreontrapd.pm | 107 ++++++++++++------ centreon/lib/perl/centreon/trapd/lib.pm | 9 +- 2 files changed, 79 insertions(+), 37 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index e396f1fedad..916ba5c53ed 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -91,6 +91,7 @@ sub new { $self->{current_hostname} = undef; $self->{current_server_id} = undef; $self->{current_service_id} = undef; + $self->{current_server_ip_address} = undef; $self->{current_service_desc} = undef; $self->{current_trap_id} = undef; $self->{current_ip} = undef; @@ -100,6 +101,10 @@ sub new { $self->{current_trap_log} = undef; $self->{current_vendor_name} = undef; + # + $self->{traps_global_output} = undef; + $self->{traps_global_status} = undef; + # For policy_trap = 1 (temp). To avoid doing the same thing twice # ID oid ===> Host ID ===> Service ID %{$self->{policy_trap_skip}} = (); @@ -349,21 +354,24 @@ sub manage_pool { sub do_exec { my $self = shift; - my $traps_output = $self->substitute_string($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_args}); - my $status = $self->substitute_string($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_status}); + $self->{traps_global_status} = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_status}; + # PREEXEC commands + $self->execute_preexec(); + + $self->{traps_global_output} = $self->substitute_string($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_args}); ###################################################################### # Advanced matching rules if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment}) && $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment} == 1) { - $status = $self->checkMatchingRules($traps_output, $status); + $status = $self->checkMatchingRules(); } ##################################################################### # Submit value to passive service if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_submit_result_enable}) && $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_submit_result_enable} == 1) { - $self->submitResult($status, $traps_output); + $self->submitResult(); } ###################################################################### @@ -377,7 +385,7 @@ sub do_exec { # Execute special command if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command_enable}) && $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command_enable} == 1) { - $self->executeCommand($traps_output, $status); + $self->executeCommand(); } if ($self->{centreontrapd_config}->{log_trap_db} == 1 && $self->{current_trap_log} == 1) { @@ -393,8 +401,8 @@ sub do_exec { trap_oid => $self->{current_oid}, trap_name => $self->{current_trap_name}, vendor => $self->{current_vendor_name}, - severity => $status, - output_message => $traps_output, + severity => $self->{traps_global_status}, + output_message => $self->{traps_global_output}, entvar => \@{$self->{entvar}}, entvarname => \@{$self->{entvarname}}); } @@ -520,10 +528,9 @@ sub forceCheck { # sub submitResult { my $self = shift; - my ($status, $traps_output) = @_; my $datetime = time(); - my $str = "PROCESS_SERVICE_CHECK_RESULT;$self->{current_hostname};$self->{current_service_desc};$status;$traps_output"; + my $str = "PROCESS_SERVICE_CHECK_RESULT;$self->{current_hostname};$self->{current_service_desc};" . $self->{traps_global_status} . ";" . $self->{traps_global_output}; my $submit; if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { @@ -543,6 +550,30 @@ sub submitResult { } } +sub execute_preexec { + my $self = shift; + + foreach my $trap_id (keys %{$self->{ref_oids}->{ $self->{current_trap_id} }->{traps_preexec}}) { + my $tpe_string = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$trap_id}->{tpe_string}; + $tpe_string = $self->substitute_string($tpe_string); + $tpe_string = $self->subtitute_centreon_var($tpe_string); + + my $output = `$tpe_string`; + if ($? == -1) { + $self->{logger}->writeLogError("EXEC: Execution error: $!"); + } elsif (($? >> 8) != 0) { + $self->{logger}->writeLogInfo("EXEC: Exit command: " . ($? >> 8)); + } + if (defined($output)) { + chomp $output; + push @{$self->{preexec}}, $output; + $self->{logger}->writeLogInfo("EXEC: Output : $output"); + } else { + push @{$self->{preexec}}, ""; + } + } +} + ########################## ## REPLACE # @@ -555,7 +586,7 @@ sub substitute_host_macro { $str =~ s/\Q$macro_name\E/\Q$self->{ref_macro_hosts}->{$macro_name}\E/g; } } - + return $str; } @@ -570,6 +601,12 @@ sub substitute_string { $str =~ s/\$$x(\s|$)/${$self->{entvar}}[$i]/g; } + # Substitute preexec var + for (my $i=0; $i <= $#{$self->{preexec}}; $i++) { + my $x = $i + 1; + $str =~ s/\$p$x(\s|$)/${$self->{preexec}}[$i]/g; + } + # Substitute $* my $sub_str = join($self->{centreontrapd_config}->{separator}, @{$self->{entvar}}); $str =~ s/\$\*/$sub_str/g; @@ -579,12 +616,30 @@ sub substitute_string { return $str; } +sub subtitute_centreon_var { + my $self = shift; + my $str = $_[0]; + + $str =~ s/\@HOSTNAME\@/$self->{current_hostname}/g; + $str =~ s/\@HOSTADDRESS\@/$self->{current_ip}/g; + $str =~ s/\@HOSTADDRESS2\@/$self->{agent_dns_name}/g; + $str =~ s/\@SERVICEDESC\@/$self->{current_service_desc}/g; + $str =~ s/\@TRAPOUTPUT\@/$self->{traps_global_output}/g; + $str =~ s/\@OUTPUT\@/$self->{traps_global_output}/g; + $str =~ s/\@STATUS\@/$self->{traps_global_status}/g; + $str =~ s/\@TIME\@/$self->{trap_date_time_epoch}/g; + $str =~ s/\@POLLERID\@/$self->{current_server_id}/g; + $str =~ s/\@POLLERADDRESS\@/$self->{current_server_ip_address}/g; + $str =~ s/\@CMDFILE\@/$self->{cmdFile}/g; + $str = $self->substitute_host_macro($str); + return $str; +} + ####################################### ## Check Advanced Matching Rules # sub checkMatchingRules { my $self = shift; - my ($traps_output, $status) = @_; # Check matching options foreach my $tmo_id (keys %{$self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}}) { @@ -610,6 +665,7 @@ sub checkMatchingRules { } $tmoString = $self->substitute_string($tmoString); + $tmoString = $self->subtitute_centreon_var($tmoString); ########################## # REPLACE special Chars @@ -619,23 +675,15 @@ sub checkMatchingRules { $tmoString =~ s/\"\;/\"/g; $tmoString =~ s/\'\;\'\;/"/g; } - $tmoString =~ s/\@HOSTNAME\@/$self->{current_hostname}/g; - $tmoString =~ s/\@HOSTADDRESS\@/$self->{current_ip}/g; - $tmoString =~ s/\@HOSTADDRESS2\@/$self->{agent_dns_name}/g; - $tmoString =~ s/\@SERVICEDESC\@/$self->{current_service_desc}/g; - $tmoString =~ s/\@TRAPOUTPUT\@/$traps_output/g; - $tmoString =~ s/\@OUTPUT\@/$traps_output/g; - $tmoString =~ s/\@TIME\@/$self->{trap_date_time_epoch}/g; # Integrate OID Matching if (defined($tmoString) && $tmoString =~ m/$regexp/g) { - $status = $tmoStatus; + $self->{traps_global_status} = $tmoStatus; $self->{logger}->writeLogInfo("Regexp: String:$tmoString => REGEXP:$regexp"); - $self->{logger}->writeLogInfo("Status: $status ($tmoStatus)"); + $self->{logger}->writeLogInfo("Status: $self->{traps_global_status} ($tmoStatus)"); last; } } - return $status; } ################################ @@ -643,12 +691,10 @@ sub checkMatchingRules { # sub executeCommand { my $self = shift; - my ($traps_output, $status) = @_; my $datetime = time(); my $traps_execution_command = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command}; $traps_execution_command = $self->substitute_string($traps_execution_command); - $traps_execution_command = $self->substitute_host_macro($traps_execution_command); ########################## # REPLACE MACROS @@ -659,17 +705,9 @@ sub executeCommand { $traps_execution_command =~ s/\'\;\'\;/"/g; $traps_execution_command =~ s/\'\;/'/g; } - $traps_execution_command =~ s/\@HOSTNAME\@/$self->{current_hostname}/g; - $traps_execution_command =~ s/\@HOSTADDRESS\@/$self->{current_ip}/g; - $traps_execution_command =~ s/\@HOSTADDRESS2\@/$self->{agent_dns_name}/g; - $traps_execution_command =~ s/\@SERVICEDESC\@/$self->{current_service_desc}/g; - $traps_execution_command =~ s/\@TRAPOUTPUT\@/$traps_output/g; - $traps_execution_command =~ s/\@OUTPUT\@/$traps_output/g; - $traps_execution_command =~ s/\@STATUS\@/$status/g; - $traps_execution_command =~ s/\@TIME\@/$datetime/g; - $traps_execution_command =~ s/\@POLLERID\@/$self->{current_server_id}/g; - $traps_execution_command =~ s/\@CMDFILE\@/$self->{cmdFile}/g; - + + $traps_execution_command = $self->subtitute_centreon_var($traps_execution_command); + ########################## # SEND COMMAND if ($traps_execution_command) { @@ -724,6 +762,7 @@ sub getTrapsInfos { } $self->{current_host_id} = $host_id; $self->{current_server_id} = $self->{ref_hosts}->{$host_id}->{nagios_server_id}; + $self->{current_server_ip_address} = $self->{ref_hosts}->{$host_id}->{ns_ip_address}; $self->{current_hostname} = $self->{ref_hosts}->{$host_id}->{host_name}; #### Get Services #### diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 53d48c2b8b7..bd6460ab8ff 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -111,7 +111,9 @@ sub get_oids { } # Get Trap PREEXEC Commands - #($dstatus, $sth) = $cdb->query(""); + ($dstatus, $sth) = $cdb->query("SELECT * FROM traps_preexec WHERE trap_id = " . $_ . " ORDER BY tpe_order ASC"); + return -1 if ($dstatus == -1); + $ref_result->{$_}->{traps_preexec} = $sth->fetchall_hashref("trap_id"); # Get Associated Host # TODO @@ -138,11 +140,12 @@ sub get_hosts { # Get server_id foreach (keys %$ref_result) { - ($dstatus, $sth) = $args{cdb}->query("SELECT nagios_server_id FROM ns_host_relation WHERE - host_host_id = " . $ref_result->{$_}->{host_id} . " LIMIT 1"); + ($dstatus, $sth) = $args{cdb}->query("SELECT ns_host_relation.nagios_server_id, nagios_server.ns_ip_address FROM ns_host_relation, nagios_server WHERE + ns_host_relation.host_host_id = " . $ref_result->{$_}->{host_id} . " AND ns_host_relation.nagios_server_id = nagios_server.id LIMIT 1"); return -1 if ($dstatus == -1); my $data = $sth->fetchrow_hashref(); $ref_result->{$_}->{nagios_server_id} = $data->{nagios_server_id}; + $ref_result->{$_}->{ns_ip_address} = $data->{ns_ip_address}; } return (0, $ref_result); From 9cd61ad09dc198dcfd9671056bc8c04106149b87 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 6 Jun 2013 15:56:41 +0200 Subject: [PATCH 068/458] Add routing system from a custom value (permits to configure traps from PABX or virtualcenter) --- .../lib/perl/centreon/script/centreontrapd.pm | 17 ++++++++++++++++- centreon/lib/perl/centreon/trapd/lib.pm | 15 ++++++++++++--- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 916ba5c53ed..d6f2e83ba7d 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -611,6 +611,20 @@ sub substitute_string { my $sub_str = join($self->{centreontrapd_config}->{separator}, @{$self->{entvar}}); $str =~ s/\$\*/$sub_str/g; + # $A + $str =~ s/\$A(\s|$)/$self->{agent_dns_name}/g; + + # $aA (Trap agent IP Adress) + $str =~ s/\$aA(\s|$)/${$self->{var}}[4]/g; + + # $R, $r (Trap Hostname) + $str =~ s/\$R(\s|$)/${$self->{var}}[0]/g; + $str =~ s/\$r(\s|$)/${$self->{var}}[0]/g; + + # $aR, $ar (IP Adress) + $str =~ s/\$aR(\s|$)/${$self->{var}}[1]/g; + $str =~ s/\$ar(\s|$)/${$self->{var}}[1]/g; + # Clean OID $str =~ s/\@\{[\.0-9]*\}//g; return $str; @@ -753,7 +767,8 @@ sub getTrapsInfos { agent_dns_name => $self->{agent_dns_name}, ip_address => $self->{current_ip}, entvar => \@{$self->{entvar}}, - entvarname => \@{$self->{entvarname}}); + entvarname => \@{$self->{entvarname}}, + centreontrapd => $self); return 0 if ($fstatus == -1); foreach my $host_id (keys %{$self->{ref_hosts}}) { if (!defined($self->{ref_hosts}->{$host_id}->{nagios_server_id})) { diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index bd6460ab8ff..a875070f5fb 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -97,7 +97,8 @@ sub get_oids { my ($dstatus, $sth) = $cdb->query("SELECT name, traps_log, traps_execution_command, traps_reschedule_svc_enable, traps_id, traps_args, traps_oid, traps_name, traps_advanced_treatment, traps_execution_command_enable, traps_submit_result_enable, traps_status, - traps_timeout, traps_exec_interval, traps_exec_interval_type + traps_timeout, traps_exec_interval, traps_exec_interval_type, + traps_routing_mode, traps_routing_value FROM traps LEFT JOIN traps_vendor ON (traps_vendor.id = traps.manufacturer_id) WHERE traps_oid = " . $cdb->quote($oid)); return -1 if ($dstatus == -1); $ref_result = $sth->fetchall_hashref('traps_id'); @@ -133,8 +134,16 @@ sub get_hosts { my ($dstatus, $sth); my $ref_result; - ($dstatus, $sth) = $args{cdb}->query("SELECT host_id, host_name FROM host WHERE - host_address=" . $args{cdb}->quote($args{agent_dns_name}) . " OR host_address=" . $args{cdb}->quote($args{ip_address})); + if ($args{trap_info}->{traps_routing_mode} == 1) { + my $search_str = $args{centreontrapd}->substitute_string($args{trap_info}->{traps_routing_value}); + ($dstatus, $sth) = $args{cdb}->query("SELECT host_id, host_name FROM host WHERE + host_address=" . $args{cdb}->quote($search_str); + } else { + # Default Mode + ($dstatus, $sth) = $args{cdb}->query("SELECT host_id, host_name FROM host WHERE + host_address=" . $args{cdb}->quote($args{agent_dns_name}) . " OR host_address=" . $args{cdb}->quote($args{ip_address})); + } + return -1 if ($dstatus == -1); $ref_result = $sth->fetchall_hashref('host_id'); From dd46fae1b9f5df0a117d1ffcd0d81394a93cd3d7 Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Mon, 10 Jun 2013 09:49:37 +0200 Subject: [PATCH 069/458] fixes logger call --- centreon/lib/perl/centreon/script/centcore.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index 28da88a8419..74689246ce7 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -221,7 +221,7 @@ sub getBrokerStats($) { alarm 0; }; if ($@) { - writeLogFile("Could not read pipe ".$data->{'config_value'}." on poller ".$server_info->{'ns_ip_address'}."\n"); + $self->{logger}->writeLogError("Could not read pipe ".$data->{'config_value'}." on poller ".$server_info->{'ns_ip_address'}."\n"); } if (defined($stdout) && $stdout) { $self->{logger}->writeLogInfo("Result : $stdout"); From 85c599df8fd955a8314381db7bcce5dc8af5a577 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 10 Jun 2013 15:55:50 +0200 Subject: [PATCH 070/458] Ref #3616 --- .../centreon/centstorage/CentstorageAction.pm | 5 - .../centreon/centstorage/CentstoragePool.pm | 191 ++++++++++++++---- .../lib/perl/centreon/script/centstorage.pm | 3 +- 3 files changed, 150 insertions(+), 49 deletions(-) diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm index d39af63c5a1..abad3762718 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm @@ -11,7 +11,6 @@ sub new { my $self = {}; $self->{"logger"} = shift; $self->{"rebuild_progress"} = shift; - $self->{"centreon_23_compatibility"} = shift; $self->{"dbcentreon"} = undef; $self->{"dbcentstorage"} = undef; $self->{"purge_delay"} = 3600; @@ -98,10 +97,6 @@ sub check_deleted { my $self = shift; my $pipe_write = $_[0]; - if (defined($self->{'centreon_23_compatibility'}) && $self->{'centreon_23_compatibility'} == 1) { - return ; - } - if (time() < ($self->{"last_deleted_time"} + $self->{"deleted_delay"})) { return ; } diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index f7eeb084d3e..039b4e5e187 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -58,7 +58,11 @@ sub new { $self->{"metric_value"} = undef; $self->{"metric_unit"} = undef; $self->{"metric_warn"} = undef; + $self->{"warn_low"} = undef; + $self->{"warn_threshold_mode"} = undef; $self->{"metric_crit"} = undef; + $self->{"crit_low"} = undef; + $self->{"crit_threshold_mode"} = undef; $self->{"metric_min"} = undef; $self->{"metric_max"} = undef; @@ -342,29 +346,44 @@ sub create_metric { my ($index_id, $cache_metrics, $metric_name) = @_; # Check if exists already - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT * FROM `metrics` WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($metric_name) . " LIMIT 1"); + my ($status, $stmt) = $self->{dbcentstorage}->query("SELECT * FROM `metrics` WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{dbcentstorage}->quote($metric_name) . " LIMIT 1"); return -1 if ($status == -1); my $data = $stmt->fetchrow_hashref(); # move part for compat with old centstorage name if (!defined($data)) { - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT * FROM `metrics` WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($self->remove_special_char_metric($metric_name)) . " LIMIT 1"); + ($status, $stmt) = $self->{dbcentstorage}->query("SELECT * FROM `metrics` WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{dbcentstorage}->quote($self->remove_special_char_metric($metric_name)) . " LIMIT 1"); return -1 if ($status == -1); $data = $stmt->fetchrow_hashref(); if (defined($data)) { - ($status) = $self->{'dbcentstorage'}->query("UPDATE `metrics` SET `metric_name` = " . $self->{'dbcentstorage'}->quote($metric_name) . " WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{'dbcentstorage'}->quote($self->remove_special_char_metric($metric_name)) . " LIMIT 1"); + ($status) = $self->{dbcentstorage}->query("UPDATE `metrics` SET `metric_name` = " . $self->{dbcentstorage}->quote($metric_name) . " WHERE `index_id` = '" . $index_id . "' AND `metric_name` = " . $self->{dbcentstorage}->quote($self->remove_special_char_metric($metric_name)) . " LIMIT 1"); return -1 if ($status == -1); } else { # Insert - ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `metrics` (`index_id`, `metric_name`, `unit_name`, `warn`, `crit`, `min`, `max`, `data_source_type`) VALUES ('" . $index_id . "', " . $self->{'dbcentstorage'}->quote($metric_name) . ", '" . $self->{"metric_unit"} . "', '" . $self->{"metric_warn"} . "', '" . $self->{"metric_crit"} . "', '" . $self->{"metric_min"} . "', '" . $self->{"metric_max"} . "', '" . $self->{"metric_type"} . "')"); + ($status, $stmt) = $self->{dbcentstorage}->query("INSERT INTO `metrics` (`index_id`, `metric_name`, `unit_name`, `warn`, `warn_low`, `warn_threshold_mode`, `crit`, `crit_low`, `crit_threshold_mode`, `min`, `max`, `data_source_type`) VALUES ('" . $index_id . "', " . $self->{dbcentstorage}->quote($metric_name) . ", '" . $self->{metric_unit} . "', " . + $self->{dbcentstorage}->quote($self->{metric_warn}) . ", " . $self->{dbcentstorage}->quote($self->{warn_low}) . ", " . $self->{dbcentstorage}->quote($self->{warn_threshold_mode}) . ", " . + $self->{dbcentstorage}->quote($self->{metric_crit}) . ", " . $self->{dbcentstorage}->quote($self->{crit_low}) . ", " . $self->{dbcentstorage}->quote($self->{crit_threshold_mode}) . ", " . + $self->{metric_min} . "', '" . $self->{metric_max} . "', '" . $self->{metric_type} . "')"); return -1 if ($status); - my $last_insert_id = $self->{'dbcentstorage'}->last_insert_id(); - $$cache_metrics->{$metric_name} = {'metric_id' => $last_insert_id, 'metric_unit' => $self->{"metric_unit"}, 'metric_warn' => $self->{"metric_warn"}, 'metric_crit' => $self->{"metric_crit"}, 'metric_min' => $self->{"metric_min"}, 'metric_max' => $self->{"metric_max"}, 'data_source_type' => $self->{"metric_type"}}; + my $last_insert_id = $self->{dbcentstorage}->last_insert_id(); + $$cache_metrics->{$metric_name} = {metric_id => $last_insert_id, metric_unit => $self->{metric_unit}, + metric_warn => $self->{metric_warn}, warn_low => $self->{warn_low}, warn_threshold_mode => $self->{warn_threshold_mode}, + metric_crit => $self->{metric_crit}, crit_low => $self->{crit_low}, crit_threshold_mode => $self->{crit_threshold_mode}, + metric_min => $self->{metric_min}, metric_max => $self->{metric_max}, data_source_type => $self->{metric_type}}; return 0; } } # We get - $$cache_metrics->{$metric_name} = {'metric_id' => $data->{'metric_id'}, 'metric_unit' => defined($data->{"unit_name"}) ? $data->{"unit_name"} : "", 'metric_warn' => defined($data->{"warn"}) ? $data->{"warn"} : "", 'metric_crit' => defined($data->{"crit"}) ? $data->{"crit"} : "", 'metric_min' => defined($data->{"min"}) ? $data->{"min"} : "", 'metric_max' => defined($data->{"max"}) ? $data->{"max"} : "", 'data_source_type' => $data->{"data_source_type"}}; + $$cache_metrics->{$metric_name} = {metric_id => $data->{metric_id}, metric_unit => defined($data->{unit_name}) ? $data->{unit_name} : "", + metric_warn => defined($data->{warn}) ? $data->{warn} : "", + warn_low => defined($data->{warn_low}) ? $data->{warn_low} : "", + warn_threshold_mode => defined($data->{warn_threshold_mode}) ? $data->{warn_threshold_mode} : "", + metric_crit => defined($data->{crit}) ? $data->{crit} : "", + crit_low => defined($data->{crit_low}) ? $data->{crit_low} : "", + crit_threshold_mode => defined($data->{crit_threshold_mode}) ? $data->{crit_threshold_mode} : "", + metric_min => defined($data->{min}) ? $data->{min} : "", + metric_max => defined($data->{max}) ? $data->{max} : "", + data_source_type => $data->{data_source_type}}; return 0; } @@ -372,17 +391,28 @@ sub check_update_extra_metric { my $self = shift; my $cache_metric = $_[0]; - if ($$cache_metric->{'metric_unit'} ne $self->{"metric_unit"} || - $$cache_metric->{'metric_warn'} ne $self->{"metric_warn"} || - $$cache_metric->{'metric_crit'} ne $self->{"metric_crit"} || - $$cache_metric->{'metric_min'} ne $self->{"metric_min"} || - $$cache_metric->{'metric_max'} ne $self->{"metric_max"}) { - $self->{'dbcentstorage'}->query("UPDATE `metrics` SET `unit_name` = " . $self->{'dbcentstorage'}->quote($self->{"metric_unit"}) . ", `warn` = '" . $self->{"metric_warn"} . "', `crit` = '" . $self->{"metric_crit"} . "', `min` = '" . $self->{"metric_min"} . "', `max` = '" . $self->{"metric_max"} . "' WHERE `metric_id` = " . $$cache_metric->{'metric_id'}); - $$cache_metric->{'metric_unit'} = $self->{"metric_unit"}; - $$cache_metric->{'metric_warn'} = $self->{"metric_warn"}; - $$cache_metric->{'metric_crit'} = $self->{"metric_crit"}; - $$cache_metric->{'metric_min'} = $self->{"metric_min"}; - $$cache_metric->{'metric_max'} = $self->{"metric_max"}; + if ($$cache_metric->{metric_unit} ne $self->{metric_unit} || + $$cache_metric->{metric_warn} ne $self->{metric_warn} || + $$cache_metric->{warn_low} ne $self->{warn_low} || + $$cache_metric->{warn_threshold_mode} ne $self->{warn_threshold_mode} || + $$cache_metric->{metric_crit} ne $self->{metric_crit} || + $$cache_metric->{crit_low} ne $self->{crit_low} || + $$cache_metric->{crit_threshold_mode} ne $self->{crit_threshold_mode} || + $$cache_metric->{metric_min} ne $self->{metric_min} || + $$cache_metric->{metric_max} ne $self->{metric_max}) { + $self->{dbcentstorage}->query("UPDATE `metrics` SET `unit_name` = " . $self->{dbcentstorage}->quote($self->{metric_unit}) . ", " . + "`warn` = " . $self->{dbcentstorage}->quote($self->{metric_warn}) . ", `warn_low` = " . $self->{dbcentstorage}->quote($self->{warn_low}) . ", `warn_threshold_mode` = " . $self->{dbcentstorage}->quote($self->{warn_threshold_mode}) . ", " . + "`crit` = " . $self->{dbcentstorage}->quote($self->{metric_crit}) . ", `crit_low` = " . $self->{dbcentstorage}->quote($self->{crit_low}) . ", `warn_threshold_mode` = " . $self->{dbcentstorage}->quote($self->{crit_threshold_mode}) . ", " . + "`min` = '" . $self->{metric_min} . "', `max` = '" . $self->{metric_max} . "' WHERE `metric_id` = " . $$cache_metric->{metric_id}); + $$cache_metric->{metric_unit} = $self->{metric_unit}; + $$cache_metric->{metric_warn} = $self->{metric_warn}; + $$cache_metric->{warn_low} = $self->{warn_low}; + $$cache_metric->{warn_threshold_mode} = $self->{warn_threshold_mode}; + $$cache_metric->{metric_crit} = $self->{metric_crit}; + $$cache_metric->{crit_low} = $self->{crit_low}; + $$cache_metric->{crit_threshold_mode} = $self->{crit_threshold_mode}; + $$cache_metric->{metric_min} = $self->{metric_min}; + $$cache_metric->{metric_max} = $self->{metric_max}; } } @@ -390,7 +420,7 @@ sub send_rename_command { my $self = shift; my ($old_host_name, $old_service_description, $new_host_name, $new_service_description) = @_; - $self->{'logger'}->writeLogInfo("Hostname/Servicename changed had been detected " . $old_host_name . "/" . $old_service_description); + $self->{logger}->writeLogInfo("Hostname/Servicename changed had been detected " . $old_host_name . "/" . $old_service_description); my $fh = $self->{'pipe_write'}; print $fh "RENAMECLEAN\t" . $old_host_name . "\t" . $old_service_description . "\t" . $new_host_name . "\t" . $new_service_description . "\n"; } @@ -544,6 +574,8 @@ sub parse_label { sub parse_value { my $self = shift; + my $with_unit = shift; + my $unit = ''; my $value = ""; my $neg = 1; @@ -557,8 +589,12 @@ sub parse_value { $value =~ s/,/./g; $value = $value * $neg; } - $self->skip_chars(";"); - return $value; + if (defined($with_unit) && $with_unit == 1) { + $unit = $self->parse_unit(); + } else { + $self->skip_chars(";"); + } + return ($value, $unit); } sub parse_unit { @@ -572,11 +608,75 @@ sub parse_unit { sub parse_threshold { my $self = shift; - my $value = ""; + my $neg = 1; + my $value_tmp = ""; + + my $arobase = 0; + my $infinite_neg = 0; + my $infinite_pos = 0; + my $value_start = ""; + my $value_end = ""; + my $global_status = 1; + + if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "@") { + $arobase = 1; + $self->{"perfdata_pos"}++; + } - $value = $self->continue_to(undef, "[ \t;]"); + if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "~") { + $infinite_neg = 1; + $self->{"perfdata_pos"}++; + } else { + if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "-") { + $neg = -1; + $self->{"perfdata_pos"}++; + } + $value_tmp = $self->continue_to(undef, "[^0-9\.,]"); + if (defined($value_tmp) && $value_tmp ne "") { + $value_tmp =~ s/,/./g; + $value_tmp = $value_tmp * $neg; + } + $neg = 1; + } + + if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq ":") { + if ($value_tmp ne "") { + $value_start = $value_tmp; + } else { + $value_start = 0; + } + $self->{"perfdata_pos"}++; + + if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "-") { + $neg = -1; + $self->{"perfdata_pos"}++; + } + $value_end = $self->continue_to(undef, "[^0-9\.,]"); + if (defined($value_tmp) && $value_end ne "") { + $value_end =~ s/,/./g; + $value_end = $value_end * $neg; + } else { + $infinite_pos = 1; + } + } else { + $value_end = $value_tmp; + } + + my $value = $self->continue_to(undef, "[ \t;]"); $self->skip_chars(";"); - return $value; + if ($value ne '') { + $self->{logger}->writeLogInfo("Wrong threshold..."); + $global_status = 0; + } + + if ($infinite_neg == 1) { + $value_start = '-1e500'; + } + if ($infinite_pos == 1) { + $value_end = '1e500'; + } + + return ($global_status, $value_start, $value_end, $arobase); } sub get_perfdata { @@ -595,17 +695,15 @@ sub get_perfdata { return 1; } - $perf_value = $self->parse_value(); + ($perf_value, $perf_unit) = $self->parse_value(1); if (!defined($perf_value) || $perf_value eq '') { $self->{"logger"}->writeLogError("Wrong perfdata format: " . $self->{'service_perfdata'}); return -1 if ($self->{'perfdata_parser_stop'} == 1); return 1; } - $perf_unit = $self->parse_unit(); - - $perf_warn = $self->parse_threshold(); - $perf_crit = $self->parse_threshold(); + my ($status_th_warn, $th_warn_start, $th_warn_end, $th_warn_inclusive) = $self->parse_threshold(); + my ($status_th_crit, $th_crit_start, $th_crit_end, $th_crit_inclusive) = $self->parse_threshold(); $perf_min = $self->parse_value(); $perf_max = $self->parse_value(); @@ -621,22 +719,31 @@ sub get_perfdata { } } - # Can't manage threshold well (db not ready) - if ($perf_warn =~ /[^0-9-.,]/) { - $perf_warn = ""; + $self->{metric_name} = $perf_label; + $self->{metric_value} = $perf_value; + $self->{metric_unit} = $perf_unit; + + $self->{metric_warn} = 0; + $self->{warn_low} = 0; + $self->{warn_threshold_mode} = 0; + if ($status_th_warn == 1) { + $self->{metric_warn} = $th_warn_end; + $self->{warn_low} = $th_warn_start; + $self->{warn_threshold_mode} = $th_warn_inclusive; } - if ($perf_crit =~ /[^0-9-.,]/) { - $perf_crit = ""; + + $self->{metric_crit} = 0; + $self->{crit_low} = 0; + $self->{crit_threshold_mode} = 0; + if ($status_th_warn == 1) { + $self->{metric_crit} = $th_crit_end; + $self->{crit_low} = $th_crit_start; + $self->{crit_threshold_mode} = $th_crit_inclusive; } - $self->{"metric_name"} = $perf_label; - $self->{"metric_value"} = $perf_value; - $self->{"metric_unit"} = $perf_unit; - $self->{"metric_warn"} = $perf_warn; - $self->{"metric_crit"} = $perf_crit; - $self->{"metric_min"} = $perf_min; - $self->{"metric_max"} = $perf_max; - $self->{"metric_type"} = $rrd_trans{$counter_type}; + $self->{metric_min} = $perf_min; + $self->{metric_max} = $perf_max; + $self->{metric_type} = $rrd_trans{$counter_type}; return 1; } diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index 15169734862..ad4a9b6f3d4 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -57,7 +57,6 @@ sub new { TIMEOUT => 60, rrd_cache_mode => 0, rrd_flush_time => 60 * 10, - centreon_23_compatibility => 0, perfdata_parser_stop => 1 ); @@ -356,7 +355,7 @@ sub create_delete_child { logger => $self->{logger}); $centreon_db_centstorage->connect(); - my $centstorage_action = centreon::centstorage::CentstorageAction->new($self->{logger}, $self->{rebuild_progress}, $self->{centstorage_config}->{centreon_23_compatibility}); + my $centstorage_action = centreon::centstorage::CentstorageAction->new($self->{logger}, $self->{rebuild_progress}); $centstorage_action->main($centreon_db_centreon, $centreon_db_centstorage, $self->{delete_pipes}{'reader_two'}, $self->{delete_pipes}{'writer_one'}, $self->{config_file}); exit(0); From df574ef48afafc624af2271a4e1ff841d7f68a74 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 10 Jun 2013 16:46:52 +0200 Subject: [PATCH 071/458] Ref #3616 - Wont fix UPDATE check for float value (int from check but float in DB) --- centreon/lib/perl/centreon/centstorage/CentstoragePool.pm | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index 039b4e5e187..27d98765063 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -361,7 +361,7 @@ sub create_metric { # Insert ($status, $stmt) = $self->{dbcentstorage}->query("INSERT INTO `metrics` (`index_id`, `metric_name`, `unit_name`, `warn`, `warn_low`, `warn_threshold_mode`, `crit`, `crit_low`, `crit_threshold_mode`, `min`, `max`, `data_source_type`) VALUES ('" . $index_id . "', " . $self->{dbcentstorage}->quote($metric_name) . ", '" . $self->{metric_unit} . "', " . $self->{dbcentstorage}->quote($self->{metric_warn}) . ", " . $self->{dbcentstorage}->quote($self->{warn_low}) . ", " . $self->{dbcentstorage}->quote($self->{warn_threshold_mode}) . ", " . - $self->{dbcentstorage}->quote($self->{metric_crit}) . ", " . $self->{dbcentstorage}->quote($self->{crit_low}) . ", " . $self->{dbcentstorage}->quote($self->{crit_threshold_mode}) . ", " . + $self->{dbcentstorage}->quote($self->{metric_crit}) . ", " . $self->{dbcentstorage}->quote($self->{crit_low}) . ", " . $self->{dbcentstorage}->quote($self->{crit_threshold_mode}) . ", '" . $self->{metric_min} . "', '" . $self->{metric_max} . "', '" . $self->{metric_type} . "')"); return -1 if ($status); my $last_insert_id = $self->{dbcentstorage}->last_insert_id(); @@ -402,7 +402,7 @@ sub check_update_extra_metric { $$cache_metric->{metric_max} ne $self->{metric_max}) { $self->{dbcentstorage}->query("UPDATE `metrics` SET `unit_name` = " . $self->{dbcentstorage}->quote($self->{metric_unit}) . ", " . "`warn` = " . $self->{dbcentstorage}->quote($self->{metric_warn}) . ", `warn_low` = " . $self->{dbcentstorage}->quote($self->{warn_low}) . ", `warn_threshold_mode` = " . $self->{dbcentstorage}->quote($self->{warn_threshold_mode}) . ", " . - "`crit` = " . $self->{dbcentstorage}->quote($self->{metric_crit}) . ", `crit_low` = " . $self->{dbcentstorage}->quote($self->{crit_low}) . ", `warn_threshold_mode` = " . $self->{dbcentstorage}->quote($self->{crit_threshold_mode}) . ", " . + "`crit` = " . $self->{dbcentstorage}->quote($self->{metric_crit}) . ", `crit_low` = " . $self->{dbcentstorage}->quote($self->{crit_low}) . ", `crit_threshold_mode` = " . $self->{dbcentstorage}->quote($self->{crit_threshold_mode}) . ", " . "`min` = '" . $self->{metric_min} . "', `max` = '" . $self->{metric_max} . "' WHERE `metric_id` = " . $$cache_metric->{metric_id}); $$cache_metric->{metric_unit} = $self->{metric_unit}; $$cache_metric->{metric_warn} = $self->{metric_warn}; @@ -659,6 +659,7 @@ sub parse_threshold { $infinite_pos = 1; } } else { + $value_start = 0; $value_end = $value_tmp; } @@ -735,7 +736,7 @@ sub get_perfdata { $self->{metric_crit} = 0; $self->{crit_low} = 0; $self->{crit_threshold_mode} = 0; - if ($status_th_warn == 1) { + if ($status_th_crit == 1) { $self->{metric_crit} = $th_crit_end; $self->{crit_low} = $th_crit_start; $self->{crit_threshold_mode} = $th_crit_inclusive; From 588b8cdd53bb10fddb477a15d8000737db051fb5 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 24 Jun 2013 14:52:21 +0200 Subject: [PATCH 072/458] Add no submit option for advanced treatment --- .../lib/perl/centreon/script/centreontrapd.pm | 16 +++++++++++++--- centreon/lib/perl/centreon/trapd/lib.pm | 4 ++-- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index d6f2e83ba7d..73b6e9e4cba 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -353,7 +353,8 @@ sub manage_pool { # sub do_exec { my $self = shift; - + my $matching_result = 0; + $self->{traps_global_status} = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_status}; # PREEXEC commands $self->execute_preexec(); @@ -364,13 +365,14 @@ sub do_exec { # Advanced matching rules if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment}) && $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment} == 1) { - $status = $self->checkMatchingRules(); + $matching_result = $self->checkMatchingRules(); } ##################################################################### # Submit value to passive service if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_submit_result_enable}) && - $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_submit_result_enable} == 1) { + $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_submit_result_enable} == 1 && + $matching_result == 0) { $self->submitResult(); } @@ -654,6 +656,7 @@ sub subtitute_centreon_var { # sub checkMatchingRules { my $self = shift; + my $matching_boolean = 0; # Check matching options foreach my $tmo_id (keys %{$self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}}) { @@ -695,9 +698,16 @@ sub checkMatchingRules { $self->{traps_global_status} = $tmoStatus; $self->{logger}->writeLogInfo("Regexp: String:$tmoString => REGEXP:$regexp"); $self->{logger}->writeLogInfo("Status: $self->{traps_global_status} ($tmoStatus)"); + $matching_boolean = 1; last; } } + + # Dont do submit if no matching + if ($matching_boolean == 0 && $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment_default} == 1) { + return 1; + } + return 0; } ################################ diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index a875070f5fb..5cca8d1ce19 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -96,7 +96,7 @@ sub get_oids { my $ref_result; my ($dstatus, $sth) = $cdb->query("SELECT name, traps_log, traps_execution_command, traps_reschedule_svc_enable, traps_id, traps_args, - traps_oid, traps_name, traps_advanced_treatment, traps_execution_command_enable, traps_submit_result_enable, traps_status, + traps_oid, traps_name, traps_advanced_treatment, traps_advanced_treatment_default, traps_execution_command_enable, traps_submit_result_enable, traps_status, traps_timeout, traps_exec_interval, traps_exec_interval_type, traps_routing_mode, traps_routing_value FROM traps LEFT JOIN traps_vendor ON (traps_vendor.id = traps.manufacturer_id) WHERE traps_oid = " . $cdb->quote($oid)); @@ -137,7 +137,7 @@ sub get_hosts { if ($args{trap_info}->{traps_routing_mode} == 1) { my $search_str = $args{centreontrapd}->substitute_string($args{trap_info}->{traps_routing_value}); ($dstatus, $sth) = $args{cdb}->query("SELECT host_id, host_name FROM host WHERE - host_address=" . $args{cdb}->quote($search_str); + host_address=" . $args{cdb}->quote($search_str)); } else { # Default Mode ($dstatus, $sth) = $args{cdb}->query("SELECT host_id, host_name FROM host WHERE From 6b6f1bb9accb0666a4dc75a266e8092ad24eec18 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 24 Jun 2013 17:37:37 +0200 Subject: [PATCH 073/458] Ref #3874 --- centreon/lib/perl/centreon/common/db.pm | 45 ++-- .../lib/perl/centreon/script/centreontrapd.pm | 198 +++++++----------- centreon/lib/perl/centreon/trapd/lib.pm | 50 ++--- 3 files changed, 123 insertions(+), 170 deletions(-) diff --git a/centreon/lib/perl/centreon/common/db.pm b/centreon/lib/perl/centreon/common/db.pm index c2a6a533325..a72496265f4 100644 --- a/centreon/lib/perl/centreon/common/db.pm +++ b/centreon/lib/perl/centreon/common/db.pm @@ -15,18 +15,27 @@ sub new { user => undef, password => undef, port => 3306, - force => 0 + force => 0, + type => "mysql" ); my $self = {%defaults, %options}; - $self->{port} = 3306 if (!defined($self->{port})); + $self->{type} = 'mysql' if (!defined($self->{type})); $self->{"instance"} = undef; - $self->{"type"} = "mysql"; $self->{"args"} = []; bless $self, $class; return $self; } +# Getter/Setter DB name +sub type { + my $self = shift; + if (@_) { + $self->{"type"} = shift; + } + return $self->{"type"}; +} + # Getter/Setter DB name sub db { my $self = shift; @@ -141,16 +150,26 @@ sub connect() { my $status = 0; while (1) { - $self->{port} = 3306 if (!defined($self->{port})); - $self->{"instance"} = DBI->connect( - "DBI:".$self->{"type"} - .":".$self->{"db"} - .":".$self->{"host"} - .":".$self->{"port"}, - $self->{"user"}, - $self->{"password"}, - { "RaiseError" => 0, "PrintError" => 0, "AutoCommit" => 1 } - ); + $self->{port} = 3306 if (!defined($self->{port}) && $self->{"type"} eq 'mysql'); + if ($self->{"type"} =~ /SQLite/i) { + $self->{"instance"} = DBI->connect( + "DBI:".$self->{"type"} + .":".$self->{"db"}, + $self->{"user"}, + $self->{"password"}, + { "RaiseError" => 0, "PrintError" => 0, "AutoCommit" => 1 } + ); + } else { + $self->{"instance"} = DBI->connect( + "DBI:".$self->{"type"} + .":".$self->{"db"} + .":".$self->{"host"} + .":".$self->{"port"}, + $self->{"user"}, + $self->{"password"}, + { "RaiseError" => 0, "PrintError" => 0, "AutoCommit" => 1 } + ); + } if (defined($self->{"instance"})) { last; } diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 73b6e9e4cba..f63cf89c7bc 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -28,7 +28,6 @@ sub new { %{$self->{centreontrapd_default_config}} = ( - daemon => 1, timeout_end => 30, spool_directory => "/var/spool/centreontrapd/", sleep => 2, @@ -143,10 +142,7 @@ sub init { $self->{centreontrapd_config}->{time_format}); centreon::trapd::lib::init_modules(logger => $self->{logger}, config => $self->{centreontrapd_config}, htmlentities => \$self->{htmlentities}); - # Daemon Only - if ($self->{centreontrapd_config}->{daemon} == 1) { - $self->set_signal_handlers; - } + $self->set_signal_handlers; } sub set_signal_handlers { @@ -414,19 +410,6 @@ sub manage_exec { my $self = shift; $self->{id_logdb}++; - if ($self->{centreontrapd_config}->{daemon} == 0) { - eval { - local $SIG{ALRM} = sub { die "TIMEOUT"; }; - alarm($self->{centreontrapd_config}->{cmd_timeout}); - $self->do_exec(); - alarm(0); - }; - if ($@) { - $self->{logger}->writeLogError("ERROR: Exec timeout"); - return 0; - } - return 1; - } #### Fork And manage exec #### ####### Check Interval ###### @@ -831,6 +814,7 @@ sub run { $self->{logger}->writeLogDebug("PID: $$"); $self->{cdb} = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, + type => $self->{centreon_config}->{db_type}, host => $self->{centreon_config}->{db_host}, port => $self->{centreon_config}->{db_port}, user => $self->{centreon_config}->{db_user}, @@ -848,122 +832,94 @@ sub run { } $self->{whoami} = getpwuid($<); - if ($self->{centreontrapd_config}->{daemon} == 1) { - if ($self->{centreontrapd_config}->{log_trap_db} == 1) { - $self->create_logdb_child(); - } - - while (1) { - centreon::trapd::lib::purge_duplicate_trap(config => $self->{centreontrapd_config}, - duplicate_traps => \%{$self->{duplicate_traps}}); - while ((my $file = centreon::trapd::lib::get_trap(logger => $self->{logger}, - config => $self->{centreontrapd_config}, - filenames => \@{$self->{filenames}}))) { - $self->{logger}->writeLogDebug("Processing file: $file"); + if ($self->{centreontrapd_config}->{log_trap_db} == 1) { + $self->create_logdb_child(); + } + + while (1) { + centreon::trapd::lib::purge_duplicate_trap(config => $self->{centreontrapd_config}, + duplicate_traps => \%{$self->{duplicate_traps}}); + while ((my $file = centreon::trapd::lib::get_trap(logger => $self->{logger}, + config => $self->{centreontrapd_config}, + filenames => \@{$self->{filenames}}))) { + $self->{logger}->writeLogDebug("Processing file: $file"); + + # Test can delete before. Dont go after if we cant + if (! -w $self->{centreontrapd_config}->{spool_directory} . $file) { + $self->{logger}->writeLogError("Dont have write permission on '" . $self->{centreontrapd_config}->{spool_directory} . $file . "' file."); + if ($self->{centreontrapd_config}->{policy_trap} == 1) { + unshift @{$self->{filenames}}, $file; + # We're waiting. We are in a loop + sleep $self->{centreontrapd_config}->{sleep}; + next; + } + } + + if (open FILE, $self->{centreontrapd_config}->{spool_directory} . $file) { + my $unlink_trap = 1; + my $trap_is_a_duplicate = 0; + my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, + config => $self->{centreontrapd_config}, + handle => \*FILE, + agent_dns_name => \$self->{agent_dns_name}, + trap_date => \$self->{trap_date}, + trap_time => \$self->{trap_time}, + trap_date_time => \$self->{trap_date_time}, + trap_date_time_epoch => \$self->{trap_date_time_epoch}, + duplicate_traps => \%{$self->{duplicate_traps}}, + digest_trap => \$self->{digest_trap}, + var => \@{$self->{var}}, + entvar => \@{$self->{entvar}}, + entvarname => \@{$self->{entvarname}}); - # Test can delete before. Dont go after if we cant - if (! -w $self->{centreontrapd_config}->{spool_directory} . $file) { - $self->{logger}->writeLogError("Dont have write permission on '" . $self->{centreontrapd_config}->{spool_directory} . $file . "' file."); - if ($self->{centreontrapd_config}->{policy_trap} == 1) { - unshift @{$self->{filenames}}, $file; - # We're waiting. We are in a loop - sleep $self->{centreontrapd_config}->{sleep}; - next; + if ($readtrap_result == 1) { + if (centreon::trapd::lib::check_known_trap(logger => $self->{logger}, + config => $self->{centreontrapd_config}, + oid2verif => ${$self->{var}}[3], + cdb => $self->{cdb}, + last_cache_time => \$self->{last_cache_time}, + oids_cache => \$self->{oids_cache}) == 1) { + $unlink_trap = $self->getTrapsInfos(); } + } elsif ($readtrap_result == 0) { + $self->{logger}->writeLogDebug("Error processing trap file $file. Skipping..."); + } elsif ($readtrap_result == -1) { + $trap_is_a_duplicate = 1; + $self->{logger}->writeLogInfo("Duplicate trap detected in trap file $file. Skipping..."); } - if (open FILE, $self->{centreontrapd_config}->{spool_directory} . $file) { - my $unlink_trap = 1; - my $trap_is_a_duplicate = 0; - my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, - config => $self->{centreontrapd_config}, - handle => \*FILE, - agent_dns_name => \$self->{agent_dns_name}, - trap_date => \$self->{trap_date}, - trap_time => \$self->{trap_time}, - trap_date_time => \$self->{trap_date_time}, - trap_date_time_epoch => \$self->{trap_date_time_epoch}, - duplicate_traps => \%{$self->{duplicate_traps}}, - digest_trap => \$self->{digest_trap}, - var => \@{$self->{var}}, - entvar => \@{$self->{entvar}}, - entvarname => \@{$self->{entvarname}}); - - if ($readtrap_result == 1) { - if (centreon::trapd::lib::check_known_trap(logger => $self->{logger}, - config => $self->{centreontrapd_config}, - oid2verif => ${$self->{var}}[3], - cdb => $self->{cdb}, - last_cache_time => \$self->{last_cache_time}, - oids_cache => \$self->{oids_cache}) == 1) { - $unlink_trap = $self->getTrapsInfos(); - } - } elsif ($readtrap_result == 0) { - $self->{logger}->writeLogDebug("Error processing trap file $file. Skipping..."); - } elsif ($readtrap_result == -1) { - $trap_is_a_duplicate = 1; - $self->{logger}->writeLogInfo("Duplicate trap detected in trap file $file. Skipping..."); - } - - close FILE; - if ($self->{centreontrapd_config}->{policy_trap} == 0 || ($self->{centreontrapd_config}->{policy_trap} == 1 && $unlink_trap == 1)) { - unless (unlink($self->{centreontrapd_config}->{spool_directory} . $file)) { - $self->{logger}->writeLogError("Unable to delete trap file $file from spool dir:$!"); - } - } else { - $self->{logger}->writeLogError("Dont skip trap. Need to solve the error."); - # we reput in AND we delete trap_digest (avoid skipping duplicate trap) - unshift @{$self->{filenames}}, $file; - if ($self->{centreontrapd_config}->{duplicate_trap_window}) { - delete $self->{duplicate_traps}->{$self->{digest_trap}}; - } - sleep $self->{centreontrapd_config}->{sleep}; + close FILE; + if ($self->{centreontrapd_config}->{policy_trap} == 0 || ($self->{centreontrapd_config}->{policy_trap} == 1 && $unlink_trap == 1)) { + unless (unlink($self->{centreontrapd_config}->{spool_directory} . $file)) { + $self->{logger}->writeLogError("Unable to delete trap file $file from spool dir:$!"); } } else { - $self->{logger}->writeLogError("Could not open trap file " . $self->{centreontrapd_config}->{spool_directory} . "$file: ($!)"); - if ($self->{centreontrapd_config}->{policy_trap} == 1) { - $self->{logger}->writeLogError("Dont skip trap. Need to solve the error."); - # we reput in - unshift @{$self->{filenames}}, $file; + $self->{logger}->writeLogError("Dont skip trap. Need to solve the error."); + # we reput in AND we delete trap_digest (avoid skipping duplicate trap) + unshift @{$self->{filenames}}, $file; + if ($self->{centreontrapd_config}->{duplicate_trap_window}) { + delete $self->{duplicate_traps}->{$self->{digest_trap}}; } + sleep $self->{centreontrapd_config}->{sleep}; } - - if ($self->{timetoreload} == 1) { - $self->reload(); + } else { + $self->{logger}->writeLogError("Could not open trap file " . $self->{centreontrapd_config}->{spool_directory} . "$file: ($!)"); + if ($self->{centreontrapd_config}->{policy_trap} == 1) { + $self->{logger}->writeLogError("Dont skip trap. Need to solve the error."); + # we reput in + unshift @{$self->{filenames}}, $file; } } - $self->{logger}->writeLogDebug("Sleeping for " . $self->{centreontrapd_config}->{sleep} . " seconds"); - sleep $self->{centreontrapd_config}->{sleep}; - - $self->manage_pool(1); - } - } else { - my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, - config => $self->{centreontrapd_config}, - handle => \*STDIN, - agent_dns_name => \$self->{agent_dns_name}, - trap_date => \$self->{trap_date}, - trap_time => \$self->{trap_time}, - trap_date_time => \$self->{trap_date_time}, - trap_date_time_epoch => \$self->{trap_date_time_epoch}, - duplicate_traps => \%{$self->{duplicate_traps}}, - digest_trap => \$self->{digest_trap}, - var => \@{$self->{var}}, - entvar => \@{$self->{entvar}}, - entvarname => \@{$self->{entvarname}}); - if ($readtrap_result == 1) { - if (centreon::trapd::lib::check_known_trap(logger => $self->{logger}, - config => $self->{centreontrapd_config}, - oid2verif => ${$self->{var}}[3], - cdb => $self->{cdb}, - last_cache_time => \$self->{last_cache_time}, - oids_cache => \$self->{oids_cache}) == 1) { - $self->getTrapsInfos(); + if ($self->{timetoreload} == 1) { + $self->reload(); } - } elsif ($readtrap_result == 0) { - $self->{logger}->writeLogDebug("Error processing trap file. Skipping..."); } + + $self->{logger}->writeLogDebug("Sleeping for " . $self->{centreontrapd_config}->{sleep} . " seconds"); + sleep $self->{centreontrapd_config}->{sleep}; + + $self->manage_pool(1); } } diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 5cca8d1ce19..db25791dfaa 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -165,11 +165,11 @@ sub get_services { my $services_do = {}; ### Get service List for the Host - my ($dstatus, $sth) = $cdb->query("(SELECT s.service_id, s.service_description FROM host h, host_service_relation hsr, service s WHERE + my ($dstatus, $sth) = $cdb->query("SELECT s.service_id, s.service_description FROM host h, host_service_relation hsr, service s WHERE h.host_id = " . $host_id . " AND h.host_activate = '1' AND h.host_id = hsr.host_host_id AND hsr.service_service_id = s.service_id AND s.service_activate = '1' - ) UNION ALL (SELECT s.service_id, s.service_description FROM + UNION ALL SELECT s.service_id, s.service_description FROM host h, host_service_relation hsr, hostgroup_relation hgr, service s WHERE h.host_id = " . $host_id . " AND h.host_activate = '1' AND - h.host_id = hgr.host_host_id AND hgr.hostgroup_hg_id = hsr.hostgroup_hg_id AND hsr.service_service_id = s.service_id AND s.service_activate = '1')"); + h.host_id = hgr.host_host_id AND hgr.hostgroup_hg_id = hsr.hostgroup_hg_id AND hsr.service_service_id = s.service_id AND s.service_activate = '1'"); return -1 if ($dstatus == -1); $result = $sth->fetchall_hashref('service_id'); foreach my $service_id (keys %$result) { @@ -333,26 +333,8 @@ sub check_known_trap { my $db_mode = 1; if ($args{config}->{cache_unknown_traps_enable} == 1) { - if ($args{config}->{daemon} != 1) { - $db_mode = 0; - if (-e $args{config}->{cache_unknown_traps_file}) { - if ((my $result = stat($args{config}->{cache_unknown_traps_file}))) { - if ((time() - $result->mtime) > $args{config}->{cache_unknown_traps_retention}) { - $args{logger}->writeLogInfo("Try to rewrite cache"); - !($db_mode = get_cache_oids(cdb => $args{cdb}, oids_cache => $args{oids_cache}, last_cache_time => $args{last_cache_time})) && ($db_mode = write_cache_file(logger => $args{logger}, config => $args{config}, oids_cache => $args{oids_cache})); - } - } else { - $args{logger}->writeLogError("Can't stat file " . $args{config}->{cache_unknown_traps_file} . ": $!"); - $args{logger}->writeLogError("Go to DB to get info"); - $db_mode = 1; - } - } else { - !($db_mode = get_cache_oids(cdb => $args{cdb}, oids_cache => $args{oids_cache}, last_cache_time => $args{last_cache_time})) && ($db_mode = write_cache_file(logger => $args{logger}, config => $args{config}, oids_cache => $args{oids_cache})); - } - } else { - if (!defined(${$args{last_cache_time}}) || ((time() - ${$args{last_cache_time}}) > $args{config}->{cache_unknown_traps_retention})) { - $db_mode = get_cache_oids(cdb => $args{cdb}, oids_cache => $args{oids_cache}, last_cache_time => $args{last_cache_time}); - } + if (!defined(${$args{last_cache_time}}) || ((time() - ${$args{last_cache_time}}) > $args{config}->{cache_unknown_traps_retention})) { + $db_mode = get_cache_oids(cdb => $args{cdb}, oids_cache => $args{oids_cache}, last_cache_time => $args{last_cache_time}); } } @@ -385,7 +367,7 @@ sub check_known_trap { # Read db my ($status, $sth) = $args{cdb}->query("SELECT traps_oid FROM traps WHERE traps_oid = " . $args{cdb}->quote($oid2verif)); return 0 if ($status == -1); - if ($sth->rows == 0) { + if (!$sth->fetchrow_hashref()) { $args{logger}->writeLogInfo("Unknown trap"); return 0; } @@ -478,22 +460,18 @@ sub readtrap { $args{logger}->writeLogDebug("Reading trap. Current time: " . scalar(localtime())); - if ($args{config}->{daemon} == 1) { - chomp(${$args{trap_date_time_epoch}} = (<$input>)); # Pull time trap was spooled - push(@rawtrap, ${$args{trap_date_time_epoch}}); - if (${$args{trap_date_time_epoch}} eq "") { - if ($args{logger}->is_debug()) { - $args{logger}->writeLogDebug(" Invalid trap file. Expected a serial time on the first line but got nothing"); - return 0; - } + chomp(${$args{trap_date_time_epoch}} = (<$input>)); # Pull time trap was spooled + push(@rawtrap, ${$args{trap_date_time_epoch}}); + if (${$args{trap_date_time_epoch}} eq "") { + if ($args{logger}->is_debug()) { + $args{logger}->writeLogDebug(" Invalid trap file. Expected a serial time on the first line but got nothing"); + return 0; } - ${$args{trap_date_time_epoch}} =~ s(`)(')g; #` Replace any back ticks with regular single quote - } else { - ${$args{trap_date_time_epoch}} = time(); # Use current time as time trap was received } + ${$args{trap_date_time_epoch}} =~ s(`)(')g; #` Replace any back ticks with regular single quote my @localtime_array; - if ($args{config}->{daemon} == 1 && $args{config}->{use_trap_time} == 1) { + if ($args{config}->{use_trap_time} == 1) { @localtime_array = localtime(${$args{trap_date_time_epoch}}); if ($args{config}->{date_time_format} eq "") { From 2401ace5390d330d5aa8ebd31550d39fb5083d77 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 25 Jun 2013 09:57:52 +0200 Subject: [PATCH 074/458] Clean code for centreontrapd --- .../lib/perl/centreon/script/centreontrapd.pm | 1 - centreon/lib/perl/centreon/trapd/lib.pm | 57 ++++--------------- 2 files changed, 10 insertions(+), 48 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index f63cf89c7bc..6e28d1219a4 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -45,7 +45,6 @@ sub new { date_time_format => "", cache_unknown_traps_enable => 1, cache_unknown_traps_retention => 600, - cache_unknown_traps_file => "/tmp/centreontrapd.cache", # 0 = central, 1 = poller mode => 0, cmd_timeout => 10, diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index db25791dfaa..822ff26ea5f 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -297,30 +297,12 @@ sub get_cache_oids { my %args = @_; my ($status, $sth) = $args{cdb}->query("SELECT traps_oid FROM traps"); - return 1 if ($status == -1); + return -1 if ($status == -1); ${$args{oids_cache}} = $sth->fetchall_hashref("traps_oid"); ${$args{last_cache_time}} = time(); return 0; } -sub write_cache_file { - # logger => obj - # config => hash - # oids_cache => val (not ref) - my %args = @_; - - if (!open(FILECACHE, ">", $args{config}->{cache_unknown_traps_file})) { - $args{logger}->writeLogError("Can't write " . $args{config}->{cache_unknown_traps_file} . ": $!"); - $args{logger}->writeLogError("Go to DB to get info"); - return 1; - } - my $oids_value = join("\n", keys %{${$args{oids_cache}}}); - print FILECACHE $oids_value; - close FILECACHE; - $args{logger}->writeLogInfo("Cache file refreshed"); - return 0; -} - sub check_known_trap { # logger => obj # config => hash @@ -330,40 +312,21 @@ sub check_known_trap { # oids_cache => ref my %args = @_; my $oid2verif = $args{oid2verif}; - my $db_mode = 1; if ($args{config}->{cache_unknown_traps_enable} == 1) { if (!defined(${$args{last_cache_time}}) || ((time() - ${$args{last_cache_time}}) > $args{config}->{cache_unknown_traps_retention})) { - $db_mode = get_cache_oids(cdb => $args{cdb}, oids_cache => $args{oids_cache}, last_cache_time => $args{last_cache_time}); - } - } - - if ($db_mode == 0) { - if (defined(${$args{oids_cache}})) { - if (defined(${$args{oids_cache}}->{$oid2verif})) { - return 1; - } else { - $args{logger}->writeLogInfo("Unknown trap"); - return 0; - } - } else { - if (!open FILECACHE, $args{config}->{cache_unknown_traps_file}) { - $args{logger}->writeLogError("Can't read file " . $args{config}->{cache_unknown_traps_file} . ": $!"); - $db_mode = 1; - } else { - while () { - if (/^$oid2verif$/m) { - return 1; - } - } - close FILECACHE; - $args{logger}->writeLogInfo("Unknown trap"); + if (get_cache_oids(cdb => $args{cdb}, oids_cache => $args{oids_cache}, last_cache_time => $args{last_cache_time}) == -1) { + $args{logger}->writeLogError("Cant load cache trap oids."); return 0; } } - } - - if ($db_mode == 1) { + if (defined(${$args{oids_cache}}->{$oid2verif})) { + return 1; + } else { + $args{logger}->writeLogInfo("Unknown trap"); + return 0; + } + } else { # Read db my ($status, $sth) = $args{cdb}->query("SELECT traps_oid FROM traps WHERE traps_oid = " . $args{cdb}->quote($oid2verif)); return 0 if ($status == -1); From 4d5458a738bebf42fb7209c05fd733252dde0537 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 25 Jun 2013 10:37:15 +0200 Subject: [PATCH 075/458] Fix some issue with centreontrapd (reload) --- centreon/lib/perl/centreon/common/db.pm | 2 +- .../lib/perl/centreon/script/centreontrapd.pm | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/centreon/lib/perl/centreon/common/db.pm b/centreon/lib/perl/centreon/common/db.pm index a72496265f4..eaa0af03a86 100644 --- a/centreon/lib/perl/centreon/common/db.pm +++ b/centreon/lib/perl/centreon/common/db.pm @@ -247,7 +247,7 @@ sub query { $statement_handle = $self->{"instance"}->prepare($query); if (!defined $statement_handle) { - $self->error($statement_handle->errstr, $query); + $self->error($self->{"instance"}->errstr, $query); $status = -1; last if $self->{'force'} == 0; next; diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 6e28d1219a4..44de4e28349 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -191,6 +191,7 @@ sub handle_TERM { sub handle_HUP { my $self = shift; + $self->{logger}->writeLogInfo("$$ Receiving order to reload..."); $self->{timetoreload} = 1; } @@ -270,6 +271,12 @@ sub reload { centreon::common::misc::reload_db_config($self->{logger}, $self->{config_file}, $self->{cdb}); centreon::common::misc::check_debug($self->{logger}, "debug_centreontrapd", $self->{cdb}, "centreontrapd main process"); + if ($self->{cdb}->type() =~ /SQLite/i) { + $self->{logger}->writeLogInfo("Sqlite database. Need to disconnect and connect file."); + $self->{cdb}->disconnect(); + $self->{cdb}->connect(); + } + if ($self->{logdb_pipes}{'running'} == 1) { kill('HUP', $self->{pid_logdb_child}); $self->{logger}->writeLogInfo("Send -HUP signal to logdb process.."); @@ -279,8 +286,12 @@ sub reload { ($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}) = centreon::trapd::lib::manage_params_conf($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}); - centreon::trapd::lib::init_modules(); - centreon::trapd::lib::get_cache_oids(); + # redefine to avoid out when we try modules + $SIG{__DIE__} = undef; + centreon::trapd::lib::init_modules(logger => $self->{logger}, config => $self->{centreontrapd_config}, htmlentities => \$self->{htmlentities}); + $self->set_signal_handlers; + + centreon::trapd::lib::get_cache_oids(cdb => $self->{cdb}, oids_cache => \$self->{oids_cache}, last_cache_time => \$self->{last_cache_time}); $self->{timetoreload} = 0; } @@ -918,6 +929,9 @@ sub run { $self->{logger}->writeLogDebug("Sleeping for " . $self->{centreontrapd_config}->{sleep} . " seconds"); sleep $self->{centreontrapd_config}->{sleep}; + if ($self->{timetoreload} == 1) { + $self->reload(); + } $self->manage_pool(1); } } From 29feb91348c26be4094e30c746f4c751e45f38f1 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 25 Jun 2013 11:36:47 +0200 Subject: [PATCH 076/458] centreontrapd: add debug, add functions --- .../lib/perl/centreon/script/centreontrapd.pm | 45 +++++++++++++------ centreon/lib/perl/centreon/trapd/lib.pm | 15 +++++-- 2 files changed, 43 insertions(+), 17 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 44de4e28349..bc734a24eb0 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -551,7 +551,7 @@ sub execute_preexec { foreach my $trap_id (keys %{$self->{ref_oids}->{ $self->{current_trap_id} }->{traps_preexec}}) { my $tpe_string = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$trap_id}->{tpe_string}; $tpe_string = $self->substitute_string($tpe_string); - $tpe_string = $self->subtitute_centreon_var($tpe_string); + $tpe_string = $self->substitute_centreon_var($tpe_string); my $output = `$tpe_string`; if ($? == -1) { @@ -593,13 +593,13 @@ sub substitute_string { for (my $i=0; $i <= $#{$self->{entvar}}; $i++) { my $x = $i + 1; $str =~ s/\@\{${$self->{entvarname}}[$i]\}/${$self->{entvar}}[$i]/g; - $str =~ s/\$$x(\s|$)/${$self->{entvar}}[$i]/g; + $str =~ s/\$$x([^0-9]|$)/${$self->{entvar}}[$i]$1/g; } # Substitute preexec var for (my $i=0; $i <= $#{$self->{preexec}}; $i++) { my $x = $i + 1; - $str =~ s/\$p$x(\s|$)/${$self->{preexec}}[$i]/g; + $str =~ s/\$p$x([^0-9]|$)/${$self->{preexec}}[$i]$1/g; } # Substitute $* @@ -607,25 +607,25 @@ sub substitute_string { $str =~ s/\$\*/$sub_str/g; # $A - $str =~ s/\$A(\s|$)/$self->{agent_dns_name}/g; + $str =~ s/\$A/$self->{agent_dns_name}/g; # $aA (Trap agent IP Adress) - $str =~ s/\$aA(\s|$)/${$self->{var}}[4]/g; + $str =~ s/\$aA/${$self->{var}}[4]/g; # $R, $r (Trap Hostname) - $str =~ s/\$R(\s|$)/${$self->{var}}[0]/g; - $str =~ s/\$r(\s|$)/${$self->{var}}[0]/g; + $str =~ s/\$R/${$self->{var}}[0]/g; + $str =~ s/\$r/${$self->{var}}[0]/g; # $aR, $ar (IP Adress) - $str =~ s/\$aR(\s|$)/${$self->{var}}[1]/g; - $str =~ s/\$ar(\s|$)/${$self->{var}}[1]/g; + $str =~ s/\$aR/${$self->{var}}[1]/g; + $str =~ s/\$ar/${$self->{var}}[1]/g; # Clean OID $str =~ s/\@\{[\.0-9]*\}//g; return $str; } -sub subtitute_centreon_var { +sub substitute_centreon_var { my $self = shift; my $str = $_[0]; @@ -644,6 +644,25 @@ sub subtitute_centreon_var { return $str; } +sub substitute_centreon_functions { + my $self = shift; + my $str = $_[0]; + + if ($str =~ /\@GETHOSTBYADDR\((.*?)\)\@/) { + my $result = gethostbyaddr(Socket::inet_aton("$1"),Socket::AF_INET()); + $result = '' if (!defined($result)); + $str =~ s/\@GETHOSTBYADDR\(.*?\)\@/$result/; + } + if ($str =~ /\@GETHOSTBYNAME\((.*?)\)\@/) { + my $result = gethostbyname("$1"); + $result = inet_ntoa($result) if (defined($result)); + $result = '' if (!defined($result)); + $str =~ s/\@GETHOSTBYNAME\(.*?\)\@/$result/; + } + + return $str; +} + ####################################### ## Check Advanced Matching Rules # @@ -675,7 +694,7 @@ sub checkMatchingRules { } $tmoString = $self->substitute_string($tmoString); - $tmoString = $self->subtitute_centreon_var($tmoString); + $tmoString = $self->substitute_centreon_var($tmoString); ########################## # REPLACE special Chars @@ -723,7 +742,7 @@ sub executeCommand { $traps_execution_command =~ s/\'\;/'/g; } - $traps_execution_command = $self->subtitute_centreon_var($traps_execution_command); + $traps_execution_command = $self->substitute_centreon_var($traps_execution_command); ########################## # SEND COMMAND @@ -835,7 +854,7 @@ sub run { if ($self->{centreontrapd_config}->{mode} == 0) { $self->{cmdFile} = $self->{centreon_config}->{VarLib} . "/centcore.cmd"; } else { - # Dirty!!! Need to know the poller + # Dirty!!! Need to know the poller (not Dirty if you use SQLite database) my ($status, $sth) = $self->{cdb}->query("SELECT `command_file` FROM `cfg_nagios` WHERE `nagios_activate` = '1' LIMIT 1"); my @conf = $sth->fetchrow_array(); $self->{cmdFile} = $conf[0]; diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 822ff26ea5f..af00d655980 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -133,19 +133,26 @@ sub get_hosts { my %args = @_; my ($dstatus, $sth); my $ref_result; + my $request; if ($args{trap_info}->{traps_routing_mode} == 1) { my $search_str = $args{centreontrapd}->substitute_string($args{trap_info}->{traps_routing_value}); - ($dstatus, $sth) = $args{cdb}->query("SELECT host_id, host_name FROM host WHERE - host_address=" . $args{cdb}->quote($search_str)); + $search_str = $args{centreontrapd}->substitute_centreon_functions($search_str); + $request = "SELECT host_id, host_name FROM host WHERE host_address = " . $args{cdb}->quote($search_str); } else { # Default Mode - ($dstatus, $sth) = $args{cdb}->query("SELECT host_id, host_name FROM host WHERE - host_address=" . $args{cdb}->quote($args{agent_dns_name}) . " OR host_address=" . $args{cdb}->quote($args{ip_address})); + $request = "SELECT host_id, host_name FROM host WHERE host_address=" . $args{cdb}->quote($args{agent_dns_name}) . " OR host_address=" . $args{cdb}->quote($args{ip_address}); } + ($dstatus, $sth) = $args{cdb}->query($request); return -1 if ($dstatus == -1); $ref_result = $sth->fetchall_hashref('host_id'); + + if ($args{logger}->is_debug()) { + if (scalar(keys %$ref_result) == 0) { + $args{logger}->writeLogDebug("Cant find a host. Request: " . $request); + } + } # Get server_id foreach (keys %$ref_result) { From 65a8654165a68b2a12ea84b09f9aa38702a58c4e Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 26 Jun 2013 15:12:29 +0200 Subject: [PATCH 077/458] Fix trap preexec --- centreon/lib/perl/centreon/script/centreontrapd.pm | 6 +++--- centreon/lib/perl/centreon/trapd/lib.pm | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index bc734a24eb0..8f07e15d0cf 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -62,7 +62,7 @@ sub new { @{$self->{var}} = undef; # Variables of trap received by SNMPTRAPD @{$self->{entvar}} = undef; # Enterprise variable values of trap received by SNMPTRAPD @{$self->{entvarname}} = undef; # Enterprise variable names of trap received by SNMPTRAPD - @{$self->{preexec}} = undef; # Result from PREEXEC + @{$self->{preexec}} = (); # Result from PREEXEC $self->{agent_dns_name} = undef; $self->{trap_date} = undef; $self->{trap_time} = undef; @@ -548,8 +548,8 @@ sub submitResult { sub execute_preexec { my $self = shift; - foreach my $trap_id (keys %{$self->{ref_oids}->{ $self->{current_trap_id} }->{traps_preexec}}) { - my $tpe_string = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$trap_id}->{tpe_string}; + foreach my $tpe_order (keys %{$self->{ref_oids}->{ $self->{current_trap_id} }->{traps_preexec}}) { + my $tpe_string = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_preexec}->{$tpe_order}->{tpe_string}; $tpe_string = $self->substitute_string($tpe_string); $tpe_string = $self->substitute_centreon_var($tpe_string); diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index af00d655980..b7bfa36c6ff 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -114,7 +114,7 @@ sub get_oids { # Get Trap PREEXEC Commands ($dstatus, $sth) = $cdb->query("SELECT * FROM traps_preexec WHERE trap_id = " . $_ . " ORDER BY tpe_order ASC"); return -1 if ($dstatus == -1); - $ref_result->{$_}->{traps_preexec} = $sth->fetchall_hashref("trap_id"); + $ref_result->{$_}->{traps_preexec} = $sth->fetchall_hashref("tpe_order"); # Get Associated Host # TODO From 9f7ced8c42e92cf1faf44811b0d30f22c3257b9b Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 27 Jun 2013 11:58:19 +0200 Subject: [PATCH 078/458] Ref #3874 --- centreon/lib/perl/centreon/script/centcore.pm | 43 +++++-------------- 1 file changed, 11 insertions(+), 32 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index 74689246ce7..bf6a93397d2 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -662,22 +662,12 @@ sub syncTraps($) { my $port = checkSSHPort($ns_server->{'ssh_port'}); if ($id != 0 && $ns_server->{'localhost'} == 0) { - my $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/ 2>&1"; + my $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/$id/centreontrapd.sdb $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/ 2>&1"; $self->{logger}->writeLogDebug($cmd); $stdout = `$cmd`; if (defined($stdout) && $stdout){ $self->{logger}->writeLogInfo("Result : $stdout"); } - - $self->{logger}->writeLogDebug("ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l"); - my $ls = `ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l`; - if ($ls > 1) { - $self->{logger}->writeLogDebug("$self->{rsync} --port=$port -c /etc/snmp/centreon_traps/*.conf ". $ns_server->{'ns_ip_address'} .":/etc/snmp/centreon_traps/"); - $stdout = `$self->{rsync} --port=$port -c /etc/snmp/centreon_traps/*.conf $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/`; - if (defined($stdout) && $stdout){ - $self->{logger}->writeLogInfo("Result : $stdout\n"); - } - } } } else { # synchronize Archives for all pollers @@ -689,23 +679,12 @@ sub syncTraps($) { my $port = checkSSHPort($ns_server->{'ssh_port'}); if ($id == 0) { - my $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/*.ini $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/ 2>&1"; + my $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/$id/centreontrapd.sdb $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/ 2>&1"; $self->{logger}->writeLogDebug($cmd); $stdout = `$cmd`; if (defined($stdout) && $stdout){ $self->{logger}->writeLogInfo("Result : $stdout"); } - $cmd = "ls -l /etc/snmp/centreon_traps/*.conf 2>> /dev/null | wc -l"; - $self->{logger}->writeLogDebug($cmd); - my $ls = `$cmd`; - if ($ls > 1) { - $cmd = "$self->{rsync} --port=$port -c /etc/snmp/centreon_traps/*.conf $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/"; - $self->{logger}->writeLogDebug($cmd); - $stdout = `$cmd`; - if (defined($stdout) && $stdout){ - $self->{logger}->writeLogInfo("Result : $stdout"); - } - } } } } @@ -806,9 +785,9 @@ sub getInfos($) { } ################################ -## Restart SNMPTT Daemon +## Reload CentreonTrapd Daemon # -sub restartSNMPTT($) { +sub reloadCentreonTrapd($) { my $self = shift; my $id = $_[0]; my $stdout = ""; @@ -819,20 +798,20 @@ sub restartSNMPTT($) { my $port = checkSSHPort($ns_server->{'ssh_port'}); if (defined($ns_server->{'ns_ip_address'}) && $ns_server->{'ns_ip_address'} - && defined($ns_server->{'init_script_snmptt'}) && $ns_server->{'init_script_snmptt'} ne "") { + && defined($ns_server->{'init_script_centreontrapd'}) && $ns_server->{'init_script_centreontrapd'} ne "") { # Launch command if (defined($ns_server->{'localhost'}) && $ns_server->{'localhost'}) { - $cmd = "$self->{sudo} ".$ns_server->{'init_script_snmptt'}." restart"; + $cmd = "$self->{sudo} ".$ns_server->{'init_script_centreontrapd'}." restart"; $self->{logger}->writeLogDebug($cmd); $stdout = `$cmd`; } else { - $cmd = "$self->{ssh} -p $port ". $ns_server->{'ns_ip_address'} ." $self->{sudo} ".$ns_server->{'init_script_snmptt'}." restart"; + $cmd = "$self->{ssh} -p $port ". $ns_server->{'ns_ip_address'} ." $self->{sudo} ".$ns_server->{'init_script_centreontrapd'}." reload"; $self->{logger}->writeLogDebug($cmd); $stdout = `$cmd`; } - $self->{logger}->writeLogInfo("Restart SNMPTT on poller $id ($ns_server->{'ns_ip_address'})"); + $self->{logger}->writeLogInfo("Reload CentreonTrapd on poller $id ($ns_server->{'ns_ip_address'})"); } else { - $self->{logger}->writeLogError("Cannot restart SNMPTT for poller $id"); + $self->{logger}->writeLogError("Cannot reload CentreonTrapd for poller $id"); } } @@ -863,8 +842,8 @@ sub parseRequest($){ $self->testConfig($1); } elsif ($action =~ /^SYNCTRAP\:([0-9]*)/){ $self->syncTraps($1); - } elsif ($action =~ /^RESTARTSNMPTT\:([0-9]*)/){ - $self->restartSNMPTT($1); + } elsif ($action =~ /^RELOADCENTREONTRAPD\:([0-9]*)/){ + $self->reloadCentreonTrapd($1); } elsif ($action =~ /^SYNCARCHIVES\:([0-9]*)/){ $self->syncArchives($1); } elsif ($action =~ /^EXTERNALCMD\:([0-9]*)\:(.*)/){ From ad82286896c061a90c3164eeef8b1482dc9b41e8 Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Mon, 8 Jul 2013 16:42:47 +0200 Subject: [PATCH 079/458] refs #4504; +timeout on ssh --- centreon/lib/perl/centreon/script/centcore.pm | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index bf6a93397d2..623d6f9ed35 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -346,7 +346,15 @@ sub sendExternalCommand($$){ } else { $self->{logger}->writeLogInfo("External command : ".$server_info->{'ns_ip_address'}." ($id) : \"".$cmd."\""); my $cmd = "$self->{ssh} -q ". $server_info->{'ns_ip_address'} ." -p $port '$self->{echo} \"".$cmd."\" >> ".$command_file."'\n"; - $stdout = `$cmd`; + eval { + local $SIG{ALRM} = sub { die "alarm\n" }; + alarm $timeout; + $stdout = `$cmd`; + alarm 0; + }; + if ($@) { + writeLogFile("Could not write into pipe file ".$command_file." on poller ".$server_i + } } if (defined($stdout) && $stdout){ From 20a3d0f236ab63b7b7f4dd5b97b0458c7d896a67 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 9 Jul 2013 14:19:02 +0200 Subject: [PATCH 080/458] Fix centcore --- centreon/lib/perl/centreon/script/centcore.pm | 18 ++++++++++-------- .../lib/perl/centreon/script/centstorage.pm | 1 - 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index 623d6f9ed35..325df4e0331 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -28,7 +28,8 @@ sub new { $self->{rsync} = "rsync"; $self->{rsyncWT} = $self->{rsync}; $self->{sudo} = "sudo"; - $self->{timeout} = 5; + $self->{timeout} = 5; + $self->{cmd_timeout} = 5; $self->{ssh} .= " -o ConnectTimeout=$self->{timeout} -o StrictHostKeyChecking=yes -o PreferredAuthentications=publickey -o ServerAliveInterval=10 -o ServerAliveCountMax=3 -o Compression=yes "; $self->{rsync} .= " --timeout=$self->{timeout} "; @@ -53,6 +54,8 @@ sub new { sub init { my $self = shift; + $self->SUPER::init(); + $self->{cmdFile} = $self->{centreon_config}->{VarLib} . "/centcore.cmd"; $self->{cmdDir} = $self->{centreon_config}->{VarLib} . "/centcore/"; $self->{centreonDir} = $self->{centreon_config}->{CentreonDir}; @@ -132,7 +135,7 @@ sub reload { $self->{centreon_config}->{db_user} ne $self->{centreon_dbc}->user() || $self->{centreon_config}->{db_passwd} ne $self->{centreon_dbc}->password() || $self->{centreon_config}->{db_port} ne $self->{centreon_dbc}->port()) { - $self->{logger}->writeLogInfo("Database config had been modified") + $self->{logger}->writeLogInfo("Database config had been modified"); $self->{centreon_dbc}->disconnect(); $self->{centreon_dbc}->db($self->{centreon_config}->{centreon_db}); $self->{centreon_dbc}->host($self->{centreon_config}->{db_host}); @@ -216,12 +219,12 @@ sub getBrokerStats($) { my $stdout; eval { local $SIG{ALRM} = sub { die "alarm\n" }; - alarm $timeout; - $stdout = `$ssh -q $server_info->{'ns_ip_address'} -p $port 'cat \"$data->{'config_value'}" > $statPipe'`; + alarm $self->{cmd_timeout}; + $stdout = `$self->{ssh} -q $server_info->{'ns_ip_address'} -p $port 'cat \"$data->{'config_value'}" > $statPipe'`; alarm 0; }; if ($@) { - $self->{logger}->writeLogError("Could not read pipe ".$data->{'config_value'}." on poller ".$server_info->{'ns_ip_address'}."\n"); + $self->{logger}->writeLogError("Could not read pipe ".$data->{'config_value'}." on poller ".$server_info->{'ns_ip_address'}); } if (defined($stdout) && $stdout) { $self->{logger}->writeLogInfo("Result : $stdout"); @@ -348,12 +351,12 @@ sub sendExternalCommand($$){ my $cmd = "$self->{ssh} -q ". $server_info->{'ns_ip_address'} ." -p $port '$self->{echo} \"".$cmd."\" >> ".$command_file."'\n"; eval { local $SIG{ALRM} = sub { die "alarm\n" }; - alarm $timeout; + alarm $self->{cmd_timeout}; $stdout = `$cmd`; alarm 0; }; if ($@) { - writeLogFile("Could not write into pipe file ".$command_file." on poller ".$server_i + $self->{logger}->writeLogError("Could not write into pipe file ".$command_file." on poller ".$id); } } @@ -920,7 +923,6 @@ sub run { my $self = shift; $self->SUPER::run(); - $self->init(); $self->{logger}->redirect_output(); $self->{logger}->writeLogInfo("Starting centcore engine..."); diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index ad4a9b6f3d4..a9650bebe85 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -13,7 +13,6 @@ use centreon::centstorage::CentstorageLib; use centreon::centstorage::CentstoragePool; use centreon::centstorage::CentstoragePerfdataFile; use centreon::centstorage::CentstorageAction; -use centreon::centstorage::CentstorageAction; use centreon::centstorage::CentstorageRRD; use base qw(centreon::script); From e2b546bb071650b00781375893acdb9e4e156930 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 10 Jul 2013 11:31:22 +0200 Subject: [PATCH 081/458] Ref #4539 --- .../lib/perl/centreon/script/centreontrapd.pm | 42 +++++++++++++++++-- centreon/lib/perl/centreon/trapd/Log.pm | 5 +++ centreon/lib/perl/centreon/trapd/lib.pm | 10 ++++- 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 8f07e15d0cf..f7ade140e23 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -102,6 +102,9 @@ sub new { # $self->{traps_global_output} = undef; $self->{traps_global_status} = undef; + $self->{traps_global_severity_id} = undef; + $self->{traps_global_severity_name} = undef; + $self->{traps_global_severity_level} = undef; # For policy_trap = 1 (temp). To avoid doing the same thing twice # ID oid ===> Host ID ===> Service ID @@ -362,6 +365,10 @@ sub do_exec { my $matching_result = 0; $self->{traps_global_status} = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_status}; + $self->{traps_global_severity_id} = $self->{ref_oids}->{ $self->{current_trap_id} }->{sc_id}; + $self->{traps_global_severity_name} = $self->{ref_oids}->{ $self->{current_trap_id} }->{sc_name}; + $self->{traps_global_severity_level} = $self->{ref_oids}->{ $self->{current_trap_id} }->{level}; + # PREEXEC commands $self->execute_preexec(); @@ -521,13 +528,13 @@ sub forceCheck { ####################################### ## Submit result via external command # -sub submitResult { + +sub submitResult_do { my $self = shift; + my $str = $_[0]; my $datetime = time(); - - my $str = "PROCESS_SERVICE_CHECK_RESULT;$self->{current_hostname};$self->{current_service_desc};" . $self->{traps_global_status} . ";" . $self->{traps_global_output}; - my $submit; + if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { $str =~ s/"/\\"/g; $submit = "/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{cmdFile}; @@ -545,6 +552,22 @@ sub submitResult { } } +sub submitResult { + my $self = shift; + + my $str = "PROCESS_SERVICE_CHECK_RESULT;$self->{current_hostname};$self->{current_service_desc};" . $self->{traps_global_status} . ";" . $self->{traps_global_output}; + $self->submitResult_do($str); + + ##### + # Severity + ##### + return if (!defined($self->{traps_global_severity_id}) || $self->{traps_global_severity_id} eq ''); + $str = "CHANGE_CUSTOM_SVC_VAR;$self->{current_hostname};$self->{current_service_desc};_CRITICALITY_ID;" . $self->{traps_global_severity_id}; + $self->submitResult_do($str); + $str = "CHANGE_CUSTOM_SVC_VAR;$self->{current_hostname};$self->{current_service_desc};_CRITICALITY_LEVEL;" . $self->{traps_global_severity_level}; + $self->submitResult_do($str); +} + sub execute_preexec { my $self = shift; @@ -636,6 +659,8 @@ sub substitute_centreon_var { $str =~ s/\@TRAPOUTPUT\@/$self->{traps_global_output}/g; $str =~ s/\@OUTPUT\@/$self->{traps_global_output}/g; $str =~ s/\@STATUS\@/$self->{traps_global_status}/g; + $str =~ s/\@SEVERITYNAME\@/$self->{traps_global_severity_name}/g; + $str =~ s/\@SEVERITYLEVEL\@/$self->{traps_global_severity_level}/g; $str =~ s/\@TIME\@/$self->{trap_date_time_epoch}/g; $str =~ s/\@POLLERID\@/$self->{current_server_id}/g; $str =~ s/\@POLLERADDRESS\@/$self->{current_server_ip_address}/g; @@ -675,6 +700,9 @@ sub checkMatchingRules { my $tmoString = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_string}; my $regexp = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_regexp}; my $tmoStatus = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_status}; + my $severity_level = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{level}; + my $severity_name = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{sc_name}; + my $severity_id = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{sc_id}; $self->{logger}->writeLogDebug("[$tmoString][$regexp] => $tmoStatus"); @@ -708,8 +736,14 @@ sub checkMatchingRules { # Integrate OID Matching if (defined($tmoString) && $tmoString =~ m/$regexp/g) { $self->{traps_global_status} = $tmoStatus; + $self->{traps_global_severity_name} = $severity_name; + $self->{traps_global_severity_level} = $severity_level; + $self->{traps_global_severity_id} = $severity_id; $self->{logger}->writeLogInfo("Regexp: String:$tmoString => REGEXP:$regexp"); $self->{logger}->writeLogInfo("Status: $self->{traps_global_status} ($tmoStatus)"); + $self->{logger}->writeLogInfo("Severity id: $self->{traps_global_severity_id} ($severity_id)"); + $self->{logger}->writeLogInfo("Severity name: $self->{traps_global_severity_name} ($severity_name)"); + $self->{logger}->writeLogInfo("Severity level: $self->{traps_global_severity_level} ($severity_level)"); $matching_boolean = 1; last; } diff --git a/centreon/lib/perl/centreon/trapd/Log.pm b/centreon/lib/perl/centreon/trapd/Log.pm index 2c8ab5c66dd..e1a293cf710 100644 --- a/centreon/lib/perl/centreon/trapd/Log.pm +++ b/centreon/lib/perl/centreon/trapd/Log.pm @@ -123,6 +123,11 @@ sub compute_request { } } +#### +# Protocol description: +# First: ID_UNIQUE:0:num_args:value +# Args: ID_UNIQUE:1:arg_pos:value + sub main { my $self = shift; my ($dbcentstorage, $pipe_read, $config_file, $centreontrapd_config) = @_; diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index b7bfa36c6ff..d8001e2730f 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -99,14 +99,20 @@ sub get_oids { traps_oid, traps_name, traps_advanced_treatment, traps_advanced_treatment_default, traps_execution_command_enable, traps_submit_result_enable, traps_status, traps_timeout, traps_exec_interval, traps_exec_interval_type, traps_routing_mode, traps_routing_value - FROM traps LEFT JOIN traps_vendor ON (traps_vendor.id = traps.manufacturer_id) WHERE traps_oid = " . $cdb->quote($oid)); + service_categories.level, service_categories.sc_name, service_categories.sc_id + FROM traps + LEFT JOIN traps_vendor ON (traps_vendor.id = traps.manufacturer_id) + LEFT JOIN service_categories ON (service_categories.sc_id = traps.severity_id) + WHERE traps_oid = " . $cdb->quote($oid)); return -1 if ($dstatus == -1); $ref_result = $sth->fetchall_hashref('traps_id'); foreach (keys %$ref_result) { # Get Matching Status Rules if (defined($ref_result->{$_}->{traps_advanced_treatment}) && $ref_result->{$_}->{traps_advanced_treatment} == 1) { - ($dstatus, $sth) = $cdb->query("SELECT * FROM traps_matching_properties WHERE trap_id = " . $_ . " ORDER BY tmo_id ASC"); + ($dstatus, $sth) = $cdb->query("SELECT * FROM traps_matching_properties + LEFT JOIN service_categories ON (service_categories.sc_id = traps_matching_properties.severity_id) + WHERE trap_id = " . $_ . " ORDER BY tmo_id ASC"); return -1 if ($dstatus == -1); $ref_result->{$_}->{traps_matching_properties} = $sth->fetchall_hashref("tmo_id"); } From 60eae8138839b1b3c05a3ffab5e10dfdfc96e947 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 10 Jul 2013 14:25:24 +0200 Subject: [PATCH 082/458] Fix centcore bug with localhost --- centreon/lib/perl/centreon/script/centcore.pm | 2 +- .../lib/perl/centreon/script/centreontrapd.pm | 16 ++++++++-------- centreon/lib/perl/centreon/trapd/lib.pm | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index 325df4e0331..fb8517b29ab 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -341,7 +341,7 @@ sub sendExternalCommand($$){ my $result = waitPipe($command_file); if ($result == 0) { $self->{logger}->writeLogInfo("External command on Central Server: ($id) : \"".$cmd."\""); - my $cmd = "self->{echo} \"".$cmd."\" >> ".$command_file."\n"; + my $cmd = "$self->{echo} \"".$cmd."\" >> ".$command_file; $stdout = `$cmd`; } else { $self->{logger}->writeLogError("Cannot write external command on central server : \"".$cmd."\""); diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index f7ade140e23..292b4772aa5 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -120,7 +120,7 @@ sub new { $self->{id_logdb} = 0; # redefine to avoid out when we try modules - $SIG{__DIE__} = undef; + $SIG{__DIE__} = 'IGNORE'; return $self; } @@ -290,7 +290,7 @@ sub reload { centreon::trapd::lib::manage_params_conf($self->{centreontrapd_config}->{date_format}, $self->{centreontrapd_config}->{time_format}); # redefine to avoid out when we try modules - $SIG{__DIE__} = undef; + $SIG{__DIE__} = 'IGNORE'; centreon::trapd::lib::init_modules(logger => $self->{logger}, config => $self->{centreontrapd_config}, htmlentities => \$self->{htmlentities}); $self->set_signal_handlers; @@ -312,8 +312,8 @@ sub create_logdb_child { my $current_pid = fork(); if (!$current_pid) { # Unhandle die in child - $SIG{CHLD} = undef; - $SIG{__DIE__} = undef; + $SIG{CHLD} = 'IGNORE'; + $SIG{__DIE__} = 'IGNORE'; $self->{cdb}->set_inactive_destroy(); close $self->{logdb_pipes}{'writer'}; @@ -452,8 +452,8 @@ sub manage_exec { my $current_pid = fork(); if (!$current_pid) { # Unhandle die in child - $SIG{CHLD} = undef; - $SIG{__DIE__} = undef; + $SIG{CHLD} = 'IGNORE'; + $SIG{__DIE__} = 'IGNORE'; $self->{cdb}->set_inactive_destroy(); eval { my $alarm_timeout = $self->{centreontrapd_config}->{cmd_timeout}; @@ -843,8 +843,8 @@ sub getTrapsInfos { #### If none, we stop #### my $size = keys %{$self->{ref_services}}; if ($size < 1) { - $self->{logger}->writeLogDebug("Trap without service associated. Skipping..."); - return 1; + $self->{logger}->writeLogDebug("Trap without service associated for host " . $self->{current_hostname} . ". Skipping..."); + next; } #### Check if macro $_HOST*$ needed diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index d8001e2730f..d65c6c3899e 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -98,7 +98,7 @@ sub get_oids { my ($dstatus, $sth) = $cdb->query("SELECT name, traps_log, traps_execution_command, traps_reschedule_svc_enable, traps_id, traps_args, traps_oid, traps_name, traps_advanced_treatment, traps_advanced_treatment_default, traps_execution_command_enable, traps_submit_result_enable, traps_status, traps_timeout, traps_exec_interval, traps_exec_interval_type, - traps_routing_mode, traps_routing_value + traps_routing_mode, traps_routing_value, service_categories.level, service_categories.sc_name, service_categories.sc_id FROM traps LEFT JOIN traps_vendor ON (traps_vendor.id = traps.manufacturer_id) From 713ea3a868021c2ca67fadbdb2683883c5e46cf4 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 10 Jul 2013 18:41:22 +0200 Subject: [PATCH 083/458] New system to handle sub process --- centreon/lib/perl/centreon/common/misc.pm | 85 +++++++ centreon/lib/perl/centreon/script/centcore.pm | 224 ++++++++++++------ .../lib/perl/centreon/script/centreontrapd.pm | 89 ++++--- 3 files changed, 280 insertions(+), 118 deletions(-) diff --git a/centreon/lib/perl/centreon/common/misc.pm b/centreon/lib/perl/centreon/common/misc.pm index 901b3b11c93..1b50e91f8be 100644 --- a/centreon/lib/perl/centreon/common/misc.pm +++ b/centreon/lib/perl/centreon/common/misc.pm @@ -1,6 +1,10 @@ package centreon::common::misc; + +use strict; +use warnings; use vars qw($centreon_config); +use POSIX ":sys_wait_h"; my $read_size = 1*1024*1024*10; # 10Mo @@ -126,4 +130,85 @@ sub get_line_pipe { return -1; } +sub plop { + my $child_pid; + + while (($child_pid = waitpid(-1, &WNOHANG)) > 0) { + print "SIGCHLD received: $child_pid\n"; + } + print "SIGCHLD received: $child_pid\n"; + #print "LAAAAAAAAAAAAAAAAAA\n"; +} + +sub backtick { + my %arg = ( + command => undef, + logger => undef, + timeout => 30, + wait_exit => 0, + @_, + ); + my @output; + my $pid; + my $return_code; + + my $sig_do; + if ($arg{wait_exit} == 0) { + $sig_do = 'IGNORE'; + $return_code = undef; + } else { + $sig_do = 'DEFAULT'; + } + local $SIG{CHLD} = $sig_do; + if (!defined($pid = open( KID, "-|" ))) { + $arg{logger}->writeLogError("Cant fork: $!"); + return -1; + } + + if ($pid) { + + + eval { + local $SIG{ALRM} = sub { die "Timeout by signal ALARM\n"; }; + alarm( $arg{timeout} ); + while () { + chomp; + push @output, $_; + } + + alarm(0); + }; + if ($@) { + $arg{logger}->writeLogInfo($@); + + $arg{logger}->writeLogInfo("Killing child process [$pid] ..."); + if ($pid != -1) { + kill -9, $pid; + } + $arg{logger}->writeLogInfo("Killed"); + + alarm(0); + close KID; + return (-1, join("\n", @output), -1); + } else { + if ($arg{wait_exit} == 1) { + # We're waiting the exit code + waitpid($pid, 0); + $return_code = $?; + } + close KID; + } + } else { + # child + # set the child process to be a group leader, so that + # kill -9 will kill it and all its descendents + setpgrp( 0, 0 ); + + exec($arg{command}); + exit(0); + } + + return (0, join("\n", @output), $return_code); +} + 1; diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index fb8517b29ab..afe8a4cf7ee 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -6,6 +6,7 @@ use File::Copy; use File::Path qw(mkpath); use centreon::script; use centreon::common::db; +use centreon::common::misc; use base qw(centreon::script); @@ -197,6 +198,7 @@ sub getBrokerStats($) { my $statPipe = "/tmp/.centreon-broker-stats.dat"; my $destFile = $self->{centreon_config}->{VarLib} . "/broker-stats"; my $server_info; + my ($lerror, $stdout, $cmd); # Check Cache directory if (!-d $destFile) { @@ -216,23 +218,26 @@ sub getBrokerStats($) { $port = checkSSHPort($server_info->{'ssh_port'}); # Copy the stat file into a buffer - my $stdout; - eval { - local $SIG{ALRM} = sub { die "alarm\n" }; - alarm $self->{cmd_timeout}; - $stdout = `$self->{ssh} -q $server_info->{'ns_ip_address'} -p $port 'cat \"$data->{'config_value'}" > $statPipe'`; - alarm 0; - }; - if ($@) { + + $cmd = "$self->{ssh} -q $server_info->{'ns_ip_address'} -p $port 'cat \"$data->{config_value}\" > $statPipe'"; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => $self->{cmd_timeout} + ); + if ($lerror == -1) { $self->{logger}->writeLogError("Could not read pipe ".$data->{'config_value'}." on poller ".$server_info->{'ns_ip_address'}); - } + } if (defined($stdout) && $stdout) { $self->{logger}->writeLogInfo("Result : $stdout"); } + $cmd = "$self->{scp} -P $port $server_info->{'ns_ip_address'}:$statPipe $destFile/broker-stats-$poller_id.dat >> /dev/null"; # Get the stats file - $stdout = `$self->{scp} -P $port $server_info->{'ns_ip_address'}:$statPipe $destFile/broker-stats-$poller_id.dat >> /dev/null`; - if (defined($stdout) && $stdout){ + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => $self->{cmd_timeout} + ); + if (defined($stdout) && $stdout) { $self->{logger}->writeLogInfo("Result : $stdout"); } } @@ -325,7 +330,7 @@ sub sendExternalCommand($$){ my $self = shift; # Init Parameters my ($id, $cmd) = @_; - my $stdout; + my ($lerror, $stdout, $cmd2); # Get server informations my $server_info = $self->getServerConfig($id); @@ -341,21 +346,26 @@ sub sendExternalCommand($$){ my $result = waitPipe($command_file); if ($result == 0) { $self->{logger}->writeLogInfo("External command on Central Server: ($id) : \"".$cmd."\""); - my $cmd = "$self->{echo} \"".$cmd."\" >> ".$command_file; - $stdout = `$cmd`; + + $cmd2 = "$self->{echo} \"".$cmd."\" >> ".$command_file; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd2, + logger => $self->{logger}, + timeout => $self->{cmd_timeout} + ); + if ($lerror == -1) { + $self->{logger}->writeLogError("Could not write into pipe file ".$command_file." on poller ".$id); + } } else { $self->{logger}->writeLogError("Cannot write external command on central server : \"".$cmd."\""); } } else { $self->{logger}->writeLogInfo("External command : ".$server_info->{'ns_ip_address'}." ($id) : \"".$cmd."\""); - my $cmd = "$self->{ssh} -q ". $server_info->{'ns_ip_address'} ." -p $port '$self->{echo} \"".$cmd."\" >> ".$command_file."'\n"; - eval { - local $SIG{ALRM} = sub { die "alarm\n" }; - alarm $self->{cmd_timeout}; - $stdout = `$cmd`; - alarm 0; - }; - if ($@) { + $cmd2 = "$self->{ssh} -q ". $server_info->{'ns_ip_address'} ." -p $port '$self->{echo} \"".$cmd."\" >> ".$command_file."'"; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd2, + logger => $self->{logger}, + timeout => $self->{cmd_timeout} + ); + if ($lerror == -1) { $self->{logger}->writeLogError("Could not write into pipe file ".$command_file." on poller ".$id); } } @@ -393,6 +403,7 @@ sub GetPerfData($){ my $self = shift; # init Values my ($id) = @_; + my ($lerror, $stdout, $cmd); # Get Server Infos my $server_info = $self->getServerConfig($id); @@ -428,16 +439,24 @@ sub GetPerfData($){ } # Rename perfdata file - my $cmd = "$self->{ssh} ". $server_info->{'ns_ip_address'} ." -p $port '".$move_cmd."'"; + $cmd = "$self->{ssh} ". $server_info->{'ns_ip_address'} ." -p $port '".$move_cmd."'"; $self->{logger}->writeLogDebug($cmd); - my $stdout = `$cmd`; + + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 120 + ); if (defined($stdout) && $stdout){ $self->{logger}->writeLogInfo("Result : $stdout"); } # Get Perfdata File $self->{logger}->writeLogDebug("$self->{scp} -P $port $distantconnexion:$distantperffile_buffer $localtmpperffile"); - $stdout = `$self->{scp} -P $port $distantconnexion:$distantperffile_buffer $localtmpperffile 2>> /dev/null`; + $cmd = "$self->{scp} -P $port $distantconnexion:$distantperffile_buffer $localtmpperffile 2>> /dev/null"; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 300 + ); if (defined($stdout) && $stdout){ $self->{logger}->writeLogInfo("Result : $stdout"); } @@ -446,7 +465,12 @@ sub GetPerfData($){ if (-f $localtmpperffile){ # Concat poller perfdata to central perfdata. $self->{logger}->writeLogDebug("cat $localtmpperffile >> $localperffile"); - `cat $localtmpperffile >> $localperffile`; + $cmd = "cat $localtmpperffile >> $localperffile"; + + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 300 + ); # Remove old file if (!unlink($localtmpperffile)) { @@ -465,17 +489,25 @@ sub checkRotation($$$$$) { my $remoteConnection = $_[2]; my $localLogFile = $_[3]; my $port = $_[4]; - + my ($lerror, $stdout, $cmd); + my $archivePath = $self->getNagiosConfigurationField($instanceId, 'log_archive_path'); my $getLastCmd = 'echo "$(find '.$archivePath.' -type f -exec stat -c "%Z:%n" {} \; | sort | tail -1)"'; - my $check_cmd = "$self->{ssh} -p $port -q $remoteConnection '".$getLastCmd."'"; - my $result = `$check_cmd`; - $result =~ /(\d+):(.+)/; + $cmd = "$self->{ssh} -p $port -q $remoteConnection '".$getLastCmd."'"; + + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 120 + ); my $updateTime = $1; my $fileName = $2; if (defined($updateTime) && defined($lastUpdate) && $updateTime > $lastUpdate) { - my $cmd = "$self->{scp} -P $port $remoteConnection:$fileName $localLogFile.rotate > /dev/null"; - `$cmd`; + $cmd = "$self->{scp} -P $port $remoteConnection:$fileName $localLogFile.rotate > /dev/null"; + + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 120 + ); $self->{logger}->writeLogInfo("Info: copied rotated file for instance $instanceId"); } } @@ -489,6 +521,7 @@ sub GetLogFile($) { # Init values my $id = $_[0]; my $last_access; + my ($lerror, $stdout, $cmd); # Get Server informations my $server_info = $self->getServerConfig($id); @@ -519,22 +552,30 @@ sub GetLogFile($) { my $flag; if (-f $localDir.".nagios.log.flag") { # Cet old flag - my $cmd = $localDir.".nagios.log.flag"; - my $value = `cat $cmd`; - $value =~ s/\n//g; + $cmd = "cat " . $localDir . ".nagios.log.flag"; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 120 + ); + $stdout =~ s/\n//g; - $self->checkRotation($id, $value, $distantconnexion, $locallogfile, $port); + $self->checkRotation($id, $stdout, $distantconnexion, $locallogfile, $port); # Check update - my $check_cmd = "$self->{ssh} -p $port -q $distantconnexion 'stat -c \'STAT_RESULT=%Y\' $distantlogfile'"; - $self->{logger}->writeLogDebug("Get Log Files - stat: $check_cmd"); - $last_access = `$check_cmd`; + $cmd = "$self->{ssh} -p $port -q $distantconnexion 'stat -c \'STAT_RESULT=%Y\' $distantlogfile'"; + $self->{logger}->writeLogDebug("Get Log Files - stat: $cmd"); + + ($lerror, my $last_access) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 120 + ); + $last_access =~ /STAT_RESULT=(\d+)/; $last_access = $1; $self->{logger}->writeLogDebug("Get Log File - stat: Finished"); # Check buffer - if ($value !~ $last_access) { + if ($stdout !~ $last_access) { $flag = 1; } else { $flag = 0; @@ -545,16 +586,23 @@ sub GetLogFile($) { if ($flag == 1) { # Get file with rsync - my $cmd = "$self->{scp} -P $port $distantconnexion:$distantlogfile $locallogfile > /dev/null"; - `$cmd`; + $cmd = "$self->{scp} -P $port $distantconnexion:$distantlogfile $locallogfile > /dev/null"; + ($lerror, $stdout, my $exit_code) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 300, + wait_exit => 1 + ); $self->{logger}->writeLogDebug($cmd); - if ($? ne 0) { + if (($exit_code >> 8) != 0) { $self->{logger}->writeLogError("Cannot get log file or log file doesn't exists on poller $id"); } } # Update or create time buffer - my $buffer_cmd = "echo '$last_access' > ".$localDir.".nagios.log.flag"; - `$buffer_cmd`; + $cmd = "echo '$last_access' > ".$localDir.".nagios.log.flag"; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => $self->{cmd_timeout} + ); } } else { $self->{logger}->writeLogError("Unable to create $localDir. Can get nagios log file for poller $id"); @@ -568,6 +616,7 @@ sub sendConfigFile($){ my $self = shift; # Init Values my $id = $_[0]; + my ($lerror, $stdout, $cmd); my $cfg_dir = $self->getNagiosConfigurationField($id, "cfg_dir"); my $server_info = $self->getServerConfig($id); @@ -583,8 +632,13 @@ sub sendConfigFile($){ # Send data with SCP $self->{logger}->writeLogInfo("Start: Send config files on poller $id"); - my $cmd = "$self->{scp} -P $port $origin $dest 2>&1"; - my $stdout = `$cmd`; + $cmd = "$self->{scp} -P $port $origin $dest 2>&1"; + + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 300 + ); + $self->{logger}->writeLogInfo("Result : $stdout"); $self->{logger}->writeLogInfo("End: Send config files on poller $id"); @@ -606,11 +660,17 @@ sub sendConfigFile($){ $origin = $self->{centreonDir} . "/filesGeneration/broker/".$id."/*.xml"; $dest = $server_info->{'ns_ip_address'}.":$cfg_dir"; $cmd = "$self->{scp} -P $port $origin $dest 2>&1"; - my $stdout = `$cmd`; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 300 + ); $self->{logger}->writeLogInfo("Result : $stdout"); } else { - my $cmd = "cp $origin $cfg_dir 2>&1"; - my $stdout = `$cmd`; + $cmd = "cp $origin $cfg_dir 2>&1"; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 60 + ); $self->{logger}->writeLogInfo("Result : $stdout"); } $self->{logger}->writeLogDebug("End: Send Centreon Broker config files on poller $id"); @@ -629,7 +689,7 @@ sub initEngine($$){ my $self = shift; my $id = $_[0]; my $options = $_[1]; - my ($cmd, $stdout); + my ($lerror, $cmd, $stdout); # Get configuration my $conf = $self->getServerConfig($id); @@ -644,7 +704,10 @@ sub initEngine($$){ if (defined($conf->{'ns_ip_address'}) && $conf->{'ns_ip_address'}) { # Launch command $cmd = "$self->{ssh} -p $port ". $conf->{'ns_ip_address'} ." $self->{sudo} ".$conf->{'init_script'}." ".$options; - $stdout = `$cmd`; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 120 + ); } else { $self->{logger}->writeLogError("Cannot $options Engine for poller $id"); } @@ -665,7 +728,7 @@ sub initEngine($$){ sub syncTraps($) { my $self = shift; my $id = $_[0]; - my $stdout; + my ($lerror, $stdout, $cmd); if ($id != 0) { # Get configuration @@ -673,9 +736,13 @@ sub syncTraps($) { my $port = checkSSHPort($ns_server->{'ssh_port'}); if ($id != 0 && $ns_server->{'localhost'} == 0) { - my $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/$id/centreontrapd.sdb $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/ 2>&1"; + $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/$id/centreontrapd.sdb $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/ 2>&1"; $self->{logger}->writeLogDebug($cmd); - $stdout = `$cmd`; + + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 300 + ); if (defined($stdout) && $stdout){ $self->{logger}->writeLogInfo("Result : $stdout"); } @@ -690,9 +757,12 @@ sub syncTraps($) { my $port = checkSSHPort($ns_server->{'ssh_port'}); if ($id == 0) { - my $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/$id/centreontrapd.sdb $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/ 2>&1"; + $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/$id/centreontrapd.sdb $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/ 2>&1"; $self->{logger}->writeLogDebug($cmd); - $stdout = `$cmd`; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 300 + ); if (defined($stdout) && $stdout){ $self->{logger}->writeLogInfo("Result : $stdout"); } @@ -707,13 +777,17 @@ sub syncTraps($) { sub testConfig($) { my $self = shift; my $id = $_[0]; + my ($lerror, $stdout, $cmd); my $cfg_dir = $self->getNagiosConfigurationField($id, "cfg_dir"); my $data = $self->getServerConfig($id); my $port = checkSSHPort($data->{'ssh_port'}); my $distantconnexion = $data->{'ns_ip_address'}; - my $cmd = "$self->{ssh} -p ".$port." $distantconnexion $self->{sudo} ".$data->{'nagios_bin'}." -v $cfg_dir/nagios.cfg"; - my $stdout = `$cmd`; + $cmd = "$self->{ssh} -p ".$port." $distantconnexion $self->{sudo} ".$data->{'nagios_bin'}." -v $cfg_dir/nagios.cfg"; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 60 + ); $self->{logger}->writeLogInfo("Test Config Result: $stdout"); } @@ -724,6 +798,7 @@ sub testConfig($) { sub syncArchives($) { my $self = shift; my $id = $_[0]; + my ($lerror, $stdout, $cmd); # Get configuration my $ns_server = $self->getServerConfig($id); @@ -744,9 +819,12 @@ sub syncArchives($) { } my $data = $sth->fetchrow_hashref(); # Archive Sync - my $cmd = "$self->{rsyncWT} --port=$port -c ". $ns_server->{'ns_ip_address'}. ":".$data->{'log_archive_path'}."/*.log $self->{centreon_config}->{VarLib}/log/".$ns_server->{'id'}."/archives/"; + $cmd = "$self->{rsyncWT} --port=$port -c ". $ns_server->{'ns_ip_address'}. ":".$data->{'log_archive_path'}."/*.log $self->{centreon_config}->{VarLib}/log/".$ns_server->{'id'}."/archives/ 2>> /dev/null"; $self->{logger}->writeLogDebug($cmd); - `$self->{rsyncWT} --port=$port -c $ns_server->{'ns_ip_address'}:$data->{'log_archive_path'}/*.log $self->{centreon_config}->{VarLib}/log/$ns_server->{'id'}/archives/ 2>> /dev/null`; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 300 + ); } else { # synchronize Archives for all pollers my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `id` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); @@ -766,6 +844,7 @@ sub syncArchives($) { sub getInfos($) { my $self = shift; my $id = $_[0]; + my ($lerror, $stdout, $cmd); # Get configuration my $ns_server = $self->getServerConfig($id); @@ -773,10 +852,12 @@ sub getInfos($) { if (defined($ns_server->{'ns_ip_address'}) && $ns_server->{'ns_ip_address'}) { # Launch command - my $cmd = "$self->{ssh} -p $port ". $ns_server->{'ns_ip_address'} ." ".$ns_server->{'nagios_bin'}.""; + $cmd = "$self->{ssh} -p $port ". $ns_server->{'ns_ip_address'} ." ".$ns_server->{'nagios_bin'}; $self->{logger}->writeLogDebug($cmd); - my $stdout = `$cmd`; - + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 60 + ); my @tab = split("\n", $stdout); foreach my $str (@tab) { if ($str =~ m/(Nagios) Core ([\.0-9]*[a-zA-Z0-9\-\.]+)/) { @@ -801,8 +882,7 @@ sub getInfos($) { sub reloadCentreonTrapd($) { my $self = shift; my $id = $_[0]; - my $stdout = ""; - my $cmd = ""; + my ($lerror, $stdout, $cmd); # Get configuration my $ns_server = $self->getServerConfig($id); @@ -814,11 +894,17 @@ sub reloadCentreonTrapd($) { if (defined($ns_server->{'localhost'}) && $ns_server->{'localhost'}) { $cmd = "$self->{sudo} ".$ns_server->{'init_script_centreontrapd'}." restart"; $self->{logger}->writeLogDebug($cmd); - $stdout = `$cmd`; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 120 + ); } else { $cmd = "$self->{ssh} -p $port ". $ns_server->{'ns_ip_address'} ." $self->{sudo} ".$ns_server->{'init_script_centreontrapd'}." reload"; $self->{logger}->writeLogDebug($cmd); - $stdout = `$cmd`; + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 60 + ); } $self->{logger}->writeLogInfo("Reload CentreonTrapd on poller $id ($ns_server->{'ns_ip_address'})"); } else { @@ -902,7 +988,7 @@ sub checkDebugFlag { } else { if ($self->{logger}->is_debug()) { $self->{logger}->set_default_severity(); - $self->{logger}->writeLogInfo("Disable Debug in Centcore"); + $self->{logger}->writeLogInfo("Disable Debug in Centcore. Set default severity"); } } return 0; diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 292b4772aa5..9bcb91c6c95 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -6,6 +6,7 @@ use warnings; use POSIX; use centreon::script; use centreon::common::db; +use centreon::common::misc; use centreon::trapd::lib; use centreon::trapd::Log; @@ -99,6 +100,8 @@ sub new { $self->{current_trap_log} = undef; $self->{current_vendor_name} = undef; + $self->{current_alarm_timeout} = undef; + # $self->{traps_global_output} = undef; $self->{traps_global_status} = undef; @@ -455,39 +458,13 @@ sub manage_exec { $SIG{CHLD} = 'IGNORE'; $SIG{__DIE__} = 'IGNORE'; $self->{cdb}->set_inactive_destroy(); - eval { - my $alarm_timeout = $self->{centreontrapd_config}->{cmd_timeout}; - if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_timeout})) { - $alarm_timeout = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_timeout}; - } - - local $SIG{ALRM} = sub { die "TIMEOUT"; }; - alarm($alarm_timeout); - $self->do_exec(); - alarm(0); - }; - if ($@) { - if ($self->{centreontrapd_config}->{log_trap_db} == 1 && $self->{current_trap_log} == 1) { - centreon::trapd::lib::send_logdb(pipe => $self->{logdb_pipes}{'writer'}, - id => $self->{id_logdb}, - cdb => $self->{cdb}, - trap_time => $self->{trap_date_time_epoch}, - timeout => 1, - host_name => ${$self->{var}}[0], - ip_address => $self->{current_ip}, - agent_host_name => $self->{agent_dns_name}, - agent_ip_address => ${$self->{var}}[4], - trap_oid => $self->{current_oid}, - trap_name => $self->{current_trap_name}, - vendor => $self->{current_vendor_name}, - severity => $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_status}, - output_message => $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_args}, - entvar => \@{$self->{entvar}}, - entvarname => \@{$self->{entvarname}}); - } - $self->{logger}->writeLogError("ERROR: Exec timeout"); - exit(0); + + $self->{current_alarm_timeout} = $self->{centreontrapd_config}->{cmd_timeout}; + if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_timeout}) && $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_timeout} != 0) { + $self->{current_alarm_timeout} = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_timeout}; } + $self->do_exec(); + exit(1); } @@ -516,11 +493,14 @@ sub forceCheck { $str =~ s/"/\\"/g; $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; } - my $stdout = `$submit`; - + + my ($lerror, $stdout) = centreon::common::misc::backtick(command => $submit, + logger => $self->{logger}, + timeout => $self->{current_alarm_timeout} + ); $self->{logger}->writeLogInfo("FORCE: Reschedule linked service"); $self->{logger}->writeLogInfo("FORCE: Launched command: $submit"); - if (defined($stdout)) { + if (defined($stdout) && $stdout ne "") { $self->{logger}->writeLogError("FORCE stdout: $stdout"); } } @@ -543,11 +523,14 @@ sub submitResult_do { $str =~ s/"/\\"/g; $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; } - my $stdout = `$submit`; + my ($lerror, $stdout) = centreon::common::misc::backtick(command => $submit, + logger => $self->{logger}, + timeout => $self->{current_alarm_timeout} + ); $self->{logger}->writeLogInfo("SUBMIT: Force service status via passive check update"); $self->{logger}->writeLogInfo("SUBMIT: Launched command: $submit"); - if (defined($stdout)) { + if (defined($stdout) && $stdout ne "") { $self->{logger}->writeLogError("SUBMIT RESULT stdout: $stdout"); } } @@ -562,9 +545,9 @@ sub submitResult { # Severity ##### return if (!defined($self->{traps_global_severity_id}) || $self->{traps_global_severity_id} eq ''); - $str = "CHANGE_CUSTOM_SVC_VAR;$self->{current_hostname};$self->{current_service_desc};_CRITICALITY_ID;" . $self->{traps_global_severity_id}; + $str = "CHANGE_CUSTOM_SVC_VAR;$self->{current_hostname};$self->{current_service_desc};CRITICALITY_ID;" . $self->{traps_global_severity_id}; $self->submitResult_do($str); - $str = "CHANGE_CUSTOM_SVC_VAR;$self->{current_hostname};$self->{current_service_desc};_CRITICALITY_LEVEL;" . $self->{traps_global_severity_level}; + $str = "CHANGE_CUSTOM_SVC_VAR;$self->{current_hostname};$self->{current_service_desc};CRITICALITY_LEVEL;" . $self->{traps_global_severity_level}; $self->submitResult_do($str); } @@ -576,16 +559,20 @@ sub execute_preexec { $tpe_string = $self->substitute_string($tpe_string); $tpe_string = $self->substitute_centreon_var($tpe_string); - my $output = `$tpe_string`; - if ($? == -1) { - $self->{logger}->writeLogError("EXEC: Execution error: $!"); - } elsif (($? >> 8) != 0) { - $self->{logger}->writeLogInfo("EXEC: Exit command: " . ($? >> 8)); + my ($lerror, $output, $exit_code) = centreon::common::misc::backtick(command => $tpe_string, + logger => $self->{logger}, + timeout => $self->{current_alarm_timeout}, + wait_exit => 1 + ); + if ($exit_code == -1) { + $self->{logger}->writeLogError("EXEC prexec: Execution error: $!"); + } elsif (($exit_code >> 8) != 0) { + $self->{logger}->writeLogInfo("EXEC preexec: Exit command: " . ($exit_code >> 8)); } if (defined($output)) { chomp $output; push @{$self->{preexec}}, $output; - $self->{logger}->writeLogInfo("EXEC: Output : $output"); + $self->{logger}->writeLogInfo("EXEC preexec: Output : $output"); } else { push @{$self->{preexec}}, ""; } @@ -784,11 +771,15 @@ sub executeCommand { $self->{logger}->writeLogInfo("EXEC: Launch specific command"); $self->{logger}->writeLogInfo("EXEC: Launched command: $traps_execution_command"); - my $output = `$traps_execution_command`; - if ($? == -1) { + my ($lerror, $output, $exit_code) = centreon::common::misc::backtick(command => $traps_execution_command, + logger => $self->{logger}, + timeout => $self->{current_alarm_timeout}, + wait_exit => 1 + ); + if ($exit_code == -1) { $self->{logger}->writeLogError("EXEC: Execution error: $!"); - } elsif (($? >> 8) != 0) { - $self->{logger}->writeLogInfo("EXEC: Exit command: " . ($? >> 8)); + } elsif (($exit_code >> 8) != 0) { + $self->{logger}->writeLogInfo("EXEC: Exit command: " . ($exit_code >> 8)); } if (defined($output)) { chomp $output; From 4aab23f3afcdc2b0149202fbee70436217ac2927 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 10 Jul 2013 18:48:30 +0200 Subject: [PATCH 084/458] Fix bug in deocde_entities call --- centreon/lib/perl/centreon/script/centreontrapd.pm | 4 ++-- centreon/lib/perl/centreon/trapd/lib.pm | 3 --- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 9bcb91c6c95..1425c995e03 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -714,7 +714,7 @@ sub checkMatchingRules { ########################## # REPLACE special Chars if ($self->{htmlentities} == 1) { - $tmoString = decode_entities($tmoString); + $tmoString = HTML::Entities::decode_entities($tmoString); } else { $tmoString =~ s/\"\;/\"/g; $tmoString =~ s/\'\;\'\;/"/g; @@ -756,7 +756,7 @@ sub executeCommand { ########################## # REPLACE MACROS if ($self->{htmlentities} == 1) { - $traps_execution_command = decode_entities($traps_execution_command); + $traps_execution_command = HTML::Entities::decode_entities($traps_execution_command); } else { $traps_execution_command =~ s/\"\;/\"/g; $traps_execution_command =~ s/\'\;\'\;/"/g; diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index d65c6c3899e..95b210d38c2 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -25,7 +25,6 @@ sub init_modules { $args{logger}->writeLogError("SNMP module, NOT the CPAN Net::SNMP module!"); die("Quit"); } - require SNMP; if (defined ($args{config}->{mibs_environment}) && $args{config}->{mibs_environment} ne '') { $ENV{'MIBS'} = $args{config}->{mibs_environment}; } @@ -49,7 +48,6 @@ sub init_modules { $args{logger}->writeLogError("for system requirements"); die("Quit"); } - require Socket; $args{logger}->writeLogInfo("********** DNS enabled **********"); } @@ -62,7 +60,6 @@ sub init_modules { $args{logger}->writeLogError("for system requirements."); die("Quit"); } - require Digest::MD5; } eval "require HTML::Entities"; From fc41e551b2c30b9a3a8aa89e450cd8dc8ff99403 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 11 Jul 2013 10:30:01 +0200 Subject: [PATCH 085/458] Add some patches from snmptt 1.4beta2 fix --- centreon/lib/perl/centreon/trapd/lib.pm | 28 +++++++++++++++---------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 95b210d38c2..d80b2427511 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -486,6 +486,13 @@ sub readtrap { } } + # With DNS resolution disabled in snmptrapd, some systems pass the hostname as: + # UDP: [x.x.x.x]:161->[y.y.y.y] + # If this is detected, use x.x.x.x as the hostname. + if ($tempvar[0] =~ /\[(\d+\.\d+\.\d+\.\d+)\].*?->\[(\d+\.\d+\.\d+\.\d+)\]/) { + $tempvar[0] = $1; + } + # Some systems pass the IP address as udp:ipaddress:portnumber. This will pull # out just the IP address $tempvar[1] =~ /(\d+\.\d+\.\d+\.\d+)/; @@ -518,16 +525,16 @@ sub readtrap { chomp ($line); my $variable_fix; - #if ($linenum == 1) { + if ($linenum == 1) { # Check if line 1 contains 'variable value' or just 'value' if (defined($temp2)) { $variable_fix = 0; } else { $variable_fix = 1; } - #} + } - if ($variable_fix == 0 ) { + if ($variable_fix == 0) { # Make sure variable names are numerical $temp1 = translate_symbolic_to_oid($temp1, $args{logger}, $args{config}); @@ -536,13 +543,13 @@ sub readtrap { # Net-SNMP sometimes divides long lines into multiple lines.. if ( ($temp2 =~ /^\"/) && ( ! ($temp2 =~ /[^\\]\"$/)) ) { $args{logger}->writeLogDebug(" Multi-line value detected - merging onto one line..."); - chomp $temp2; # Remove the newline character + $temp2 =~ s/[\r\n]//g; # Remove the newline character while (defined(my $line2 = <$input>)) { chomp $line2; push(@rawtrap, $line2); - $temp2.=" ".$line2; - # Ends in a non-escaped quote - if ($line2 =~ /[^\\]\"$/) { + $temp2 .= " " . $line2; + # Check if line ends in a non-escaped quote + if (($line2 =~ /\"$/) && ($line2 !~ /\\\"$/)) { last; } } @@ -584,13 +591,12 @@ sub readtrap { # Net-SNMP sometimes divides long lines into multiple lines.. if ( ($line =~ /^\"/) && ( ! ($line =~ /[^\\]\"$/)) ) { $args{logger}->writeLogDebug(" Multi-line value detected - merging onto one line..."); - chomp $line; # Remove the newline character + $temp2 =~ s/[\r\n]//g; # Remove newline characters while (defined(my $line2 = <$input>)) { chomp $line2; push(@rawtrap, $line2); - $line.=" ".$line2; - # Ends in a non-escaped quote - if ($line2 =~ /[^\\]\"$/) { + $temp2 .= " " . $line2; + if (($line2 =~ /\"$/) && ($line2 !~ /\\\"$/)) { # Ends in a non-escaped quote or it's a single line with a quote. last; } } From 14d9b26fdd57235fc9bafa9a9e9956e2c6a0b357 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 11 Jul 2013 11:02:15 +0200 Subject: [PATCH 086/458] Add severities in local push db --- centreon/lib/perl/centreon/script/centreontrapd.pm | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 1425c995e03..69859fb79be 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -728,9 +728,9 @@ sub checkMatchingRules { $self->{traps_global_severity_id} = $severity_id; $self->{logger}->writeLogInfo("Regexp: String:$tmoString => REGEXP:$regexp"); $self->{logger}->writeLogInfo("Status: $self->{traps_global_status} ($tmoStatus)"); - $self->{logger}->writeLogInfo("Severity id: $self->{traps_global_severity_id} ($severity_id)"); - $self->{logger}->writeLogInfo("Severity name: $self->{traps_global_severity_name} ($severity_name)"); - $self->{logger}->writeLogInfo("Severity level: $self->{traps_global_severity_level} ($severity_level)"); + $self->{logger}->writeLogInfo("Severity id: " . (defined($self->{traps_global_severity_id}) ? $self->{traps_global_severity_id} : "null")); + $self->{logger}->writeLogInfo("Severity name: " . (defined($self->{traps_global_severity_name}) ? $self->{traps_global_severity_name} : "null")); + $self->{logger}->writeLogInfo("Severity level: " . (defined($self->{traps_global_severity_level}) ? $self->{traps_global_severity_level} : "null")); $matching_boolean = 1; last; } From 5f7838e685fca1a3af47d88193520c0a04764a17 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 11 Jul 2013 11:25:20 +0200 Subject: [PATCH 087/458] Add severities in trap log. --- .../lib/perl/centreon/script/centreontrapd.pm | 4 +++- centreon/lib/perl/centreon/trapd/Log.pm | 2 +- centreon/lib/perl/centreon/trapd/lib.pm | 15 ++++++++++----- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 69859fb79be..e16fe8644cd 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -419,7 +419,9 @@ sub do_exec { trap_oid => $self->{current_oid}, trap_name => $self->{current_trap_name}, vendor => $self->{current_vendor_name}, - severity => $self->{traps_global_status}, + status => $self->{traps_global_status}, + severity_id => $self->{traps_global_severity_id}, + severity_name => $self->{traps_global_severity_name}, output_message => $self->{traps_global_output}, entvar => \@{$self->{entvar}}, entvarname => \@{$self->{entvarname}}); diff --git a/centreon/lib/perl/centreon/trapd/Log.pm b/centreon/lib/perl/centreon/trapd/Log.pm index e1a293cf710..22218d2193d 100644 --- a/centreon/lib/perl/centreon/trapd/Log.pm +++ b/centreon/lib/perl/centreon/trapd/Log.pm @@ -97,7 +97,7 @@ sub compute_request { $self->{dbcentstorage}->transaction_mode(1); eval { foreach my $id (keys %{$self->{request_log}}) { - $self->{dbcentstorage}->query("INSERT INTO log_traps (`trap_time`, `timeout`, `host_name`, `ip_address`, `agent_host_name`, `agent_ip_address`, `trap_oid`, `trap_name`, `vendor`, `severity`, `output_message`) VALUES (" . $self->{request_log}->{$id}->{value} . ")"); + $self->{dbcentstorage}->query("INSERT INTO log_traps (`trap_time`, `timeout`, `host_name`, `ip_address`, `agent_host_name`, `agent_ip_address`, `trap_oid`, `trap_name`, `vendor`, `status`, `severity_id`, `severity_name`, `output_message`) VALUES (" . $self->{request_log}->{$id}->{value} . ")"); $self->{dbcentstorage}->query("SET \@last_id_trap = LAST_INSERT_ID();"); if (defined($self->{request_log}->{$id}->{args})) { foreach (@{$self->{request_log}->{$id}->{args}}) { diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index d80b2427511..1eebed38780 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -273,7 +273,7 @@ sub send_logdb { # Need atomic write (Limit to 4096 with Linux) $args{output_message} =~ s/\n/\\n/g; - print $pipe $args{id} . ":0:$num_args:" . + my $value = $args{id} . ":0:$num_args:" . $args{trap_time} . "," . $args{cdb}->quote($args{timeout}) . "," . $args{cdb}->quote($args{host_name}) . "," . @@ -283,9 +283,14 @@ sub send_logdb { $args{cdb}->quote($args{trap_oid}) . "," . $args{cdb}->quote($args{trap_name}) . "," . $args{cdb}->quote($args{vendor}) . "," . - $args{cdb}->quote($args{severity}) . "," . - $args{cdb}->quote($args{output_message}) . "\n"; - for (my $i=0; $i <= $#{$args{entvar}}; $i++) { + $args{cdb}->quote($args{status}) . "," . + $args{cdb}->quote($args{severity_id}) . "," . + $args{cdb}->quote($args{severity_name}) . ","; + # We truncate if it + $value .= substr($args{cdb}->quote($args{output_message}), 0, 4096 - length($value) - 1); + print $pipe $value . "\n"; + + for (my $i=0; $i <= $#{$args{entvar}}; $i++) { my $value = ${$args{entvar}}[$i]; $value =~ s/\n/\\n/g; print $pipe $args{id} . ":1:$i:" . @@ -293,7 +298,7 @@ sub send_logdb { $args{cdb}->quote(${$args{entvarname}}[$i]) . "," . $args{cdb}->quote($value) . "," . $args{trap_time} . "\n"; - } + } } ############## From 838e13b8eda524f96bf33bde8ad3d15390b81126 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 11 Jul 2013 17:43:28 +0200 Subject: [PATCH 088/458] Ref #4623 --- .../centreon/centstorage/CentstorageAction.pm | 145 ++-- .../centreon/centstorage/CentstorageLib.pm | 22 +- .../centstorage/CentstoragePerfdataFile.pm | 95 +-- .../centreon/centstorage/CentstoragePool.pm | 636 +++++++++--------- .../centreon/centstorage/CentstorageRRD.pm | 238 +++---- .../centstorage/CentstorageRebuild.pm | 44 +- centreon/lib/perl/centreon/common/misc.pm | 40 ++ centreon/lib/perl/centreon/script/centcore.pm | 2 +- .../lib/perl/centreon/script/centstorage.pm | 98 +-- 9 files changed, 700 insertions(+), 620 deletions(-) diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm index abad3762718..2d4a3a61cb7 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm @@ -4,25 +4,26 @@ package centreon::centstorage::CentstorageAction; use strict; use warnings; use centreon::common::misc; -my %handlers = ('TERM' => {}, 'HUP' => {}); +my %handlers = (TERM => {}, HUP => {}); sub new { my $class = shift; my $self = {}; - $self->{"logger"} = shift; - $self->{"rebuild_progress"} = shift; - $self->{"dbcentreon"} = undef; - $self->{"dbcentstorage"} = undef; - $self->{"purge_delay"} = 3600; - $self->{"last_purge_time"} = time() - $self->{"purge_delay"} - 5; + $self->{logger} = shift; + $self->{rebuild_progress} = shift; + $self->{centstorage_config} = shift; + $self->{dbcentreon} = undef; + $self->{dbcentstorage} = undef; + $self->{purge_delay} = 3600; + $self->{last_purge_time} = time() - $self->{purge_delay} - 5; - $self->{"deleted_delay"} = 120; - $self->{"last_deleted_time"} = time() - $self->{"deleted_delay"} - 5; + $self->{deleted_delay} = 120; + $self->{last_deleted_time} = time() - $self->{deleted_delay} - 5; - $self->{"rrd_metrics_path"} = undef; - $self->{"rrd_status_path"} = undef; + $self->{rrd_metrics_path} = undef; + $self->{rrd_status_path} = undef; - $self->{"save_read"} = []; + $self->{save_read} = []; # reload flag $self->{reload} = 1; @@ -37,7 +38,7 @@ sub set_signal_handlers { my $self = shift; $SIG{TERM} = \&class_handle_TERM; - $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; + $handlers{TERM}->{$self} = sub { $self->handle_TERM() }; $SIG{HUP} = \&class_handle_HUP; $handlers{HUP}->{$self} = sub { $self->handle_HUP() }; } @@ -49,15 +50,15 @@ sub handle_HUP { sub handle_TERM { my $self = shift; - $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); + $self->{logger}->writeLogInfo("$$ Receiving order to stop..."); - $self->{'dbcentreon'}->disconnect() if (defined($self->{'dbcentreon'})); - $self->{'dbcentstorage'}->disconnect() if (defined($self->{'dbcentstorage'})); + $self->{dbcentreon}->disconnect() if (defined($self->{dbcentreon})); + $self->{dbcentstorage}->disconnect() if (defined($self->{dbcentstorage})); } sub class_handle_TERM { - foreach (keys %{$handlers{'TERM'}}) { - &{$handlers{'TERM'}->{$_}}(); + foreach (keys %{$handlers{TERM}}) { + &{$handlers{TERM}->{$_}}(); } exit(0); } @@ -88,6 +89,9 @@ sub reload { $self->{dbcentstorage}->disconnect(); $self->{dbcentstorage}->connect(); } + + centreon::common::misc::get_option_config($self->{centstorage_config}, $self->{dbcentreon}, + "centstorage", "nopurge"); centreon::common::misc::check_debug($self->{logger}, "debug_centstorage", $self->{dbcentreon}, "centstorage delete process"); $self->{reload} = 1; @@ -97,24 +101,28 @@ sub check_deleted { my $self = shift; my $pipe_write = $_[0]; - if (time() < ($self->{"last_deleted_time"} + $self->{"deleted_delay"})) { + if (time() < ($self->{last_deleted_time} + $self->{deleted_delay})) { return ; } - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `host_name`, `service_description`, `metrics`.metric_id FROM `index_data` LEFT JOIN `metrics` ON (index_data.id = metrics.index_id) WHERE index_data.to_delete = '1' ORDER BY id"); + if (defined($self->{centstorage_config}->{nopurge}) && int($self->{centstorage_config}->{nopurge}) == 1) { + return ; + } + + my ($status, $stmt) = $self->{dbcentstorage}->query("SELECT `id`, `host_name`, `service_description`, `metrics`.metric_id FROM `index_data` LEFT JOIN `metrics` ON (index_data.id = metrics.index_id) WHERE index_data.to_delete = '1' ORDER BY id"); return -1 if ($status == -1); my $current_index_id = -1; while ((my $data = $stmt->fetchrow_hashref())) { - if ($current_index_id != $data->{'id'}) { - if ($self->delete_rrd_file($self->{"rrd_status_path"}, $data->{'id'}) == 0) { - $self->{'dbcentstorage'}->query("DELETE FROM index_data WHERE id = " . $data->{'id'}); + if ($current_index_id != $data->{id}) { + if ($self->delete_rrd_file($self->{rrd_status_path}, $data->{id}) == 0) { + $self->{dbcentstorage}->query("DELETE FROM index_data WHERE id = " . $data->{id}); } - $current_index_id = $data->{'id'}; - print $pipe_write "DELETECLEAN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\n"; + $current_index_id = $data->{id}; + print $pipe_write "DELETECLEAN\t" . $data->{host_name} . "\t" . $data->{service_description} . "\n"; } - if (defined($data->{'metric_id'})) { - if ($self->delete_rrd_file($self->{"rrd_metrics_path"}, $data->{'metric_id'}) == 0) { - $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data->{'metric_id'}); + if (defined($data->{metric_id})) { + if ($self->delete_rrd_file($self->{rrd_metrics_path}, $data->{metric_id}) == 0) { + $self->{dbcentstorage}->query("DELETE FROM metrics WHERE metric_id = " . $data->{metric_id}); } } } @@ -122,32 +130,32 @@ sub check_deleted { ### # Check metrics alone ### - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `host_name`, `service_description`, `metrics`.metric_id, `metrics`.metric_name FROM `metrics` LEFT JOIN `index_data` ON (index_data.id = metrics.index_id) WHERE metrics.to_delete = '1'"); + ($status, $stmt) = $self->{dbcentstorage}->query("SELECT `host_name`, `service_description`, `metrics`.metric_id, `metrics`.metric_name FROM `metrics` LEFT JOIN `index_data` ON (index_data.id = metrics.index_id) WHERE metrics.to_delete = '1'"); return -1 if ($status == -1); while ((my $data = $stmt->fetchrow_hashref())) { - if (defined($data->{'host_name'})) { - print $pipe_write "DELETECLEAN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\t" . $data->{'metric_name'} . "\n"; + if (defined($data->{host_name})) { + print $pipe_write "DELETECLEAN\t" . $data->{host_name} . "\t" . $data->{service_description} . "\t" . $data->{metric_name} . "\n"; } - if ($self->delete_rrd_file($self->{"rrd_metrics_path"}, $data->{'metric_id'}) == 0) { - $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data->{'metric_id'}); + if ($self->delete_rrd_file($self->{rrd_metrics_path}, $data->{metric_id}) == 0) { + $self->{dbcentstorage}->query("DELETE FROM metrics WHERE metric_id = " . $data->{metric_id}); } } - $self->{"last_deleted_time"} = time(); + $self->{last_deleted_time} = time(); } sub check_rebuild { my $self = shift; my $pipe_write = $_[0]; - return if ($self->{"rebuild_progress"} == 1); - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `host_name`, `service_description` FROM `index_data` WHERE `must_be_rebuild` IN ('1', '2') LIMIT 1"); + return if ($self->{rebuild_progress} == 1); + my ($status, $stmt) = $self->{dbcentstorage}->query("SELECT `host_name`, `service_description` FROM `index_data` WHERE `must_be_rebuild` IN ('1', '2') LIMIT 1"); return -1 if ($status == -1); my $data = $stmt->fetchrow_hashref(); if (defined($data)) { - $self->{"rebuild_progress"} = 1; - $self->{"logger"}->writeLogInfo("Rebuild detected: " . $data->{'host_name'} . "/" . $data->{'service_description'}); - print $pipe_write "REBUILDBEGIN\t" . $data->{'host_name'} . "\t" . $data->{'service_description'} . "\n"; + $self->{rebuild_progress} = 1; + $self->{logger}->writeLogInfo("Rebuild detected: " . $data->{host_name} . "/" . $data->{service_description}); + print $pipe_write "REBUILDBEGIN\t" . $data->{host_name} . "\t" . $data->{service_description} . "\n"; } } @@ -155,12 +163,11 @@ sub delete_rrd_file { my $self = shift; my ($path, $id) = @_; - if (-e $path . "/" . $id . ".rrd") { if (unlink($path . "/" . $id . ".rrd")) { - $self->{'logger'}->writeLogInfo("Delete RRD file " . $path . "/" . $id . ".rrd"); + $self->{logger}->writeLogInfo("Delete RRD file " . $path . "/" . $id . ".rrd"); } else { - $self->{'logger'}->writeLogError("Cannot delete RRD file " . $path . "/" . $id . ".rrd: " . $!); + $self->{logger}->writeLogError("Cannot delete RRD file " . $path . "/" . $id . ".rrd: " . $!); return 1; } } @@ -173,8 +180,12 @@ sub purge_mysql_and_rrd { my %cache_index_data = (); my %cache_services = (); + if (defined($self->{centstorage_config}->{nopurge}) && int($self->{centstorage_config}->{nopurge}) == 1) { + return ; + } + # Get By direct - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT host_host_id, service_service_id FROM host_service_relation WHERE hostgroup_hg_id IS NULL"); + ($status, $stmt) = $self->{dbcentreon}->query("SELECT host_host_id, service_service_id FROM host_service_relation WHERE hostgroup_hg_id IS NULL"); return -1 if ($status == -1); $rows = []; while ($data = (shift(@$rows) || @@ -183,7 +194,7 @@ sub purge_mysql_and_rrd { } # Get By Hostgroup - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT host.host_id, host_service_relation.service_service_id FROM host, host_service_relation, hostgroup_relation WHERE host.host_id = hostgroup_relation.host_host_id AND hostgroup_relation.hostgroup_hg_id = host_service_relation.hostgroup_hg_id"); + ($status, $stmt) = $self->{dbcentreon}->query("SELECT host.host_id, host_service_relation.service_service_id FROM host, host_service_relation, hostgroup_relation WHERE host.host_id = hostgroup_relation.host_host_id AND hostgroup_relation.hostgroup_hg_id = host_service_relation.hostgroup_hg_id"); return -1 if ($status == -1); $rows = []; while ($data = (shift(@$rows) || @@ -195,28 +206,28 @@ sub purge_mysql_and_rrd { # Cache Dir #### my @files = (); - if (opendir(DIR, $self->{"rrd_status_path"})) { + if (opendir(DIR, $self->{rrd_status_path})) { @files = grep { $_ ne '.' and $_ ne '..' } readdir DIR; } else { - $self->{'logger'}->writeLogError("Can't opendir " . $self->{"rrd_status_path"} . ": $!"); + $self->{logger}->writeLogError("Can't opendir " . $self->{"rrd_status_path"} . ": $!"); } - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT host_id, service_id, id FROM index_data"); + ($status, $stmt) = $self->{dbcentstorage}->query("SELECT host_id, service_id, id FROM index_data"); return -1 if ($status); $rows = []; while ($data = (shift(@$rows) || shift(@{$rows = $stmt->fetchall_arrayref(undef,10_000)||[]}) ) ) { $cache_index_data{$$data[2]} = 1; if (defined($$data[0]) && defined($$data[1]) && !defined($cache_services{$$data[0] . ";" . $$data[1]})) { - ($status, my $stmt2) = $self->{'dbcentstorage'}->query("SELECT metric_id FROM metrics WHERE index_id = '" . $$data[2] . "'"); + ($status, my $stmt2) = $self->{dbcentstorage}->query("SELECT metric_id FROM metrics WHERE index_id = '" . $$data[2] . "'"); next if ($status == -1); while ((my $data2 = $stmt2->fetchrow_hashref())) { - $self->{'dbcentstorage'}->query("DELETE FROM metrics WHERE metric_id = " . $data2->{'metric_id'}); - $self->delete_rrd_file($self->{"rrd_metrics_path"}, $data2->{'metric_id'}); + $self->{dbcentstorage}->query("DELETE FROM metrics WHERE metric_id = " . $data2->{metric_id}); + $self->delete_rrd_file($self->{"rrd_metrics_path"}, $data2->{metric_id}); } - $self->{'dbcentstorage'}->query("DELETE FROM index_data WHERE id = '" . $$data[2] . "'"); - $self->{'logger'}->writeLogInfo("Delete MySQL metrics " . $$data[0] . "/" . $$data[1]); - $self->delete_rrd_file($self->{"rrd_status_path"}, $$data[2]); + $self->{dbcentstorage}->query("DELETE FROM index_data WHERE id = '" . $$data[2] . "'"); + $self->{logger}->writeLogInfo("Delete MySQL metrics " . $$data[0] . "/" . $$data[1]); + $self->delete_rrd_file($self->{rrd_status_path}, $$data[2]); } } @@ -225,7 +236,7 @@ sub purge_mysql_and_rrd { ### foreach (@files) { if ($_ =~ /(.*)\.rrd$/ && !defined($cache_index_data{$1})) { - $self->delete_rrd_file($self->{"rrd_status_path"}, $1); + $self->delete_rrd_file($self->{rrd_status_path}, $1); } } @@ -233,14 +244,14 @@ sub purge_mysql_and_rrd { # Purge RRD Metrics ### @files = (); - if (opendir(DIR, $self->{"rrd_metrics_path"})) { + if (opendir(DIR, $self->{rrd_metrics_path})) { @files = grep { $_ ne '.' and $_ ne '..' } readdir DIR; } else { - $self->{'logger'}->writeLogError("Can't opendir " . $self->{"rrd_metrics_path"} . ": $!"); + $self->{logger}->writeLogError("Can't opendir " . $self->{rrd_metrics_path} . ": $!"); } my %cache_metrics_data = (); - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id FROM metrics"); + ($status, $stmt) = $self->{dbcentstorage}->query("SELECT metric_id FROM metrics"); return -1 if ($status == -1); $rows = []; while ($data = (shift(@$rows) || @@ -250,7 +261,7 @@ sub purge_mysql_and_rrd { foreach (@files) { if ($_ =~ /(.*)\.rrd$/ && !defined($cache_metrics_data{$1})) { - $self->delete_rrd_file($self->{"rrd_metrics_path"}, $1); + $self->delete_rrd_file($self->{rrd_metrics_path}, $1); } } } @@ -259,11 +270,11 @@ sub get_centstorage_information { my $self = shift; my ($rrd_metrics_path, $rrd_status_path); - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT RRDdatabase_path, RRDdatabase_status_path FROM config"); + my ($status, $stmt) = $self->{dbcentstorage}->query("SELECT RRDdatabase_path, RRDdatabase_status_path FROM config"); my $data = $stmt->fetchrow_hashref(); if (defined($data)) { - $rrd_metrics_path = $data->{'RRDdatabase_path'}; - $rrd_status_path = $data->{'RRDdatabase_status_path'}; + $rrd_metrics_path = $data->{RRDdatabase_path}; + $rrd_status_path = $data->{RRDdatabase_status_path}; } return ($status, $rrd_metrics_path, $rrd_status_path); } @@ -271,12 +282,12 @@ sub get_centstorage_information { sub check_purge { my $self = shift; - if (time() < ($self->{"last_purge_time"} + $self->{"purge_delay"})) { + if (time() < ($self->{last_purge_time} + $self->{purge_delay})) { return ; } $self->purge_mysql_and_rrd(); - $self->{"last_purge_time"} = time(); + $self->{last_purge_time} = time(); } sub main { @@ -288,11 +299,11 @@ sub main { $self->{dbcentstorage} = $dbcentstorage; $self->{config_file} = $config_file; - ($status, $self->{"rrd_metrics_path"}, $self->{"rrd_status_path"}) = $self->get_centstorage_information(); + ($status, $self->{rrd_metrics_path}, $self->{rrd_status_path}) = $self->get_centstorage_information(); # We have to manage if you don't need infos - $self->{'dbcentreon'}->force(0); - $self->{'dbcentstorage'}->force(0); + $self->{dbcentreon}->force(0); + $self->{dbcentstorage}->force(0); my $read_select = new IO::Select(); $read_select->add($pipe_read); @@ -308,7 +319,7 @@ sub main { # Check Type if (defined($method) && $method eq "REBUILDFINISH") { - $self->{"rebuild_progress"} = 0; + $self->{rebuild_progress} = 0; } } } diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm b/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm index bf183f10e14..85810a6402c 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm @@ -8,7 +8,7 @@ sub start_or_not { my ($status2, $stmt) = $centreon_db_centreon->query("SELECT value FROM options WHERE `key` = 'centstorage' LIMIT 1"); my $data = $stmt->fetchrow_hashref(); - if (defined($data) && int($data->{'value'}) == 0) { + if (defined($data) && int($data->{value}) == 0) { $status = 0; } return $status; @@ -18,10 +18,10 @@ sub get_main_perfdata_file { my ($centreon_db_centreon) = @_; my $filename; - my ($status, $stmt) = $centreon_db_centreon->query("SELECT `nagios_perfdata` FROM `nagios_server` WHERE `localhost` = '1'"); + my ($status, $stmt) = $centreon_db_centreon->query("SELECT `nagios_perfdata` FROM `nagios_server` WHERE `localhost` = '1' ORDER BY ns_activate DESC LIMIT 1"); my $data = $stmt->fetchrow_hashref(); if (defined($data)) { - $filename = $data->{'nagios_perfdata'}; + $filename = $data->{nagios_perfdata}; } return ($status, $filename); } @@ -59,13 +59,13 @@ sub call_pool_rebuild { $pool_choosen = $routing_services->{$host_name . ";" . $service_description}; for ($i = 0; $i < $pool_childs; $i++) { if ($i == $pool_choosen) { - my $fh = $pool_pipes->{$i}->{'writer_two'}; + my $fh = $pool_pipes->{$i}->{writer_two}; # It's when you loose a pool. You have to know $$rebuild_progress = 1; $$rebuild_pool_choosen = $pool_choosen; print $fh "REBUILDBEGIN\t$host_name\t$service_description\n"; } else { - my $fh = $pool_pipes->{$i}->{'writer_two'}; + my $fh = $pool_pipes->{$i}->{writer_two}; print $fh "REBUILDBEGIN\n"; } } @@ -79,11 +79,11 @@ sub call_pool_rebuild_finish { $$rebuild_pool_choosen = -1; for ($i = 0; $i < $pool_childs; $i++) { if ($rebuild_pool_choosen != $i) { - $fh = $pool_pipes->{$i}->{'writer_two'}; + $fh = $pool_pipes->{$i}->{writer_two}; print $fh "REBUILDFINISH\n"; } } - $fh = $delete_pipes->{'writer_two'}; + $fh = $delete_pipes->{writer_two}; print $fh "REBUILDFINISH\n"; } @@ -94,12 +94,12 @@ sub call_pool_rename_clean { my $pool_choosen; if (!defined($routing_services->{$old_host_name . ";" . $old_service_description})) { # There is no for the old name. Can go back - my $fh = $pool_pipes->{$routing_services->{$new_host_name . ";" . $new_service_description}}->{'writer_two'}; + my $fh = $pool_pipes->{$routing_services->{$new_host_name . ";" . $new_service_description}}->{writer_two}; print $fh "RENAMEFINISH\t" . $new_host_name . "\t" . $new_service_description . "\n"; return ; } # Send to clean - my $fh = $pool_pipes->{$routing_services->{$old_host_name . ";" . $old_service_description}}->{'writer_two'}; + my $fh = $pool_pipes->{$routing_services->{$old_host_name . ";" . $old_service_description}}->{writer_two}; print $fh "RENAMECLEAN\t" . $old_host_name . "\t" . $old_service_description . "\t" . $new_host_name . "\t" . $new_service_description . "\n"; } @@ -108,7 +108,7 @@ sub call_pool_rename_finish { my ($method, $new_host_name, $new_service_description) = split(/\t/, $line); if (defined($routing_services->{$new_host_name . ";" . $new_service_description})) { - my $fh = $pool_pipes->{$routing_services->{$new_host_name . ";" . $new_service_description}}->{'writer_two'}; + my $fh = $pool_pipes->{$routing_services->{$new_host_name . ";" . $new_service_description}}->{writer_two}; print $fh "RENAMEFINISH\t" . $new_host_name . "\t" . $new_service_description . "\n"; return ; } @@ -122,7 +122,7 @@ sub call_pool_delete_clean { # No cache. so we return return ; } - my $fh = $pool_pipes->{$routing_services->{$host_name . ";" . $service_description}}->{'writer_two'}; + my $fh = $pool_pipes->{$routing_services->{$host_name . ";" . $service_description}}->{writer_two}; print $fh "$line\n"; } diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm index cfd8709632f..53ac3a654cb 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm @@ -9,42 +9,52 @@ use centreon::common::misc; sub new { my $class = shift; my $self = {}; - $self->{"logger"} = shift; - $self->{"filehandler"} = undef; - $self->{"filename"} = undef; - $self->{"eof_file"} = 0; - $self->{"readed"} = 0; - $self->{"buffer"} = []; + $self->{logger} = shift; + $self->{filehandler} = undef; + $self->{filename} = undef; + $self->{eof_file} = 0; + $self->{readed} = 0; + $self->{buffer} = []; bless $self, $class; return $self; } sub compute { my $self = shift; - $self->{'filename'} = $_[0]; - my ($pool_pipes, $routing_services, $roundrobin_pool_current, $total_pool) = ($_[1], $_[2], $_[3], $_[4]); - - if ($self->{'filename'} !~ /_read$/) { - if (!(File::Copy::move($self->{'filename'}, $self->{'filename'} . "_read"))) { - $self->{"logger"}->writeLogError("Cannot move " . $self->{'filename'} . " file : $!"); + $self->{filename} = shift; + my ($pool_pipes, $routing_services, $roundrobin_pool_current, $total_pool, $auto_duplicate, $duplicate_file) = @_; + my $do_duplicate = 0; + + if (defined($auto_duplicate) && int($auto_duplicate) == 1 && + defined($duplicate_file) && $duplicate_file ne "") { + if (!open(FILEDUPLICATE, ">> " . $duplicate_file)) { + $self->{logger}->writeLogError("Can't open for write " . $duplicate_file . "_read.offset file: $!"); + } else { + $do_duplicate = 1; + } + } + + if ($self->{filename} !~ /_read$/) { + if (!(File::Copy::move($self->{filename}, $self->{filename} . "_read"))) { + $self->{logger}->writeLogError("Cannot move " . $self->{filename} . " file : $!"); return -1; } - if (!open($self->{"filehandler"}, '+< ' . $self->{"filename"} . "_read")) { - $self->{"logger"}->writeLogError("Cannot open " . $self->{'filename'} . "_read file : $!"); + if (!open($self->{filehandler}, '+< ' . $self->{filename} . "_read")) { + $self->{logger}->writeLogError("Cannot open " . $self->{filename} . "_read file : $!"); return -1; } } else { - $self->{'filename'} =~ s/_read$//; - if (!open($self->{"filehandler"}, '+< ' . $self->{"filename"} . "_read")) { - $self->{"logger"}->writeLogError("Cannot open " . $self->{'filename'} . "_read file : $!"); + $self->{filename} =~ s/_read$//; + if (!open($self->{filehandler}, '+< ' . $self->{filename} . "_read")) { + $self->{logger}->writeLogError("Cannot open " . $self->{filename} . "_read file : $!"); return -1; } } # Get offset if exist - if (-e $self->{'filename'} . "_read.offset") { - if (!open(FILE, "<", $self->{'filename'} . "_read.offset")) { - $self->{"logger"}->writeLogError("Can't read " . $self->{'filename'} . "_read.offset file: $!"); + if (-e $self->{filename} . "_read.offset") { + if (!open(FILE, "<", $self->{filename} . "_read.offset")) { + $self->{logger}->writeLogError("Can't read " . $self->{filename} . "_read.offset file: $!"); return -1; } my $offset = ; @@ -52,61 +62,70 @@ sub compute { chomp $offset; $offset = int($offset); if ($offset =~ /^[0-9]+$/) { - seek($self->{"filehandler"}, $offset, 1); - $self->{"readed"} = $offset; + seek($self->{filehandler}, $offset, 1); + $self->{readed} = $offset; } - unlink($self->{'filename'} . "_read.offset"); + unlink($self->{filename} . "_read.offset"); } - my $fh = $self->{"filehandler"}; - while ((my ($status, $readline) = centreon::common::misc::get_line_file($fh, \@{$self->{"buffer"}}, \$self->{"readed"}))) { + my $fh = $self->{filehandler}; + while ((my ($status, $readline) = centreon::common::misc::get_line_file($fh, \@{$self->{buffer}}, \$self->{readed}))) { last if ($status == -1); + if ($do_duplicate == 1) { + print FILEDUPLICATE $readline . "\n"; + } + $readline =~ /([0-9]+?)\t+?([^\t]+?)\t+?([^\t]+?)\t/; if (defined($1) && defined($2) && defined($3)) { if (defined($routing_services->{$2 . ";" . $3})) { - my $tmp_fh = $pool_pipes->{$routing_services->{$2 . ";" . $3}}->{'writer_two'}; + my $tmp_fh = $pool_pipes->{$routing_services->{$2 . ";" . $3}}->{writer_two}; print $tmp_fh "UPDATE\t$readline\n"; } else { # Choose a pool my $pool_num = $$roundrobin_pool_current % $total_pool; $$roundrobin_pool_current++; - my $tmp_fh = $pool_pipes->{$pool_num}->{'writer_two'}; + my $tmp_fh = $pool_pipes->{$pool_num}->{writer_two}; print $tmp_fh "UPDATE\t$readline\n"; $routing_services->{$2 . ";" . $3} = $pool_num; } } } - $self->{"eof_file"} = 1; + $self->{eof_file} = 1; $self->finish(); + + if ($do_duplicate == 1) { + close FILEDUPLICATE; + } + return 0; } sub finish { my $self = shift; - if (defined($self->{"filehandler"})) { - my $fh = $self->{"filehandler"}; + if (defined($self->{filehandler})) { + my $fh = $self->{filehandler}; if ($self->{"eof_file"} == 1) { - if (!unlink($self->{"filename"} . "_read")) { - $self->{"logger"}->writeLogError("Cannot unlink " . $self->{'filename'} . "_read file : $!\n"); + if (!unlink($self->{filename} . "_read")) { + $self->{logger}->writeLogError("Cannot unlink " . $self->{filename} . "_read file : $!"); } close($fh); } else { - $self->{"logger"}->writeLogInfo("Write Offset File " . $self->{'filename'} . "_read.offset file\n"); - if (open(FILE, ">", $self->{'filename'} . "_read.offset")) { + $self->{logger}->writeLogInfo("Write Offset File " . $self->{filename} . "_read.offset file"); + if (open(FILE, ">", $self->{filename} . "_read.offset")) { require bytes; - my $offset = $self->{"readed"}; - for (my $i = scalar(@{$self->{"buffer"}}) - 1; $i >= 0; $i--) { - $offset = $offset - bytes::length(${$self->{"buffer"}}[$i]) - 1; # -1 = \n + my $offset = $self->{readed}; + for (my $i = scalar(@{$self->{buffer}}) - 1; $i >= 0; $i--) { + $offset = $offset - bytes::length(${$self->{buffer}}[$i]) - 1; # -1 = \n } # Last: Don't have \n $offset += 1; print FILE $offset . "\n"; close FILE; } else { - $self->{"logger"}->writeLogError("Can't write offset " . $self->{'filename'} . "_read.offset file: $!\n"); + $self->{logger}->writeLogError("Can't write offset " . $self->{'filename'} . "_read.offset file: $!\n"); # Slurp File my $rs_save = $/; undef $/; diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index 27d98765063..a4a2c361548 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -8,32 +8,32 @@ use centreon::common::misc; use centreon::centstorage::CentstorageLib; use centreon::centstorage::CentstorageRebuild; -my %handlers = ('TERM' => {}, 'CHLD' => {}, 'HUP' => {}); -my %rrd_trans = ("g" => 0, "c" => 1, "d" => 2, "a" => 3); +my %handlers = (TERM => {}, CHLD => {}, HUP => {}); +my %rrd_trans = (g => 0, c => 1, d => 2, a => 3); sub new { my $class = shift; my $self = {}; - $self->{"logger"} = shift; - $self->{"rrd"} = shift; - $self->{"rebuild_progress"} = shift; - $self->{"dbcentreon"} = undef; - $self->{"dbcentstorage"} = undef; + $self->{logger} = shift; + $self->{rrd} = shift; + $self->{rebuild_progress} = shift; + $self->{dbcentreon} = undef; + $self->{dbcentstorage} = undef; # skip if we don't find IDS in config - $self->{"skip_if_no_ids"} = 1; + $self->{skip_if_no_ids} = 1; - $self->{"len_storage_rrd"} = undef; - $self->{"rrd_metrics_path"} = undef; - $self->{"rrd_status_path"} = undef; - $self->{"main_perfdata_file"} = undef; - $self->{"interval_time"} = undef; - $self->{"do_rrd_status"} = 1; - $self->{"TIMEOUT"} = 30; - $self->{"num_pool"} = undef; + $self->{len_storage_rrd} = undef; + $self->{rrd_metrics_path} = undef; + $self->{rrd_status_path} = undef; + $self->{main_perfdata_file} = undef; + $self->{interval_time} = undef; + $self->{do_rrd_status} = 1; + $self->{TIMEOUT} = 30; + $self->{num_pool} = undef; # If rebuild in progress, we don't try to insert in DATA_BIN - $self->{"storage_type"} = undef; + $self->{storage_type} = undef; # { # 'metrics' => {'name1' => {}, 'name2' => {} } # 'service_id' => @@ -44,54 +44,54 @@ sub new { # 'rebuild' => # 'rrd_retention' => # } - $self->{"cache_service"} = {}; + $self->{cache_service} = {}; # Perfdata parsing vars - $self->{"perfdata_pos"} = undef; - $self->{"perfdata_size"} = undef; - $self->{"perfdata_chars"} = undef; - - $self->{"perfdata_parser_stop"} = 0; - - $self->{"service_perfdata"} = undef; - $self->{"metric_name"} = undef; - $self->{"metric_value"} = undef; - $self->{"metric_unit"} = undef; - $self->{"metric_warn"} = undef; - $self->{"warn_low"} = undef; - $self->{"warn_threshold_mode"} = undef; - $self->{"metric_crit"} = undef; - $self->{"crit_low"} = undef; - $self->{"crit_threshold_mode"} = undef; - $self->{"metric_min"} = undef; - $self->{"metric_max"} = undef; + $self->{perfdata_pos} = undef; + $self->{perfdata_size} = undef; + $self->{perfdata_chars} = undef; + + $self->{perfdata_parser_stop} = 0; + + $self->{service_perfdata} = undef; + $self->{metric_name} = undef; + $self->{metric_value} = undef; + $self->{metric_unit} = undef; + $self->{metric_warn} = undef; + $self->{warn_low} = undef; + $self->{warn_threshold_mode} = undef; + $self->{metric_crit} = undef; + $self->{crit_low} = undef; + $self->{crit_threshold_mode} = undef; + $self->{metric_min} = undef; + $self->{metric_max} = undef; # By service - $self->{"cache_services_failed"} = {}; - $self->{"last_check_failed"} = time(); - $self->{"check_failed_every"} = 60 * 10; # 20 minutes + $self->{cache_services_failed} = {}; + $self->{last_check_failed} = time(); + $self->{check_failed_every} = 60 * 10; # 20 minutes # Rename - $self->{"cache_services_rename"} = {}; - $self->{"rename_rebuild_wait"} = 0; - $self->{"rename_old_new"} = {}; + $self->{cache_services_rename} = {}; + $self->{rename_rebuild_wait} = 0; + $self->{rename_old_new} = {}; - $self->{"group_databin_stmt"} = ""; - $self->{"group_databin_total"} = 0; - $self->{"group_databin_append"} = ""; - $self->{"group_databin_max"} = 500; + $self->{group_databin_stmt} = ""; + $self->{group_databin_total} = 0; + $self->{group_databin_append} = ""; + $self->{group_databin_max} = 500; - $self->{"rebuild_index_id"} = undef; - $self->{"rebuild_key"} = undef; - $self->{"current_pid"} = undef; + $self->{rebuild_index_id} = undef; + $self->{rebuild_key} = undef; + $self->{current_pid} = undef; # reload flag $self->{reload} = 1; $self->{config_file} = undef; - $self->{"save_read"} = []; - $self->{"read_select"} = undef; - $self->{"pipe_write"} = undef; + $self->{save_read} = []; + $self->{read_select} = undef; + $self->{pipe_write} = undef; bless $self, $class; $self->set_signal_handlers; return $self; @@ -101,9 +101,9 @@ sub set_signal_handlers { my $self = shift; $SIG{TERM} = \&class_handle_TERM; - $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; + $handlers{TERM}->{$self} = sub { $self->handle_TERM() }; $SIG{CHLD} = \&class_handle_CHLD; - $handlers{'CHLD'}->{$self} = sub { $self->handle_CHLD() }; + $handlers{CHLD}->{$self} = sub { $self->handle_CHLD() }; $SIG{HUP} = \&class_handle_HUP; $handlers{HUP}->{$self} = sub { $self->handle_HUP() }; } @@ -115,11 +115,11 @@ sub handle_HUP { sub handle_TERM { my $self = shift; - $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); + $self->{logger}->writeLogInfo("$$ Receiving order to stop..."); - if (defined($self->{"current_pid"})) { - $self->{'logger'}->writeLogInfo("Send -TERM signal to rebuild process.."); - kill('TERM', $self->{"current_pid"}); + if (defined($self->{current_pid})) { + $self->{logger}->writeLogInfo("Send -TERM signal to rebuild process.."); + kill('TERM', $self->{current_pid}); } ### @@ -132,10 +132,10 @@ sub handle_TERM { alarm 0; }; if ($@) { - $self->{'dbcentstorage'}->kill(); + $self->{dbcentstorage}->kill(); } - $self->{'dbcentreon'}->disconnect() if (defined($self->{'dbcentreon'})); - $self->{'dbcentstorage'}->disconnect() if (defined($self->{'dbcentstorage'})); + $self->{dbcentreon}->disconnect() if (defined($self->{dbcentreon})); + $self->{dbcentstorage}->disconnect() if (defined($self->{dbcentstorage})); ### # Flush RRD @@ -145,27 +145,27 @@ sub handle_TERM { ### # Write In File ### - if (open(FILE, '>> ' . $self->{"main_perfdata_file"} . "_" . $self->{'num_pool'} . ".bckp")) { - foreach my $id (keys %{$self->{"cache_services_failed"}}) { - foreach (@{$self->{"cache_services_failed"}->{$id}}) { + if (open(FILE, '>> ' . $self->{main_perfdata_file} . "_" . $self->{num_pool} . ".bckp")) { + foreach my $id (keys %{$self->{cache_services_failed}}) { + foreach (@{$self->{cache_services_failed}->{$id}}) { print FILE join("\t", @$_) . "\n"; } } # Rename - foreach my $id (keys %{$self->{"cache_services_rename"}}) { - foreach (@{$self->{"cache_services_rename"}->{$id}}) { + foreach my $id (keys %{$self->{cache_services_rename}}) { + foreach (@{$self->{cache_services_rename}->{$id}}) { print FILE join("\t", @$_) . "\n"; } } ### Try to read pipe - my @rh_set = $self->{'read_select'}->can_read(1); + my @rh_set = $self->{read_select}->can_read(1); if (scalar(@rh_set) > 0) { foreach my $rh (@rh_set) { my $read_done = 0; - while ((my ($status_line, $readline) = centreon::common::misc::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + while ((my ($status_line, $readline) = centreon::common::misc::get_line_pipe($rh, \@{$self->{save_read}}, \$read_done))) { last if ($status_line <= 0); if ($readline =~ /^UPDATE/) { $readline =~ s/^UPDATE\t//; @@ -176,15 +176,15 @@ sub handle_TERM { } close FILE; } else { - $self->{"logger"}->writeLogError("Cannot open " . $self->{"main_perfdata_file"} . "_" . $self->{'num_pool'} . ".bckp file : $!"); + $self->{"logger"}->writeLogError("Cannot open " . $self->{main_perfdata_file} . "_" . $self->{num_pool} . ".bckp file : $!"); } ### # Check Child ### my $kill_or_not = 1; - for (my $i = 0; $i < $self->{"TIMEOUT"}; $i++) { - if (!defined($self->{"current_pid"})) { + for (my $i = 0; $i < $self->{TIMEOUT}; $i++) { + if (!defined($self->{current_pid})) { $kill_or_not = 0; last; } @@ -192,8 +192,8 @@ sub handle_TERM { } if ($kill_or_not == 1) { - $self->{'logger'}->writeLogInfo("Send -KILL signal to rebuild process.."); - kill('KILL', $self->{"current_pid"}); + $self->{logger}->writeLogInfo("Send -KILL signal to rebuild process.."); + kill('KILL', $self->{current_pid}); } } @@ -202,14 +202,14 @@ sub handle_CHLD { my $child_pid; my $exit_code; - $self->{'logger'}->writeLogInfo("Received SIGCHLD..."); - $self->{"current_pid"} = undef; - if ($self->{"rename_rebuild_wait"} == 1) { - my ($new_host_name, $new_service_description) = split(';', $self->{"rename_old_new"}->{$self->{"rebuild_key"}}); - $self->force_flush_rrd($self->{"rebuild_key"}); - delete $self->{"cache_service"}->{$self->{"rebuild_key"}}; - delete $self->{"cache_services_failed"}->{$self->{"rebuild_key"}}; - delete $self->{"rename_old_new"}->{$self->{"rebuild_key"}}; + $self->{logger}->writeLogInfo("Received SIGCHLD..."); + $self->{current_pid} = undef; + if ($self->{rename_rebuild_wait} == 1) { + my ($new_host_name, $new_service_description) = split(';', $self->{rename_old_new}->{$self->{rebuild_key}}); + $self->force_flush_rrd($self->{rebuild_key}); + delete $self->{cache_service}->{$self->{rebuild_key}}; + delete $self->{cache_services_failed}->{$self->{rebuild_key}}; + delete $self->{rename_old_new}->{$self->{rebuild_key}}; $self->send_rename_finish($new_host_name, $new_service_description); } $self->rebuild_finish(); @@ -220,15 +220,15 @@ sub handle_CHLD { } sub class_handle_TERM { - foreach (keys %{$handlers{'TERM'}}) { - &{$handlers{'TERM'}->{$_}}(); + foreach (keys %{$handlers{TERM}}) { + &{$handlers{TERM}->{$_}}(); } exit(0); } sub class_handle_CHLD { - foreach (keys %{$handlers{'CHLD'}}) { - &{$handlers{'CHLD'}->{$_}}(); + foreach (keys %{$handlers{CHLD}}) { + &{$handlers{CHLD}->{$_}}(); } } @@ -267,21 +267,21 @@ sub add_data_mysql { my $self = shift; my ($metric_id, $ctime, $value) = @_; - $self->{"group_databin_stmt"} .= $self->{"group_databin_append"} . "('$metric_id', '$ctime', '$value')"; - $self->{"group_databin_append"} = ", "; - $self->{"group_databin_total"}++; + $self->{group_databin_stmt} .= $self->{group_databin_append} . "('$metric_id', '$ctime', '$value')"; + $self->{group_databin_append} = ", "; + $self->{group_databin_total}++; } sub force_flush_rrd { my $self = shift; my ($key) = @_; - if (defined($self->{"cache_service"}->{$key})) { - foreach (keys %{$self->{"cache_service"}->{$key}->{'metrics'}}) { - $self->{'rrd'}->flush_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$_}->{'metric_id'}); + if (defined($self->{cache_service}->{$key})) { + foreach (keys %{$self->{cache_service}->{$key}->{metrics}}) { + $self->{rrd}->flush_metric($self->{cache_service}->{$key}->{metrics}->{$_}->{metric_id}); } - $self->{'rrd'}->flush_status($self->{"cache_service"}->{$key}->{'index_id'}); + $self->{rrd}->flush_status($self->{cache_service}->{$key}->{index_id}); } } @@ -289,30 +289,30 @@ sub flush_mysql { my $self = shift; my ($force) = @_; - return 0 if ($self->{"rebuild_progress"} == 1 && (!defined($force) || $force == 0)); - if ((defined($force) && $force == 1 && $self->{"group_databin_total"} > 0) || $self->{"group_databin_total"} > $self->{"group_databin_max"}) { - my $rq = "INSERT INTO `data_bin` (`id_metric`, `ctime`, `value`) VALUES " . $self->{"group_databin_stmt"}; - my ($status, $stmt) = $self->{'dbcentstorage'}->query($rq); - $self->{"group_databin_total"} = 0; - $self->{"group_databin_append"} = ""; - $self->{"group_databin_stmt"} = ""; + return 0 if ($self->{rebuild_progress} == 1 && (!defined($force) || $force == 0)); + if ((defined($force) && $force == 1 && $self->{group_databin_total} > 0) || $self->{group_databin_total} > $self->{group_databin_max}) { + my $rq = "INSERT INTO `data_bin` (`id_metric`, `ctime`, `value`) VALUES " . $self->{group_databin_stmt}; + my ($status, $stmt) = $self->{dbcentstorage}->query($rq); + $self->{group_databin_total} = 0; + $self->{group_databin_append} = ""; + $self->{group_databin_stmt} = ""; } } sub flush_failed { my $self = shift; - if (time() > ($self->{"last_check_failed"} + $self->{"check_failed_every"})) { + if (time() > ($self->{last_check_failed} + $self->{check_failed_every})) { # Need to reconnect (maybe a gone away. So we try) - $self->{'dbcentreon'}->disconnect(); - $self->{'dbcentreon'}->connect(); + $self->{dbcentreon}->disconnect(); + $self->{dbcentreon}->connect(); - $self->{'logger'}->writeLogInfo("Begin Cache Services Failed"); - foreach my $id (keys %{$self->{"cache_services_failed"}}) { - next if ($self->{"rebuild_progress"} == 1 && $id == $self->{"rebuild_key"}); + $self->{logger}->writeLogInfo("Begin Cache Services Failed"); + foreach my $id (keys %{$self->{cache_services_failed}}) { + next if ($self->{rebuild_progress} == 1 && $id == $self->{rebuild_key}); my @tmp_ar = (); my $lerror = 0; - foreach (@{$self->{"cache_services_failed"}->{$id}}) { + foreach (@{$self->{cache_services_failed}->{$id}}) { if ($lerror == 0 && $self->update(1, @$_) != 0) { push @tmp_ar, \@$_; $lerror = 1; @@ -321,12 +321,12 @@ sub flush_failed { } } if (scalar(@tmp_ar) != 0) { - @{$self->{"cache_services_failed"}->{$id}} = @tmp_ar; + @{$self->{cache_services_failed}->{$id}} = @tmp_ar; } else { - delete $self->{"cache_services_failed"}->{$id}; + delete $self->{cache_services_failed}->{$id}; } } - $self->{"last_check_failed"} = time(); + $self->{last_check_failed} = time(); } } @@ -421,8 +421,8 @@ sub send_rename_command { my ($old_host_name, $old_service_description, $new_host_name, $new_service_description) = @_; $self->{logger}->writeLogInfo("Hostname/Servicename changed had been detected " . $old_host_name . "/" . $old_service_description); - my $fh = $self->{'pipe_write'}; - print $fh "RENAMECLEAN\t" . $old_host_name . "\t" . $old_service_description . "\t" . $new_host_name . "\t" . $new_service_description . "\n"; + my $fh = $self->{pipe_write}; + print $fh "RENAMECLEAN\t" . $old_host_name . "\t" . $old_service_description . "\t" . $new_host_name . "\t" . $new_service_description . "\n"; } sub create_service { @@ -431,56 +431,56 @@ sub create_service { my ($status, $stmt); if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `storage_type`, `host_name`, `service_description`, `rrd_retention` FROM `index_data` WHERE `host_name` = " . $self->{'dbcentstorage'}->quote($host_name) . " AND `service_description` = " . $self->{'dbcentstorage'}->quote($service_description) . " LIMIT 1"); + ($status, $stmt) = $self->{dbcentstorage}->query("SELECT `id`, `storage_type`, `host_name`, `service_description`, `rrd_retention` FROM `index_data` WHERE `host_name` = " . $self->{dbcentstorage}->quote($host_name) . " AND `service_description` = " . $self->{dbcentstorage}->quote($service_description) . " LIMIT 1"); } else { - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT `id`, `storage_type`, `host_name`, `service_description`, `rrd_retention` FROM `index_data` WHERE `host_id` = " . $host_id . " AND `service_id` = " . $service_id . " LIMIT 1"); + ($status, $stmt) = $self->{dbcentstorage}->query("SELECT `id`, `storage_type`, `host_name`, `service_description`, `rrd_retention` FROM `index_data` WHERE `host_id` = " . $host_id . " AND `service_id` = " . $service_id . " LIMIT 1"); } return -1 if ($status == -1); my $data = $stmt->fetchrow_hashref(); - if (defined($data) && ($data->{'host_name'} ne $host_name || $data->{'service_description'} ne $service_description)) { - ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE `index_data` SET `host_name` = " . $self->{'dbcentstorage'}->quote($host_name) . ", `service_description` = " . $self->{'dbcentreon'}->quote($service_description) . " WHERE id = " . $data->{'id'}); + if (defined($data) && ($data->{host_name} ne $host_name || $data->{service_description} ne $service_description)) { + ($status, $stmt) = $self->{dbcentstorage}->query("UPDATE `index_data` SET `host_name` = " . $self->{dbcentstorage}->quote($host_name) . ", `service_description` = " . $self->{dbcentreon}->quote($service_description) . " WHERE id = " . $data->{'id'}); if ($status != -1) { - $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = int($data->{'storage_type'}); - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $data->{'id'}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; + $self->{cache_service}->{$host_name . ";" . $service_description} = {}; + $self->{cache_service}->{$host_name . ";" . $service_description}->{metrics} = {}; + $self->{cache_service}->{$host_name . ";" . $service_description}->{service_id} = $service_id; + $self->{cache_service}->{$host_name . ";" . $service_description}->{host_id} = $host_id; + $self->{cache_service}->{$host_name . ";" . $service_description}->{storage_type} = int($data->{storage_type}); + $self->{cache_service}->{$host_name . ";" . $service_description}->{index_id} = $data->{id}; + $self->{cache_service}->{$host_name . ";" . $service_description}->{check_interval} = $interval; + $self->{cache_service}->{$host_name . ";" . $service_description}->{rebuild} = 0; + $self->{cache_service}->{$host_name . ";" . $service_description}->{rrd_retention} = (defined($data->{rrd_retention})) ? $data->{rrd_retention} : -1; # Send command to clean cache - $self->send_rename_command($data->{'host_name'}, $data->{'service_description'}, $host_name, $service_description); + $self->send_rename_command($data->{host_name}, $data->{service_description}, $host_name, $service_description); return -2; } - } elsif (defined($data) && ($data->{'host_name'} eq $host_name || $data->{'service_description'} eq $service_description)) { + } elsif (defined($data) && ($data->{host_name} eq $host_name || $data->{service_description} eq $service_description)) { # same name but exist already - $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = int($data->{'storage_type'}); - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $data->{'id'}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; + $self->{cache_service}->{$host_name . ";" . $service_description} = {}; + $self->{cache_service}->{$host_name . ";" . $service_description}->{metrics} = {}; + $self->{cache_service}->{$host_name . ";" . $service_description}->{service_id} = $service_id; + $self->{cache_service}->{$host_name . ";" . $service_description}->{host_id} = $host_id; + $self->{cache_service}->{$host_name . ";" . $service_description}->{storage_type} = int($data->{storage_type}); + $self->{cache_service}->{$host_name . ";" . $service_description}->{index_id} = $data->{id}; + $self->{cache_service}->{$host_name . ";" . $service_description}->{check_interval} = $interval; + $self->{cache_service}->{$host_name . ";" . $service_description}->{rebuild} = 0; + $self->{cache_service}->{$host_name . ";" . $service_description}->{rrd_retention} = (defined($data->{rrd_retention})) ? $data->{rrd_retention} : -1; } else { # create if ($host_name =~ /_Module_([a-zA-Z0-9]*)/) { - ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `index_data` (`host_name`, `service_description`, `host_id`, `service_id`, `special`, `storage_type`) VALUES (" . $self->{'dbcentstorage'}->quote($host_name) . ", " . $self->{'dbcentstorage'}->quote($service_description) . ", " . $host_id . ", " . $service_id . ", '1', '" . $self->{'storage_type'} . "')"); + ($status, $stmt) = $self->{dbcentstorage}->query("INSERT INTO `index_data` (`host_name`, `service_description`, `host_id`, `service_id`, `special`, `storage_type`) VALUES (" . $self->{dbcentstorage}->quote($host_name) . ", " . $self->{dbcentstorage}->quote($service_description) . ", " . $host_id . ", " . $service_id . ", '1', '" . $self->{storage_type} . "')"); } else { - ($status, $stmt) = $self->{'dbcentstorage'}->query("INSERT INTO `index_data` (`host_name`, `service_description`, `host_id`, `service_id`, `storage_type`) VALUES (" . $self->{'dbcentstorage'}->quote($host_name) . ", " . $self->{'dbcentstorage'}->quote($service_description) . ", " . $host_id . ", " . $service_id . ", '" . $self->{'storage_type'} . "')"); + ($status, $stmt) = $self->{dbcentstorage}->query("INSERT INTO `index_data` (`host_name`, `service_description`, `host_id`, `service_id`, `storage_type`) VALUES (" . $self->{dbcentstorage}->quote($host_name) . ", " . $self->{dbcentstorage}->quote($service_description) . ", " . $host_id . ", " . $service_id . ", '" . $self->{storage_type} . "')"); } if ($status != -1) { - $self->{"cache_service"}->{$host_name . ";" . $service_description} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'metrics'} = {}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'service_id'} = $service_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'host_id'} = $host_id; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'storage_type'} = $self->{'storage_type'}; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'index_id'} = $self->{'dbcentstorage'}->last_insert_id(); - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'check_interval'} = $interval; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rebuild'} = 0; - $self->{"cache_service"}->{$host_name . ";" . $service_description}->{'rrd_retention'} = -1; + $self->{cache_service}->{$host_name . ";" . $service_description} = {}; + $self->{cache_service}->{$host_name . ";" . $service_description}->{metrics} = {}; + $self->{cache_service}->{$host_name . ";" . $service_description}->{service_id} = $service_id; + $self->{cache_service}->{$host_name . ";" . $service_description}->{host_id} = $host_id; + $self->{cache_service}->{$host_name . ";" . $service_description}->{storage_type} = $self->{storage_type}; + $self->{cache_service}->{$host_name . ";" . $service_description}->{index_id} = $self->{dbcentstorage}->last_insert_id(); + $self->{cache_service}->{$host_name . ";" . $service_description}->{check_interval} = $interval; + $self->{cache_service}->{$host_name . ";" . $service_description}->{rebuild} = 0; + $self->{cache_service}->{$host_name . ";" . $service_description}->{rrd_retention} = -1; } } @@ -491,13 +491,13 @@ sub get_centstorage_information { my $self = shift; my ($len_storage_rrd, $rrd_metrics_path, $rrd_status_path, $storage_type); - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT len_storage_rrd, RRDdatabase_path, RRDdatabase_status_path, storage_type FROM config"); + my ($status, $stmt) = $self->{dbcentstorage}->query("SELECT len_storage_rrd, RRDdatabase_path, RRDdatabase_status_path, storage_type FROM config"); my $data = $stmt->fetchrow_hashref(); if (defined($data)) { - $len_storage_rrd = int($data->{'len_storage_rrd'}); - $rrd_metrics_path = $data->{'RRDdatabase_path'}; - $rrd_status_path = $data->{'RRDdatabase_status_path'}; - $storage_type = int($data->{'storage_type'}); + $len_storage_rrd = int($data->{len_storage_rrd}); + $rrd_metrics_path = $data->{RRDdatabase_path}; + $rrd_status_path = $data->{RRDdatabase_status_path}; + $storage_type = int($data->{storage_type}); } return ($status, $len_storage_rrd, $rrd_metrics_path, $rrd_status_path, $storage_type); } @@ -506,10 +506,10 @@ sub get_centreon_intervaltime { my $self = shift; my $interval = 60; - my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT `value` AS interval_length FROM options WHERE `key` = 'interval_length'"); + my ($status, $stmt) = $self->{dbcentreon}->query("SELECT `value` AS interval_length FROM options WHERE `key` = 'interval_length'"); my $data = $stmt->fetchrow_hashref(); if (defined($data)) { - $interval = $data->{'interval_length'}; + $interval = $data->{interval_length}; } return (0, $interval); } @@ -527,7 +527,7 @@ sub trim { sub skip_chars { my $self = shift; - $self->{"perfdata_pos"}++ while ($self->{"perfdata_pos"} < $self->{"perfdata_size"} && (${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] =~ /$_[0]/)); + $self->{perfdata_pos}++ while ($self->{perfdata_pos} < $self->{perfdata_size} && (${$self->{perfdata_chars}}[$self->{perfdata_pos}] =~ /$_[0]/)); } sub continue_to { @@ -535,23 +535,23 @@ sub continue_to { my ($forbidden, $stop1, $not_stop_after) = @_; my $value = ""; - while ($self->{"perfdata_pos"} < $self->{"perfdata_size"}) { - if (defined($forbidden) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] =~ /$forbidden/) { + while ($self->{perfdata_pos} < $self->{perfdata_size}) { + if (defined($forbidden) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] =~ /$forbidden/) { return undef; } - if (${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] =~ /$stop1/) { + if (${$self->{perfdata_chars}}[$self->{perfdata_pos}] =~ /$stop1/) { if (!defined($not_stop_after)) { return $value; } - if (!($self->{"perfdata_pos"} + 1 < $self->{"perfdata_size"} && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"} + 1] =~ /$not_stop_after/)) { - $self->{"perfdata_pos"}++; + if (!($self->{perfdata_pos} + 1 < $self->{perfdata_size} && ${$self->{perfdata_chars}}[$self->{perfdata_pos} + 1] =~ /$not_stop_after/)) { + $self->{perfdata_pos}++; return $value; } - $self->{"perfdata_pos"}++; + $self->{perfdata_pos}++; } - $value .= ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]; - $self->{"perfdata_pos"}++; + $value .= ${$self->{perfdata_chars}}[$self->{perfdata_pos}]; + $self->{perfdata_pos}++; } return $value; @@ -561,13 +561,13 @@ sub parse_label { my $self = shift; my $label; - if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "'") { - $self->{"perfdata_pos"}++; + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq "'") { + $self->{perfdata_pos}++; $label = $self->continue_to(undef, "'", "'"); } else { $label = $self->continue_to("[ \t]", "="); } - $self->{"perfdata_pos"}++; + $self->{perfdata_pos}++; return $label; } @@ -579,9 +579,9 @@ sub parse_value { my $value = ""; my $neg = 1; - if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "-") { + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq "-") { $neg = -1; - $self->{"perfdata_pos"}++; + $self->{perfdata_pos}++; } $value = $self->continue_to(undef, "[^0-9\.,]"); @@ -618,18 +618,18 @@ sub parse_threshold { my $value_end = ""; my $global_status = 1; - if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "@") { + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq "@") { $arobase = 1; - $self->{"perfdata_pos"}++; + $self->{perfdata_pos}++; } - if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "~") { + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq "~") { $infinite_neg = 1; - $self->{"perfdata_pos"}++; + $self->{perfdata_pos}++; } else { - if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "-") { + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq "-") { $neg = -1; - $self->{"perfdata_pos"}++; + $self->{perfdata_pos}++; } $value_tmp = $self->continue_to(undef, "[^0-9\.,]"); if (defined($value_tmp) && $value_tmp ne "") { @@ -639,17 +639,17 @@ sub parse_threshold { $neg = 1; } - if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq ":") { + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq ":") { if ($value_tmp ne "") { $value_start = $value_tmp; } else { $value_start = 0; } - $self->{"perfdata_pos"}++; + $self->{perfdata_pos}++; - if (defined(${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}]) && ${$self->{"perfdata_chars"}}[$self->{"perfdata_pos"}] eq "-") { + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq "-") { $neg = -1; - $self->{"perfdata_pos"}++; + $self->{perfdata_pos}++; } $value_end = $self->continue_to(undef, "[^0-9\.,]"); if (defined($value_tmp) && $value_end ne "") { @@ -684,22 +684,22 @@ sub get_perfdata { my $self = shift; my ($counter_type, $perf_label, $perf_value, $perf_unit, $perf_warn, $perf_crit, $perf_min, $perf_max); - if (!defined($self->{'service_perfdata'}) || $self->{"perfdata_pos"} >= $self->{"perfdata_size"}) { + if (!defined($self->{service_perfdata}) || $self->{perfdata_pos} >= $self->{perfdata_size}) { return 0; } $self->skip_chars("[ \t]"); $perf_label = $self->parse_label(); if (!defined($perf_label) || $perf_label eq '') { - $self->{"logger"}->writeLogError("Wrong perfdata format: " . $self->{'service_perfdata'}); - return -1 if ($self->{'perfdata_parser_stop'} == 1); + $self->{logger}->writeLogError("Wrong perfdata format: " . $self->{service_perfdata}); + return -1 if ($self->{perfdata_parser_stop} == 1); return 1; } ($perf_value, $perf_unit) = $self->parse_value(1); if (!defined($perf_value) || $perf_value eq '') { - $self->{"logger"}->writeLogError("Wrong perfdata format: " . $self->{'service_perfdata'}); - return -1 if ($self->{'perfdata_parser_stop'} == 1); + $self->{logger}->writeLogError("Wrong perfdata format: " . $self->{service_perfdata}); + return -1 if ($self->{perfdata_parser_stop} == 1); return 1; } @@ -714,8 +714,8 @@ sub get_perfdata { $counter_type = $1; $perf_label = $2; if (!defined($perf_label) || $perf_label eq '') { - $self->{"logger"}->writeLogError("Wrong perfdata format: " . $self->{'service_perfdata'}); - return -1 if ($self->{'perfdata_parser_stop'} == 1); + $self->{logger}->writeLogError("Wrong perfdata format: " . $self->{service_perfdata}); + return -1 if ($self->{perfdata_parser_stop} == 1); return 1; } } @@ -752,12 +752,12 @@ sub get_perfdata { sub init_perfdata { my $self = shift; - if (!defined($self->{'service_perfdata'})) { + if (!defined($self->{service_perfdata})) { return ; } - @{$self->{"perfdata_chars"}} = split //, $self->trim($self->{'service_perfdata'}); - $self->{"perfdata_pos"} = 0; - $self->{"perfdata_size"} = scalar(@{$self->{"perfdata_chars"}}); + @{$self->{perfdata_chars}} = split //, $self->trim($self->{service_perfdata}); + $self->{perfdata_pos} = 0; + $self->{perfdata_size} = scalar(@{$self->{perfdata_chars}}); } ###################################################### @@ -766,17 +766,17 @@ sub cache_update_service_index_data { my $self = shift; my ($key) = @_; - my ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT rrd_retention FROM index_data WHERE id = " . $self->{"cache_service"}->{$key}->{'index_id'}); - if ($status == -1) { - $self->{'logger'}->writeLogError("Cannot get index_data"); - return -1; - } + my ($status, $stmt) = $self->{dbcentstorage}->query("SELECT rrd_retention FROM index_data WHERE id = " . $self->{cache_service}->{$key}->{index_id}); + if ($status == -1) { + $self->{logger}->writeLogError("Cannot get index_data"); + return -1; + } my $data = $stmt->fetchrow_hashref(); if (!defined($data)) { - $self->{'logger'}->writeLogError("Can't find index_data"); + $self->{logger}->writeLogError("Can't find index_data"); return -1; } - $self->{"cache_service"}->{$key}->{'rrd_retention'} = (defined($data->{'rrd_retention'})) ? $data->{'rrd_retention'} : -1; + $self->{cache_service}->{$key}->{rrd_retention} = (defined($data->{rrd_retention})) ? $data->{rrd_retention} : -1; return 0; } @@ -796,32 +796,32 @@ sub get_host_service_ids { $service_register = "'2'"; } # Get Host_Id - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT `host_id` FROM `host` WHERE `host_name` = " . $self->{'dbcentreon'}->quote($host_name) . " AND `host_register` = '$host_register' LIMIT 1"); + ($status, $stmt) = $self->{dbcentreon}->query("SELECT `host_id` FROM `host` WHERE `host_name` = " . $self->{dbcentreon}->quote($host_name) . " AND `host_register` = '$host_register' LIMIT 1"); return -1 if ($status); $data = $stmt->fetchrow_hashref(); if (!defined($data)) { - $self->{'logger'}->writeLogError("Can't find 'host_id' $host_name"); + $self->{logger}->writeLogError("Can't find 'host_id' $host_name"); return -2; } - $host_id = $data->{'host_id'}; + $host_id = $data->{host_id}; - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM service, host_service_relation hsr WHERE hsr.host_host_id = '" . $host_id . "' AND hsr.service_service_id = service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN (" . $service_register . ") LIMIT 1"); + ($status, $stmt) = $self->{dbcentreon}->query("SELECT service_id FROM service, host_service_relation hsr WHERE hsr.host_host_id = '" . $host_id . "' AND hsr.service_service_id = service_id AND service_description = " . $self->{dbcentreon}->quote($service_description) . " AND `service_register` IN (" . $service_register . ") LIMIT 1"); return -1 if ($status == -1); $data = $stmt->fetchrow_hashref(); if (!defined($data)) { # Search in service By hostgroup - ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_id FROM hostgroup_relation hgr, service, host_service_relation hsr WHERE hgr.host_host_id = '" . $host_id . "' AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id AND service_id = hsr.service_service_id AND service_description = " . $self->{'dbcentreon'}->quote($service_description) . " AND `service_register` IN (" . $service_register . ") LIMIT 1"); + ($status, $stmt) = $self->{dbcentreon}->query("SELECT service_id FROM hostgroup_relation hgr, service, host_service_relation hsr WHERE hgr.host_host_id = '" . $host_id . "' AND hsr.hostgroup_hg_id = hgr.hostgroup_hg_id AND service_id = hsr.service_service_id AND service_description = " . $self->{dbcentreon}->quote($service_description) . " AND `service_register` IN (" . $service_register . ") LIMIT 1"); return -1 if ($status == -1); $data = $stmt->fetchrow_hashref(); } if (!defined($data)) { - $self->{'logger'}->writeLogError("Can't find 'service_id' for $host_name/$service_description"); + $self->{logger}->writeLogError("Can't find 'service_id' for $host_name/$service_description"); return -2; } - $service_id = $data->{'service_id'}; + $service_id = $data->{service_id}; return (0, $host_id, $service_id); } @@ -836,16 +836,16 @@ sub get_check_interval_normal { $rotation_check = {} if (!defined($rotation_check)); return (0, 5) if (defined($rotation_check->{$service_id})); - my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT service_normal_check_interval, service_template_model_stm_id FROM service WHERE service_id = " . $service_id); + my ($status, $stmt) = $self->{dbcentreon}->query("SELECT service_normal_check_interval, service_template_model_stm_id FROM service WHERE service_id = " . $service_id); return -1 if ($status == -1); my $data = $stmt->fetchrow_hashref(); return (0, 5) if (!defined($data)); - if (!defined($data->{'service_normal_check_interval'}) || $data->{'service_normal_check_interval'} eq '') { + if (!defined($data->{service_normal_check_interval}) || $data->{service_normal_check_interval} eq '') { $rotation_check->{$service_id} = 1; - $self->get_check_interval_normal($data->{'service_template_model_stm_id'}, $rotation_check); + $self->get_check_interval_normal($data->{service_template_model_stm_id}, $rotation_check); } else { - return (0, $data->{'service_normal_check_interval'}); + return (0, $data->{service_normal_check_interval}); } } @@ -856,18 +856,18 @@ sub get_check_interval_module { my $interval = 1; $service_description =~ /([a-zA-Z0-9]*)_([0-9]*)/; if ($1 eq "meta"){ - my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT normal_check_interval FROM meta_service WHERE meta_id = '" . $2 . "' LIMIT 1"); + my ($status, $stmt) = $self->{dbcentreon}->query("SELECT normal_check_interval FROM meta_service WHERE meta_id = '" . $2 . "' LIMIT 1"); return -1 if ($status == -1); my $data = $stmt->fetchrow_hashref(); - if (defined($data->{'normal_check_interval'})){ - $interval = $data->{'normal_check_interval'}; + if (defined($data->{normal_check_interval})){ + $interval = $data->{normal_check_interval}; } } elsif ($1 eq "ba") { - my ($status, $stmt) = $self->{'dbcentreon'}->query("SELECT normal_check_interval FROM mod_bam WHERE ba_id = '" . $2 . "' LIMIT 1"); + my ($status, $stmt) = $self->{dbcentreon}->query("SELECT normal_check_interval FROM mod_bam WHERE ba_id = '" . $2 . "' LIMIT 1"); return -1 if ($status == -1); my $data = $stmt->fetchrow_hashref(); - if (defined($data->{'normal_check_interval'})) { - $interval = $data->{'normal_check_interval'}; + if (defined($data->{normal_check_interval})) { + $interval = $data->{normal_check_interval}; } } return (0, $interval); @@ -893,11 +893,11 @@ sub get_information_service { # Need to identify it my ($status, $host_id, $service_id) = $self->get_host_service_ids($host_name, $service_description); if ($status != 0) { - if ($status == -2 && $self->{"skip_if_no_ids"} == 1) { + if ($status == -2 && $self->{skip_if_no_ids} == 1) { return 1; } if (!defined($no_cache) || $no_cache == 0) { - push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + push @{$self->{cache_services_failed}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{service_perfdata}]; } return 1; } @@ -906,7 +906,7 @@ sub get_information_service { ($status, my $interval) = $self->get_check_interval($host_name, $service_description, $service_id); if ($status != 0) { if (!defined($no_cache) || $no_cache == 0) { - push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + push @{$self->{cache_services_failed}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{service_perfdata}]; } return 1; } @@ -915,10 +915,10 @@ sub get_information_service { $status = $self->create_service($host_id, $service_id, $interval * $self->{"interval_time"}, $host_name, $service_description); if ($status != 0) { if ($status == -1 && (!defined($no_cache) || $no_cache == 0)) { - push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + push @{$self->{cache_services_failed}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{service_perfdata}]; } if ($status == -2 && (!defined($no_cache) || $no_cache == 0)) { - push @{$self->{"cache_services_rename"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + push @{$self->{cache_services_rename}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{service_perfdata}]; } return 1; } @@ -929,79 +929,79 @@ sub get_information_service { sub update { my $self = shift; my ($play_failed, $timestamp, $host_name, $service_description, $last_service_state, $service_state); - ($play_failed, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}) = @_; + ($play_failed, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{service_perfdata}) = @_; if ($timestamp !~ /^[0-9]+$/ || $timestamp > (time() + 86400)) { - $self->{'logger'}->writeLogError("Unknown timestamp format or in future: $timestamp"); + $self->{logger}->writeLogError("Unknown timestamp format or in future: $timestamp"); return 0; } # Not good number field if (!defined($service_state)) { - $self->{'logger'}->writeLogError("Line not well formed"); + $self->{logger}->writeLogError("Line not well formed"); return 0; } my $key_service = $host_name . ";" . $service_description; # We quit because we have failed to retest before || rebuild - if ((defined($self->{"cache_services_failed"}->{$key_service}) && $play_failed == 0) || - defined($self->{"cache_service"}->{$key_service}) && $self->{"cache_service"}->{$key_service}->{'rebuild'} == 1) { - push @{$self->{"cache_services_failed"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + if ((defined($self->{cache_services_failed}->{$key_service}) && $play_failed == 0) || + defined($self->{cache_service}->{$key_service}) && $self->{cache_service}->{$key_service}->{rebuild} == 1) { + push @{$self->{cache_services_failed}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{service_perfdata}]; return 1; } # We quit because we wait rename finish - if (defined($self->{"cache_services_rename"}->{$key_service}) && $play_failed == 0) { - push @{$self->{"cache_services_rename"}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{'service_perfdata'}]; + if (defined($self->{cache_services_rename}->{$key_service}) && $play_failed == 0) { + push @{$self->{cache_services_rename}->{$key_service}}, [$timestamp, $host_name, $service_description, $last_service_state, $service_state, $self->{service_perfdata}]; return 1; } - if (!defined($self->{"cache_service"}->{$key_service})) { + if (!defined($self->{cache_service}->{$key_service})) { my $status = $self->get_information_service($key_service, $timestamp, $host_name, $service_description, $last_service_state, $service_state, $play_failed); return 1 if ($status == 1); } $self->init_perfdata(); while (($self->get_perfdata()) > 0) { - if (!defined($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}})) { + if (!defined($self->{cache_service}->{$key_service}->{metrics}->{$self->{metric_name}})) { # Need to identify metrics # if failed, we go 'next' - my $status = $self->create_metric($self->{"cache_service"}->{$key_service}->{'index_id'}, \$self->{"cache_service"}->{$key_service}->{'metrics'}, $self->{"metric_name"}); + my $status = $self->create_metric($self->{cache_service}->{$key_service}->{index_id}, \$self->{cache_service}->{$key_service}->{metrics}, $self->{metric_name}); next if ($status == -1); } - $self->check_update_extra_metric(\$self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}); + $self->check_update_extra_metric(\$self->{cache_service}->{$key_service}->{metrics}->{$self->{metric_name}}); ### # Check data source type: DB ### - if ($self->{"cache_service"}->{$key_service}->{'storage_type'} == 2) { + if ($self->{cache_service}->{$key_service}->{storage_type} == 2) { # Do DataBin Add - $self->add_data_mysql($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'metric_id'}, + $self->add_data_mysql($self->{cache_service}->{$key_service}->{metrics}->{$self->{metric_name}}->{metric_id}, $timestamp, - $self->{"metric_value"}); + $self->{metric_value}); } ### # Do RRDs: metric ### - $self->{"rrd"}->add_metric($self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'metric_id'}, - $self->{"metric_name"}, - $self->{"cache_service"}->{$key_service}->{'check_interval'}, - $self->{"cache_service"}->{$key_service}->{'metrics'}->{$self->{"metric_name"}}->{'data_source_type'}, + $self->{rrd}->add_metric($self->{cache_service}->{$key_service}->{metrics}->{$self->{metric_name}}->{metric_id}, + $self->{metric_name}, + $self->{cache_service}->{$key_service}->{check_interval}, + $self->{cache_service}->{$key_service}->{metrics}->{$self->{metric_name}}->{data_source_type}, $timestamp, - $self->{"metric_value"}, - $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); + $self->{metric_value}, + $self->{cache_service}->{$key_service}->{rrd_retention}); } ### # Do RRD Status ### - if ($self->{"do_rrd_status"} == 1) { - $self->{"rrd"}->add_status($self->{"cache_service"}->{$key_service}->{'index_id'}, - $self->{"cache_service"}->{$key_service}->{'check_interval'}, + if ($self->{do_rrd_status} == 1) { + $self->{rrd}->add_status($self->{cache_service}->{$key_service}->{index_id}, + $self->{cache_service}->{$key_service}->{check_interval}, $timestamp, $service_state, - $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); + $self->{cache_service}->{$key_service}->{rrd_retention}); } return 0; @@ -1010,11 +1010,11 @@ sub update { sub rebuild_finish { my $self = shift; - $self->{"rebuild_progress"} = 0; - if (defined($self->{"cache_service"}->{$self->{"rebuild_key"}})) { - $self->{"cache_service"}->{$self->{"rebuild_key"}}->{'rebuild'} = 0; + $self->{rebuild_progress} = 0; + if (defined($self->{cache_service}->{$self->{rebuild_key}})) { + $self->{cache_service}->{$self->{rebuild_key}}->{rebuild} = 0; } - my $fh = $self->{'pipe_write'}; + my $fh = $self->{pipe_write}; print $fh "REBUILDFINISH\n"; } @@ -1024,14 +1024,14 @@ sub rebuild { my $status; my $current_interval; - $self->{"rebuild_progress"} = 1; + $self->{rebuild_progress} = 1; if (!defined($host_name)) { # A rebuild is in progress return 0; } my $key_service = $host_name . ";" . $service_description; - $self->{"rebuild_key"} = $key_service; + $self->{rebuild_key} = $key_service; ###### # To do the rebuild @@ -1042,10 +1042,10 @@ sub rebuild { # Maybe we have to create cache service and metrics # We'll get information for rebuild fork # - if (!defined($self->{"cache_service"}->{$key_service})) { + if (!defined($self->{cache_service}->{$key_service})) { $status = $self->get_information_service($key_service, undef, $host_name, $service_description, undef, undef, 1); if ($status == 1) { - $self->{'logger'}->writeLogError("rebuild cannot get information service"); + $self->{logger}->writeLogError("rebuild cannot get information service"); $self->rebuild_finish(); return ; } @@ -1053,13 +1053,13 @@ sub rebuild { ###### # Update Interval # - ($status, $current_interval) = $self->get_check_interval($host_name, $service_description, $self->{"cache_service"}->{$key_service}->{'service_id'}); + ($status, $current_interval) = $self->get_check_interval($host_name, $service_description, $self->{cache_service}->{$key_service}->{service_id}); if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot get interval service"); + $self->{logger}->writeLogError("rebuild cannot get interval service"); $self->rebuild_finish(); return ; } - $self->{"cache_service"}->{$key_service}->{'check_interval'} = $current_interval * $self->{"interval_time"}; + $self->{cache_service}->{$key_service}->{check_interval} = $current_interval * $self->{interval_time}; ##### # Update cache to get 'rrd_retention' @@ -1069,53 +1069,53 @@ sub rebuild { return ; } } - $self->{"cache_service"}->{$key_service}->{'rebuild'} = 1; + $self->{cache_service}->{$key_service}->{rebuild} = 1; ###### # Get List Metrics and Flush if needed # - ($status, my $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id, data_source_type FROM metrics WHERE index_id = " . $self->{"cache_service"}->{$key_service}->{'index_id'}); + ($status, my $stmt) = $self->{dbcentstorage}->query("SELECT metric_id, data_source_type FROM metrics WHERE index_id = " . $self->{cache_service}->{$key_service}->{index_id}); if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot get metrics list"); + $self->{logger}->writeLogError("rebuild cannot get metrics list"); $self->rebuild_finish(); return ; } while ((my $data = $stmt->fetchrow_hashref())) { - $self->{"rrd"}->delete_cache_metric($data->{'metric_id'}); + $self->{rrd}->delete_cache_metric($data->{metric_id}); # Update cache - $self->{"cache_service"}->{$key_service}->{'metrics'}->{'data_source_type'} = $data->{'data_source_type'}; + $self->{cache_service}->{$key_service}->{metrics}->{data_source_type} = $data->{data_source_type}; } ###### # Fork and launch rebuild (we'll rebuild each metric) # - $self->{"rebuild_index_id"} = $self->{"cache_service"}->{$key_service}->{'index_id'}; - my $rebuild_index_id = $self->{"rebuild_index_id"}; + $self->{rebuild_index_id} = $self->{cache_service}->{$key_service}->{index_id}; + my $rebuild_index_id = $self->{rebuild_index_id}; - $self->{"current_pid"} = fork(); - if (!defined($self->{"current_pid"})) { - $self->{'logger'}->writeLogError("rebuild cannot fork: $!"); + $self->{current_pid} = fork(); + if (!defined($self->{current_pid})) { + $self->{logger}->writeLogError("rebuild cannot fork: $!"); $self->rebuild_finish(); - } elsif (!$self->{"current_pid"}) { - $self->{'dbcentstorage'}->set_inactive_destroy(); - $self->{'dbcentreon'}->set_inactive_destroy(); - - my $centreon_db_centstorage = centreon::common::db->new(logger => $self->{'logger'}, - db => $self->{'dbcentstorage'}->db(), - host => $self->{'dbcentstorage'}->host(), - user => $self->{'dbcentstorage'}->user(), - password => $self->{'dbcentstorage'}->password(), - port => $self->{'dbcentstorage'}->port(), + } elsif (!$self->{current_pid}) { + $self->{dbcentstorage}->set_inactive_destroy(); + $self->{dbcentreon}->set_inactive_destroy(); + + my $centreon_db_centstorage = centreon::common::db->new(logger => $self->{logger}, + db => $self->{dbcentstorage}->db(), + host => $self->{dbcentstorage}->host(), + user => $self->{dbcentstorage}->user(), + password => $self->{dbcentstorage}->password(), + port => $self->{dbcentstorage}->port(), force => 0); $status = $centreon_db_centstorage->connect(); exit 1 if ($status == -1); - my $centstorage_rebuild = centreon::centstorage::CentstorageRebuild->new($self->{'logger'}); - $status = $centstorage_rebuild->main($centreon_db_centstorage, $rebuild_index_id, $self->{"cache_service"}->{$key_service}->{'check_interval'}, $self->{'rrd'}, $self->{"cache_service"}->{$key_service}->{'rrd_retention'}); + my $centstorage_rebuild = centreon::centstorage::CentstorageRebuild->new($self->{logger}); + $status = $centstorage_rebuild->main($centreon_db_centstorage, $rebuild_index_id, $self->{cache_service}->{$key_service}->{check_interval}, $self->{rrd}, $self->{cache_service}->{$key_service}->{rrd_retention}); $centreon_db_centstorage->disconnect(); exit $status; } - if ($self->{"current_pid"} == -1) { - $self->{"current_pid"} = undef; + if ($self->{current_pid} == -1) { + $self->{current_pid} = undef; } } @@ -1123,11 +1123,11 @@ sub rename_finish { my $self = shift; my ($host_name, $service_description) = @_; - if (defined($self->{"cache_services_rename"}->{$host_name . ";" . $service_description})) { - $self->{'logger'}->writeLogInfo("rename finish received $host_name/$service_description"); + if (defined($self->{cache_services_rename}->{$host_name . ";" . $service_description})) { + $self->{logger}->writeLogInfo("rename finish received $host_name/$service_description"); my @tmp_ar = (); my $lerror = 0; - foreach (@{$self->{"cache_services_rename"}->{$host_name . ";" . $service_description}}) { + foreach (@{$self->{cache_services_rename}->{$host_name . ";" . $service_description}}) { if ($lerror == 0 && $self->update(1, @$_) != 0) { push @tmp_ar, \@$_; $lerror = 1; @@ -1136,10 +1136,10 @@ sub rename_finish { } } if (scalar(@tmp_ar) != 0) { - @{$self->{"cache_services_failed"}->{$host_name . ";" . $service_description}} = @tmp_ar; + @{$self->{cache_services_failed}->{$host_name . ";" . $service_description}} = @tmp_ar; } - $self->{'logger'}->writeLogInfo("rename finish $host_name/$service_description ok"); - delete $self->{"cache_services_rename"}->{$host_name . ";" . $service_description}; + $self->{logger}->writeLogInfo("rename finish $host_name/$service_description ok"); + delete $self->{cache_services_rename}->{$host_name . ";" . $service_description}; } } @@ -1147,8 +1147,8 @@ sub send_rename_finish { my $self = shift; my ($host_name, $service_description) = @_; - $self->{"rename_rebuild_wait"} = 0; - my $fh = $self->{'pipe_write'}; + $self->{rename_rebuild_wait} = 0; + my $fh = $self->{pipe_write}; print $fh "RENAMEFINISH\t$host_name\t$service_description\n"; } @@ -1157,19 +1157,19 @@ sub rename_clean { my ($host_name, $service_description, $new_host_name, $new_service_description) = @_; my $key = $host_name . ";" . $service_description; - $self->{'logger'}->writeLogInfo("rename clean received $host_name/$service_description"); - $self->{"rename_old_new"}->{$key} = $new_host_name . ";" . $new_service_description; - if ($self->{"rebuild_progress"} == 1 && $self->{"rebuild_key"} eq $key) { - $self->{"rename_rebuild_wait"} = 1; - $self->{'logger'}->writeLogInfo("Wait rebuild finish..."); + $self->{logger}->writeLogInfo("rename clean received $host_name/$service_description"); + $self->{rename_old_new}->{$key} = $new_host_name . ";" . $new_service_description; + if ($self->{rebuild_progress} == 1 && $self->{rebuild_key} eq $key) { + $self->{rename_rebuild_wait} = 1; + $self->{logger}->writeLogInfo("Wait rebuild finish..."); return ; } # Do RRD flush $self->force_flush_rrd($key); - delete $self->{"cache_service"}->{$key}; - delete $self->{"cache_services_failed"}->{$key}; - delete $self->{"rename_old_new"}->{$key}; + delete $self->{cache_service}->{$key}; + delete $self->{cache_services_failed}->{$key}; + delete $self->{rename_old_new}->{$key}; $self->send_rename_finish($new_host_name, $new_service_description); } @@ -1179,15 +1179,15 @@ sub delete_clean { my $key = $host_name . ";" . $service_description; if (defined($metric_name)) { - $self->{'rrd'}->delete_cache_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$metric_name}->{'metric_id'}); - delete $self->{"cache_service"}->{$key}->{'metrics'}->{$metric_name}; + $self->{rrd}->delete_cache_metric($self->{cache_service}->{$key}->{metrics}->{$metric_name}->{metric_id}); + delete $self->{cache_service}->{$key}->{metrics}->{$metric_name}; } else { - foreach (keys %{$self->{"cache_service"}->{$key}->{'metrics'}}) { - $self->{'rrd'}->delete_cache_metric($self->{"cache_service"}->{$key}->{'metrics'}->{$_}->{'metric_id'}); + foreach (keys %{$self->{cache_service}->{$key}->{metrics}}) { + $self->{rrd}->delete_cache_metric($self->{cache_service}->{$key}->{metrics}->{$_}->{metric_id}); } - $self->{'rrd'}->delete_cache_status($self->{"cache_service"}->{$key}->{'index_id'}); - delete $self->{"cache_service"}->{$key}; - delete $self->{"cache_services_failed"}->{$key}; + $self->{rrd}->delete_cache_status($self->{cache_service}->{$key}->{index_id}); + delete $self->{cache_service}->{$key}; + delete $self->{cache_services_failed}->{$key}; } } @@ -1202,32 +1202,32 @@ sub main { $self->{config_file} = $config_file; $self->{perfdata_parser_stop} = $perfdata_parser_stop if (defined($perfdata_parser_stop)); - ($status, $self->{"main_perfdata_file"}) = centreon::centstorage::CentstorageLib::get_main_perfdata_file($self->{'dbcentreon'}); - ($status, $self->{"len_storage_rrd"}, $self->{"rrd_metrics_path"}, $self->{"rrd_status_path"}, $self->{"storage_type"}) = $self->get_centstorage_information(); - ($status, $self->{"interval_time"}) = $self->get_centreon_intervaltime(); - $self->{"rrd"}->metric_path($self->{"rrd_metrics_path"}); - $self->{"rrd"}->status_path($self->{"rrd_status_path"}); - $self->{"rrd"}->len_rrd($self->{"len_storage_rrd"}); - $self->{"rrd"}->cache_mode($rrd_cache_mode); - $self->{"rrd"}->flush($rrd_flush_time); + ($status, $self->{main_perfdata_file}) = centreon::centstorage::CentstorageLib::get_main_perfdata_file($self->{dbcentreon}); + ($status, $self->{len_storage_rrd}, $self->{rrd_metrics_path}, $self->{rrd_status_path}, $self->{storage_type}) = $self->get_centstorage_information(); + ($status, $self->{interval_time}) = $self->get_centreon_intervaltime(); + $self->{rrd}->metric_path($self->{rrd_metrics_path}); + $self->{rrd}->status_path($self->{rrd_status_path}); + $self->{rrd}->len_rrd($self->{len_storage_rrd}); + $self->{rrd}->cache_mode($rrd_cache_mode); + $self->{rrd}->flush($rrd_flush_time); # We have to manage if you don't need infos - $self->{'dbcentreon'}->force(0); - $self->{'dbcentstorage'}->force(0); + $self->{dbcentreon}->force(0); + $self->{dbcentstorage}->force(0); - $self->{'pipe_write'} = $pipe_write; - $self->{'read_select'} = new IO::Select(); - $self->{'read_select'}->add($pipe_read); + $self->{pipe_write} = $pipe_write; + $self->{read_select} = new IO::Select(); + $self->{read_select}->add($pipe_read); while (1) { - my @rh_set = $self->{'read_select'}->can_read(10); + my @rh_set = $self->{read_select}->can_read(10); if (scalar(@rh_set) == 0) { $self->flush_mysql(); - $self->{"rrd"}->flush_all(); + $self->{rrd}->flush_all(); $self->flush_failed(); } foreach my $rh (@rh_set) { my $read_done = 0; - while ((my ($status_line, $readline) = centreon::common::misc::get_line_pipe($rh, \@{$self->{'save_read'}}, \$read_done))) { + while ((my ($status_line, $readline) = centreon::common::misc::get_line_pipe($rh, \@{$self->{save_read}}, \$read_done))) { class_handle_TERM() if ($status_line == -1); last if ($status_line == 0); my ($method, @fields) = split(/\t/, $readline); @@ -1238,7 +1238,7 @@ sub main { } elsif (defined($method) && $method eq "REBUILDBEGIN") { $self->rebuild(@fields); } elsif (defined($method) && $method eq "REBUILDFINISH") { - $self->{"rebuild_progress"} = 0; + $self->{rebuild_progress} = 0; } elsif (defined($method) && $method eq "RENAMEFINISH") { $self->rename_finish(@fields); } elsif (defined($method) && $method eq "RENAMECLEAN") { @@ -1248,7 +1248,7 @@ sub main { } $self->flush_mysql(); - $self->{"rrd"}->flush_all(); + $self->{rrd}->flush_all(); } } $self->flush_failed(); diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageRRD.pm b/centreon/lib/perl/centreon/centstorage/CentstorageRRD.pm index 50e6e1309c7..23dc432013d 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageRRD.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageRRD.pm @@ -10,19 +10,19 @@ my @rrd_dst = ("GAUGE","COUNTER","DERIVE","ABSOLUTE"); sub new { my $class = shift; my $self = {}; - $self->{"logger"} = shift; - $self->{"metric_path"} = undef; - $self->{"status_path"} = undef; - $self->{"len_rrd"} = undef; - $self->{"status_info"} = {}; - $self->{"metric_info"} = {}; + $self->{logger} = shift; + $self->{metric_path} = undef; + $self->{status_path} = undef; + $self->{len_rrd} = undef; + $self->{status_info} = {}; + $self->{metric_info} = {}; # By metric_id - $self->{"rrdcache_metric_data"} = {}; - $self->{"rrdcache_status_data"} = {}; + $self->{rrdcache_metric_data} = {}; + $self->{rrdcache_status_data} = {}; # Flush every n seconds: -1 = disable - $self->{"last_flush"} = time(); - $self->{"flush"} = -1; - $self->{"cache_mode"} = 0; + $self->{last_flush} = time(); + $self->{flush} = -1; + $self->{cache_mode} = 0; bless $self, $class; return $self; } @@ -53,7 +53,7 @@ sub create_rrd_database { RRDs::create($RRDdatabase_path . "/" . $metric_id . ".rrd", "-b ".$begin, "-s ".$interval, "DS:" . substr($metric_name, 0, 19) . ":" . $lsource_type . ":".$interval.":U:U", "RRA:AVERAGE:0.5:1:".$my_len_storage_rrd, "RRA:AVERAGE:0.5:12:".($my_len_storage_rrd / 12)); my $ERR = RRDs::error; if ($ERR) { - $self->{'logger'}->writeLogError("ERROR while creating " . $RRDdatabase_path.$metric_id . ".rrd : $ERR"); + $self->{logger}->writeLogError("ERROR while creating " . $RRDdatabase_path.$metric_id . ".rrd : $ERR"); } else { chmod 0664, "${RRDdatabase_path}/${metric_id}.rrd"; } @@ -66,7 +66,7 @@ sub tune_rrd_database { RRDs::tune($RRDdatabase_path . "/" . $metric_id . ".rrd", "-h", substr($metric_name, 0, 19).":".$interval_hb); my $ERR = RRDs::error; if ($ERR) { - $self->{'logger'}->writeLogError("ERROR while tunning operation on " . $RRDdatabase_path.$metric_id . ".rrd : $ERR"); + $self->{logger}->writeLogError("ERROR while tunning operation on " . $RRDdatabase_path.$metric_id . ".rrd : $ERR"); } } @@ -90,54 +90,54 @@ sub metric_path { my $self = shift; if (@_) { - $self->{'metric_path'} = shift; + $self->{metric_path} = shift; } - return $self->{'metric_path'}; + return $self->{metric_path}; } sub status_path { my $self = shift; if (@_) { - $self->{'status_path'} = shift; + $self->{status_path} = shift; } - return $self->{'status_path'}; + return $self->{status_path}; } sub len_rrd { my $self = shift; if (@_) { - $self->{'len_rrd'} = shift() * 60 * 60 * 24; + $self->{len_rrd} = shift() * 60 * 60 * 24; } - return $self->{'len_rrd'}; + return $self->{len_rrd}; } sub flush { my $self = shift; if (@_) { - $self->{'flush'} = shift; + $self->{flush} = shift; } - return $self->{'flush'}; + return $self->{flush}; } sub cache_mode { my $self = shift; if (@_) { - $self->{'cache_mode'} = shift; + $self->{cache_mode} = shift; } - return $self->{'cache_mode'}; + return $self->{cache_mode}; } sub delete_rrd_metric { my $self = shift; my ($id) = @_; - if (-e $self->{"metric_path"} . "/" . $id . ".rrd") { - if (!unlink($self->{"metric_path"} . "/" . $id . ".rrd")) { - $self->{'logger'}->writeLogError("Cannot delete rrd file " . $self->{"metric_path"} . "/" . $id . ".rrd"); + if (-e $self->{metric_path} . "/" . $id . ".rrd") { + if (!unlink($self->{metric_path} . "/" . $id . ".rrd")) { + $self->{logger}->writeLogError("Cannot delete rrd file " . $self->{metric_path} . "/" . $id . ".rrd"); return -1; } } @@ -148,11 +148,11 @@ sub delete_cache_metric { my $self = shift; my ($metric_id) = @_; - if (defined($self->{"metric_info"}->{$metric_id})) { - delete $self->{"metric_info"}->{$metric_id}; + if (defined($self->{metric_info}->{$metric_id})) { + delete $self->{metric_info}->{$metric_id}; } - if (defined($self->{"rrdcache_metric_data"}->{$metric_id})) { - delete $self->{"rrdcache_metric_data"}->{$metric_id}; + if (defined($self->{rrdcache_metric_data}->{$metric_id})) { + delete $self->{rrdcache_metric_data}->{$metric_id}; } } @@ -160,11 +160,11 @@ sub delete_cache_status { my $self = shift; my ($id) = @_; - if (defined($self->{"status_info"}->{$id})) { - delete $self->{"status_info"}->{$id}; + if (defined($self->{status_info}->{$id})) { + delete $self->{status_info}->{$id}; } - if (defined($self->{"rrdcache_status_data"}->{$id})) { - delete $self->{"rrdcache_status_data"}->{$id}; + if (defined($self->{rrdcache_status_data}->{$id})) { + delete $self->{rrdcache_status_data}->{$id}; } } @@ -172,34 +172,34 @@ sub add_metric { my $self = shift; my ($metric_id, $metric_name, $interval, $data_source_type, $timestamp, $value, $local_rrd_retention) = @_; - if (!defined($self->{"metric_info"}->{$metric_id})) { + if (!defined($self->{metric_info}->{$metric_id})) { my $my_len_storage_rrd; if ($local_rrd_retention == -1) { - $my_len_storage_rrd = $self->{"len_rrd"} / $interval; + $my_len_storage_rrd = $self->{len_rrd} / $interval; } else { $my_len_storage_rrd = $local_rrd_retention / $interval; } - my $ltimestamp = $self->get_last_update($self->{"metric_path"}, $metric_id); + my $ltimestamp = $self->get_last_update($self->{metric_path}, $metric_id); return if ($ltimestamp == -2); - $self->{"metric_info"}->{$metric_id} = {'metric_name' => $metric_name, - 'interval' => $interval, - 'data_source_type' => $data_source_type, - 'last_timestamp' => $ltimestamp, - 'len_rrd' => $my_len_storage_rrd}; - if ($self->{"metric_info"}->{$metric_id}->{'last_timestamp'} == -1) { + $self->{metric_info}->{$metric_id} = {metric_name => $metric_name, + interval => $interval, + data_source_type => $data_source_type, + last_timestamp => $ltimestamp, + len_rrd => $my_len_storage_rrd}; + if ($self->{metric_info}->{$metric_id}->{last_timestamp} == -1) { my $interval_hb = $interval * 10; - $self->create_rrd_database($self->{"metric_path"}, $metric_id, $timestamp - 200, $interval, + $self->create_rrd_database($self->{metric_path}, $metric_id, $timestamp - 200, $interval, $self->get_ds_name($metric_name), $my_len_storage_rrd, $data_source_type); - $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($metric_name), $interval_hb); - $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} = $timestamp - 200; + $self->tune_rrd_database($self->{metric_path}, $metric_id, $self->get_ds_name($metric_name), $interval_hb); + $self->{metric_info}->{$metric_id}->{last_timestamp} = $timestamp - 200; } } - return -1 if ($timestamp <= $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} || $timestamp > (time() + 7200)); - $self->{"rrdcache_metric_data"}->{$metric_id} = [] if (!defined($self->{"rrdcache_metric_data"}->{$metric_id})); - push @{$self->{"rrdcache_metric_data"}->{$metric_id}}, $timestamp . ":" . $value; - $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} = $timestamp; + return -1 if ($timestamp <= $self->{metric_info}->{$metric_id}->{last_timestamp} || $timestamp > (time() + 7200)); + $self->{rrdcache_metric_data}->{$metric_id} = [] if (!defined($self->{rrdcache_metric_data}->{$metric_id})); + push @{$self->{rrdcache_metric_data}->{$metric_id}}, $timestamp . ":" . $value; + $self->{metric_info}->{$metric_id}->{last_timestamp} = $timestamp; } sub add_status { @@ -217,59 +217,59 @@ sub add_status { # Don't do for 'UNKNOWN' return ; } - if (!defined($self->{'status_info'}->{$index_id})) { + if (!defined($self->{status_info}->{$index_id})) { my $my_len_storage_rrd; if ($local_rrd_retention == -1) { - $my_len_storage_rrd = $self->{"len_rrd"} / $interval; + $my_len_storage_rrd = $self->{len_rrd} / $interval; } else { $my_len_storage_rrd = $local_rrd_retention / $interval; } - my $ltimestamp = $self->get_last_update($self->{"status_path"}, $index_id); + my $ltimestamp = $self->get_last_update($self->{status_path}, $index_id); return if ($ltimestamp == -2); - $self->{"status_info"}->{$index_id} = {'interval' => $interval, - 'last_timestamp' => $ltimestamp, - 'values' => [], - 'len_rrd' => $my_len_storage_rrd}; - if ($self->{"status_info"}->{$index_id}->{'last_timestamp'} == -1) { + $self->{status_info}->{$index_id} = {interval => $interval, + last_timestamp => $ltimestamp, + values => [], + len_rrd => $my_len_storage_rrd}; + if ($self->{status_info}->{$index_id}->{last_timestamp} == -1) { my $interval_hb = $interval * 10; - $self->create_rrd_database($self->{"status_path"}, $index_id, $timestamp - 200, $interval, + $self->create_rrd_database($self->{status_path}, $index_id, $timestamp - 200, $interval, "status", $my_len_storage_rrd, 0); - $self->tune_rrd_database($self->{"status_path"}, $index_id, "status", $interval_hb); - $self->{"status_info"}->{$index_id}->{'last_timestamp'} = $timestamp - 200; + $self->tune_rrd_database($self->{status_path}, $index_id, "status", $interval_hb); + $self->{status_info}->{$index_id}->{last_timestamp} = $timestamp - 200; } } - return -1 if ($timestamp <= $self->{"status_info"}->{$index_id}->{'last_timestamp'} || $timestamp > (time() + 7200)); - $self->{"rrdcache_status_data"}->{$index_id} = [] if (!defined($self->{"rrdcache_status_data"}->{$index_id})); - push @{$self->{"rrdcache_status_data"}->{$index_id}}, $timestamp . ":" . $value; - $self->{"status_info"}->{$index_id}->{'last_timestamp'} = $timestamp; + return -1 if ($timestamp <= $self->{status_info}->{$index_id}->{last_timestamp} || $timestamp > (time() + 7200)); + $self->{rrdcache_status_data}->{$index_id} = [] if (!defined($self->{rrdcache_status_data}->{$index_id})); + push @{$self->{rrdcache_status_data}->{$index_id}}, $timestamp . ":" . $value; + $self->{status_info}->{$index_id}->{last_timestamp} = $timestamp; } sub flush_metric { my $self = shift; my ($metric_id) = @_; - if (defined($self->{"rrdcache_metric_data"}->{$metric_id})) { - RRDs::update($self->{"metric_path"} . "/" . $metric_id . ".rrd", @{$self->{"rrdcache_metric_data"}->{$metric_id}}); + if (defined($self->{rrdcache_metric_data}->{$metric_id})) { + RRDs::update($self->{metric_path} . "/" . $metric_id . ".rrd", @{$self->{rrdcache_metric_data}->{$metric_id}}); my $ERR = RRDs::error; if ($ERR) { # Try to see if the file had been deleted - if (! -e $self->{"metric_path"} . "/" . $metric_id . ".rrd") { - my $my_len_storage_rrd = $self->{"metric_info"}->{$metric_id}->{'len_rrd'}; - my $interval_hb = $self->{"metric_info"}->{$metric_id}->{'interval'} * 10; - - $self->create_rrd_database($self->{"metric_path"}, $metric_id, - $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} - 200, - $self->{"metric_info"}->{$metric_id}->{'interval'}, - $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $my_len_storage_rrd, - $self->{"metric_info"}->{$metric_id}->{'data_source_type'}); - $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $interval_hb); + if (! -e $self->{metric_path} . "/" . $metric_id . ".rrd") { + my $my_len_storage_rrd = $self->{metric_info}->{$metric_id}->{len_rrd}; + my $interval_hb = $self->{metric_info}->{$metric_id}->{interval} * 10; + + $self->create_rrd_database($self->{metric_path}, $metric_id, + $self->{metric_info}->{$metric_id}->{last_timestamp} - 200, + $self->{metric_info}->{$metric_id}->{interval}, + $self->get_ds_name($self->{metric_info}->{$metric_id}->{metric_name}), $my_len_storage_rrd, + $self->{metric_info}->{$metric_id}->{data_source_type}); + $self->tune_rrd_database($self->{metric_path}, $metric_id, $self->get_ds_name($self->{metric_info}->{$metric_id}->{metric_name}), $interval_hb); } else { - $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"metric_path"} . "/" . $metric_id . ".rrd' $ERR"); + $self->{logger}->writeLogError("ERROR while updating '" . $self->{metric_path} . "/" . $metric_id . ".rrd' $ERR"); } } - delete $self->{"rrdcache_metric_data"}->{$metric_id}; + delete $self->{rrdcache_metric_data}->{$metric_id}; } } @@ -277,26 +277,26 @@ sub flush_status { my $self = shift; my ($index_id) = @_; - if (defined($self->{"rrdcache_status_data"}->{$index_id})) { - RRDs::update($self->{"status_path"} . "/" . $index_id . ".rrd", @{$self->{"rrdcache_status_data"}->{$index_id}}); + if (defined($self->{rrdcache_status_data}->{$index_id})) { + RRDs::update($self->{status_path} . "/" . $index_id . ".rrd", @{$self->{rrdcache_status_data}->{$index_id}}); my $ERR = RRDs::error; if ($ERR) { # Try to see if the file had been deleted - if (! -e $self->{"status_path"} . "/" . $index_id . ".rrd") { - my $my_len_storage_rrd = $self->{"status_info"}->{$index_id}->{'len_rrd'}; - my $interval_hb = $self->{"status_info"}->{$index_id}->{'interval'} * 10; + if (! -e $self->{status_path} . "/" . $index_id . ".rrd") { + my $my_len_storage_rrd = $self->{status_info}->{$index_id}->{len_rrd}; + my $interval_hb = $self->{status_info}->{$index_id}->{interval} * 10; - $self->create_rrd_database($self->{"status_path"}, $index_id, - $self->{"status_info"}->{$index_id}->{'last_timestamp'} - 200, - $self->{"status_info"}->{$index_id}->{'interval'}, + $self->create_rrd_database($self->{status_path}, $index_id, + $self->{status_info}->{$index_id}->{last_timestamp} - 200, + $self->{status_info}->{$index_id}->{interval}, "status", $my_len_storage_rrd, 0); $self->tune_rrd_database($self->{"status_path"}, $index_id, "status", $interval_hb); } else { - $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"status_path"} . "/" . $index_id . ".rrd' $ERR"); + $self->{logger}->writeLogError("ERROR while updating '" . $self->{status_path} . "/" . $index_id . ".rrd' $ERR"); } } - delete $self->{"rrdcache_status_data"}->{$index_id}; + delete $self->{rrdcache_status_data}->{$index_id}; } } @@ -304,62 +304,62 @@ sub flush_all { my $self = shift; my ($force) = @_; - if ($self->{'cache_mode'} == 1 && (!defined($force) || $force == 0)) { - return if (time() < ($self->{'last_flush'} + $self->{'flush'})); - $self->{'last_flush'} = time(); - $self->{'logger'}->writeLogInfo("Flush Beginning"); + if ($self->{cache_mode} == 1 && (!defined($force) || $force == 0)) { + return if (time() < ($self->{last_flush} + $self->{flush})); + $self->{last_flush} = time(); + $self->{logger}->writeLogInfo("Flush Beginning"); } ### # Metrics ### - foreach my $metric_id (keys %{$self->{"rrdcache_metric_data"}}) { - RRDs::update($self->{"metric_path"} . "/" . $metric_id . ".rrd", @{$self->{"rrdcache_metric_data"}->{$metric_id}}); + foreach my $metric_id (keys %{$self->{rrdcache_metric_data}}) { + RRDs::update($self->{metric_path} . "/" . $metric_id . ".rrd", @{$self->{rrdcache_metric_data}->{$metric_id}}); my $ERR = RRDs::error; if ($ERR) { # Try to see if the file had been deleted - if (! -e $self->{"metric_path"} . "/" . $metric_id . ".rrd") { - my $my_len_storage_rrd = $self->{"metric_info"}->{$metric_id}->{'len_rrd'}; - my $interval_hb = $self->{"metric_info"}->{$metric_id}->{'interval'} * 10; - - $self->create_rrd_database($self->{"metric_path"}, $metric_id, - $self->{"metric_info"}->{$metric_id}->{'last_timestamp'} - 200, - $self->{"metric_info"}->{$metric_id}->{'interval'}, - $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $my_len_storage_rrd, - $self->{"metric_info"}->{$metric_id}->{'data_source_type'}); - $self->tune_rrd_database($self->{"metric_path"}, $metric_id, $self->get_ds_name($self->{"metric_info"}->{$metric_id}->{'metric_name'}), $interval_hb); + if (! -e $self->{metric_path} . "/" . $metric_id . ".rrd") { + my $my_len_storage_rrd = $self->{metric_info}->{$metric_id}->{len_rrd}; + my $interval_hb = $self->{metric_info}->{$metric_id}->{interval} * 10; + + $self->create_rrd_database($self->{metric_path}, $metric_id, + $self->{metric_info}->{$metric_id}->{last_timestamp} - 200, + $self->{metric_info}->{$metric_id}->{interval}, + $self->get_ds_name($self->{metric_info}->{$metric_id}->{metric_name}), $my_len_storage_rrd, + $self->{metric_info}->{$metric_id}->{data_source_type}); + $self->tune_rrd_database($self->{metric_path}, $metric_id, $self->get_ds_name($self->{metric_info}->{$metric_id}->{metric_name}), $interval_hb); } else { - $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"metric_path"} . "/" . $metric_id . ".rrd' $ERR"); + $self->{logger}->writeLogError("ERROR while updating '" . $self->{metric_path} . "/" . $metric_id . ".rrd' $ERR"); } } } - $self->{"rrdcache_metric_data"} = {}; + $self->{rrdcache_metric_data} = {}; ### # Status ### - foreach my $service_id (keys %{$self->{"rrdcache_status_data"}}) { - RRDs::update($self->{"status_path"} . "/" . $service_id . ".rrd", @{$self->{"rrdcache_status_data"}->{$service_id}}); + foreach my $service_id (keys %{$self->{rrdcache_status_data}}) { + RRDs::update($self->{status_path} . "/" . $service_id . ".rrd", @{$self->{rrdcache_status_data}->{$service_id}}); my $ERR = RRDs::error; if ($ERR) { # Try to see if the file had been deleted - if (! -e $self->{"status_path"} . "/" . $service_id . ".rrd") { - my $my_len_storage_rrd = $self->{"status_info"}->{$service_id}->{'len_rrd'}; - my $interval_hb = $self->{"status_info"}->{$service_id}->{'interval'} * 10; + if (! -e $self->{status_path} . "/" . $service_id . ".rrd") { + my $my_len_storage_rrd = $self->{status_info}->{$service_id}->{len_rrd}; + my $interval_hb = $self->{status_info}->{$service_id}->{interval} * 10; - $self->create_rrd_database($self->{"status_path"}, $service_id, - $self->{"status_info"}->{$service_id}->{'last_timestamp'} - 200, - $self->{"status_info"}->{$service_id}->{'interval'}, + $self->create_rrd_database($self->{status_path}, $service_id, + $self->{status_info}->{$service_id}->{last_timestamp} - 200, + $self->{status_info}->{$service_id}->{interval}, "status", $my_len_storage_rrd, 0); - $self->tune_rrd_database($self->{"status_path"}, $service_id, "status", $interval_hb); + $self->tune_rrd_database($self->{status_path}, $service_id, "status", $interval_hb); } else { - $self->{'logger'}->writeLogError("ERROR while updating '" . $self->{"status_path"} . "/" . $service_id . ".rrd' $ERR"); + $self->{logger}->writeLogError("ERROR while updating '" . $self->{status_path} . "/" . $service_id . ".rrd' $ERR"); } } } - $self->{"rrdcache_status_data"} = {}; + $self->{rrdcache_status_data} = {}; - $self->{'logger'}->writeLogInfo("Flush Ending") if ($self->{'cache_mode'} == 1); + $self->{logger}->writeLogInfo("Flush Ending") if ($self->{cache_mode} == 1); } 1; diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageRebuild.pm b/centreon/lib/perl/centreon/centstorage/CentstorageRebuild.pm index 91dc5964926..6fe807a6d5b 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageRebuild.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageRebuild.pm @@ -3,13 +3,13 @@ use strict; use warnings; package centreon::centstorage::CentstorageRebuild; -my %handlers = ('TERM' => {}); +my %handlers = (TERM => {}); sub new { my $class = shift; my $self = {}; - $self->{"logger"} = shift; - $self->{"dbcentstorage"} = undef; + $self->{logger} = shift; + $self->{dbcentstorage} = undef; bless $self, $class; $self->set_signal_handlers; @@ -20,28 +20,28 @@ sub set_signal_handlers { my $self = shift; $SIG{TERM} = \&class_handle_TERM; - $handlers{'TERM'}->{$self} = sub { $self->handle_TERM() }; + $handlers{TERM}->{$self} = sub { $self->handle_TERM() }; } sub handle_TERM { my $self = shift; - $self->{'logger'}->writeLogInfo("$$ Receiving order to stop..."); + $self->{logger}->writeLogInfo("$$ Receiving order to stop..."); eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm 10; - $self->{'dbcentstorage'}->kill(); + $self->{dbcentstorage}->kill(); alarm 0; }; if ($@) { - $self->{'logger'}->writeLogError("Can't kill rebuild request"); + $self->{logger}->writeLogError("Can't kill rebuild request"); } - $self->{"dbcentstorage"}->disconnect() if (defined($self->{"dbcentstorage"})); + $self->{dbcentstorage}->disconnect() if (defined($self->{dbcentstorage})); } sub class_handle_TERM { - foreach (keys %{$handlers{'TERM'}}) { - &{$handlers{'TERM'}->{$_}}(); + foreach (keys %{$handlers{TERM}}) { + &{$handlers{TERM}->{$_}}(); } exit(0); } @@ -52,44 +52,44 @@ sub main { my $status; my $stmt; - $self->{'dbcentstorage'} = $dbcentstorage; + $self->{dbcentstorage} = $dbcentstorage; ### Update for UI - ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE index_data SET `must_be_rebuild` = '2' WHERE id = " . $index_id); + ($status, $stmt) = $self->{dbcentstorage}->query("UPDATE index_data SET `must_be_rebuild` = '2' WHERE id = " . $index_id); if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot update index_id $index_id"); + $self->{logger}->writeLogError("rebuild cannot update index_id $index_id"); return 1; } ### # Get By Metric_id ### - ($status, $stmt) = $self->{'dbcentstorage'}->query("SELECT metric_id, metric_name, data_source_type FROM metrics WHERE index_id = " . $index_id); + ($status, $stmt) = $self->{dbcentstorage}->query("SELECT metric_id, metric_name, data_source_type FROM metrics WHERE index_id = " . $index_id); if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot get metrics list"); + $self->{logger}->writeLogError("rebuild cannot get metrics list"); return 1; } while ((my $data = $stmt->fetchrow_hashref())) { - ($status, my $stmt2) = $self->{'dbcentstorage'}->query("SELECT ctime, value FROM data_bin WHERE id_metric = " . $data->{'metric_id'} . " ORDER BY ctime ASC"); + ($status, my $stmt2) = $self->{dbcentstorage}->query("SELECT ctime, value FROM data_bin WHERE id_metric = " . $data->{metric_id} . " ORDER BY ctime ASC"); if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot get metric_id datas " . $data->{'metric_id'}); + $self->{logger}->writeLogError("rebuild cannot get metric_id datas " . $data->{metric_id}); return 1; } ### Delete RRD - $status = $rrd->delete_rrd_metric($data->{'metric_id'}); + $status = $rrd->delete_rrd_metric($data->{metric_id}); my $rows = []; while (my $data2 = (shift(@$rows) || shift(@{$rows = $stmt2->fetchall_arrayref(undef,10_000)||[]}) ) ) { - $rrd->add_metric($data->{'metric_id'}, $data->{'metric_name'}, $interval, $data->{'data_source_type'}, $$data2[0], $$data2[1], $local_rrd); + $rrd->add_metric($data->{metric_id}, $data->{metric_name}, $interval, $data->{data_source_type}, $$data2[0], $$data2[1], $local_rrd); } - $rrd->flush_metric($data->{'metric_id'}); + $rrd->flush_metric($data->{metric_id}); } ### Update for UI - ($status, $stmt) = $self->{'dbcentstorage'}->query("UPDATE index_data SET `must_be_rebuild` = '0' WHERE id = " . $index_id); + ($status, $stmt) = $self->{dbcentstorage}->query("UPDATE index_data SET `must_be_rebuild` = '0' WHERE id = " . $index_id); if ($status == -1) { - $self->{'logger'}->writeLogError("rebuild cannot update index_id $index_id"); + $self->{logger}->writeLogError("rebuild cannot update index_id $index_id"); return 1; } diff --git a/centreon/lib/perl/centreon/common/misc.pm b/centreon/lib/perl/centreon/common/misc.pm index 1b50e91f8be..58d32ee69e4 100644 --- a/centreon/lib/perl/centreon/common/misc.pm +++ b/centreon/lib/perl/centreon/common/misc.pm @@ -54,6 +54,46 @@ sub reload_db_config { return (0, $cdb_mod, $csdb_mod); } +sub get_all_options_config { + my ($extra_config, $centreon_db_centreon, $prefix) = @_; + + my $save_force = $centreon_db_centreon->force(); + $centreon_db_centreon->force(0); + + my ($status, $stmt) = $centreon_db_centreon->query("SELECT `key`, `value` FROM options WHERE `key` LIKE " . $centreon_db_centreon->quote($prefix . "_%") . " LIMIT 1"); + if ($status == -1) { + $centreon_db_centreon->force($save_force); + return ; + } + while ((my $data = $stmt->fetchrow_hashref())) { + if (defined($data->{value}) && length($data->{value}) > 0) { + $data->{key} =~ s/^${prefix}_//; + $extra_config->{$data->{key}} = $data->{value}; + } + } + + $centreon_db_centreon->force($save_force); +} + +sub get_option_config { + my ($extra_config, $centreon_db_centreon, $prefix, $key) = @_; + my $data; + + my $save_force = $centreon_db_centreon->force(); + $centreon_db_centreon->force(0); + + my ($status, $stmt) = $centreon_db_centreon->query("SELECT value FROM options WHERE `key` = " . $centreon_db_centreon->quote($prefix . "_" . $key) . " LIMIT 1"); + if ($status == -1) { + $centreon_db_centreon->force($save_force); + return ; + } + if (($data = $stmt->fetchrow_hashref()) && defined($data->{value})) { + $extra_config->{$key} = $data->{value}; + } + + $centreon_db_centreon->force($save_force); +} + sub check_debug { my ($logger, $key, $cdb, $name) = @_; diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index afe8a4cf7ee..911d0b66605 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -263,7 +263,7 @@ sub getNagiosConfigurationField($$){ sub getLocalServerID(){ my $self = shift; - my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `id` FROM `nagios_server` WHERE `localhost` = '1' LIMIT 1"); + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `id` FROM `nagios_server` WHERE `localhost` = '1' ORDER BY ns_activate DESC LIMIT 1"); if ($status == -1) { $self->{logger}->writeLogError("Error when getting server properties"); return undef; diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index a9650bebe85..8922cef4328 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -56,7 +56,10 @@ sub new { TIMEOUT => 60, rrd_cache_mode => 0, rrd_flush_time => 60 * 10, - perfdata_parser_stop => 1 + perfdata_parser_stop => 1, + auto_duplicate => 0, + duplicate_file => undef, + nopurge => 0 ); $self->set_signal_handlers; @@ -161,12 +164,12 @@ sub handle_DIE { # Send -TERM signal ### for (my $i = 0; defined($self->{centstorage_config}->{pool_childs}) && $i < $self->{centstorage_config}->{pool_childs}; $i++) { - if (defined($self->{pool_pipes}{$i}) && $self->{pool_pipes}{$i}->{'running'} == 1) { - kill('TERM', $self->{pool_pipes}{$i}->{'pid'}); + if (defined($self->{pool_pipes}{$i}) && $self->{pool_pipes}{$i}->{running} == 1) { + kill('TERM', $self->{pool_pipes}{$i}->{pid}); $self->{logger}->writeLogInfo("Send -TERM signal to pool process.."); } } - if (defined($self->{delete_pipes}{'running'}) && $self->{delete_pipes}{'running'} == 1) { + if (defined($self->{delete_pipes}{running}) && $self->{delete_pipes}{running} == 1) { $self->{logger}->writeLogInfo("Send -TERM signal to delete process.."); kill('TERM', $self->{pid_delete_child}); } @@ -185,9 +188,9 @@ sub handle_DIE { $self->verify_pool(0); my $running = 0; for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { - $running += $self->{pool_pipes}{$i}->{'running'} == 1; + $running += $self->{pool_pipes}{$i}->{running} == 1; } - $running += $self->{delete_pipes}{'running'}; + $running += $self->{delete_pipes}{running}; if ($running == 0) { $kill_or_not = 0; last; @@ -197,12 +200,12 @@ sub handle_DIE { if ($kill_or_not == 1) { for (my $i = 0; $i < $self->{centstorage_config}->{pool_childs}; $i++) { - if ($self->{pool_pipes}{$i}->{'running'} == 1) { - kill('KILL', $self->{pool_pipes}{$i}->{'pid'}); + if ($self->{pool_pipes}{$i}->{running} == 1) { + kill('KILL', $self->{pool_pipes}{$i}->{pid}); $self->{logger}->writeLogInfo("Send -KILL signal to pool process.."); } } - if ($self->{delete_pipes}{'running'} == 1) { + if ($self->{delete_pipes}{running} == 1) { kill('KILL', $self->{pid_delete_child}); $self->{logger}->writeLogInfo("Send -KILL signal to delete process.."); } @@ -233,10 +236,10 @@ sub verify_pool { foreach my $child_pid (keys %{$self->{return_child}}) { foreach my $pool_num (keys %{$self->{pool_pipes}}) { - if ($self->{pool_pipes}{$pool_num}->{'pid'} == $child_pid) { + if ($self->{pool_pipes}{$pool_num}->{pid} == $child_pid) { $self->{logger}->writeLogInfo("Pool child '$pool_num' is dead"); - $self->{read_select}->remove($self->{pool_pipes}{$pool_num}->{'reader_one'}); - $self->{pool_pipes}{$pool_num}->{'running'} = 0; + $self->{read_select}->remove($self->{pool_pipes}{$pool_num}->{reader_one}); + $self->{pool_pipes}{$pool_num}->{running} = 0; if (defined($create_pool) && $create_pool == 1) { # We have lost one. And if it's the pool rebuild, send progress finish if ($pool_num == $self->{rebuild_pool_choosen}) { @@ -250,8 +253,8 @@ sub verify_pool { } if ($child_pid == $self->{pid_delete_child}) { $self->{logger}->writeLogInfo("Delete child is dead"); - $self->{read_select}->remove($self->{delete_pipes}{'reader_one'}); - $self->{delete_pipes}{'running'} = 0; + $self->{read_select}->remove($self->{delete_pipes}{reader_one}); + $self->{delete_pipes}{running} = 0; if (defined($create_pool) && $create_pool == 1) { $self->create_delete_child(); } @@ -273,16 +276,16 @@ sub create_pool_child { $writer_pipe_two->autoflush(1); $self->{pool_pipes}{$pool_num} = {}; - $self->{pool_pipes}{$pool_num}->{'reader_one'} = \*$reader_pipe_one; - $self->{pool_pipes}{$pool_num}->{'writer_one'} = \*$writer_pipe_one; - $self->{pool_pipes}{$pool_num}->{'reader_two'} = \*$reader_pipe_two; - $self->{pool_pipes}{$pool_num}->{'writer_two'} = \*$writer_pipe_two; + $self->{pool_pipes}{$pool_num}->{reader_one} = \*$reader_pipe_one; + $self->{pool_pipes}{$pool_num}->{writer_one} = \*$writer_pipe_one; + $self->{pool_pipes}{$pool_num}->{reader_two} = \*$reader_pipe_two; + $self->{pool_pipes}{$pool_num}->{writer_two} = \*$writer_pipe_two; $self->{logger}->writeLogInfo("Create Pool child '$pool_num'"); my $current_pid = fork(); if (!$current_pid) { - close $self->{pool_pipes}{$pool_num}->{'reader_one'}; - close $self->{pool_pipes}{$pool_num}->{'writer_two'}; + close $self->{pool_pipes}{$pool_num}->{reader_one}; + close $self->{pool_pipes}{$pool_num}->{writer_two}; my $centreon_db_centreon = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, host => $self->{centreon_config}->{db_host}, port => $self->{centreon_config}->{db_port}, @@ -302,18 +305,19 @@ sub create_pool_child { my $centstorage_rrd = centreon::centstorage::CentstorageRRD->new($self->{logger}); - my $centstorage_pool = centreon::centstorage::CentstoragePool->new($self->{logger}, $centstorage_rrd, $self->{rebuild_progress}); + my $centstorage_pool = centreon::centstorage::CentstoragePool->new($self->{logger}, $centstorage_rrd, $self->{rebuild_progress}, $self->{centstorage_config}); $centstorage_pool->main($centreon_db_centreon, $centreon_db_centstorage, - $self->{pool_pipes}{$pool_num}->{'reader_two'}, $self->{pool_pipes}{$pool_num}->{'writer_one'}, $pool_num, - $self->{centstorage_config}->{rrd_cache_mode}, $self->{centstorage_config}->{rrd_flush_time}, $self->{centstorage_config}->{perfdata_parser_stop}, $self->{config_file}); + $self->{pool_pipes}{$pool_num}->{reader_two}, $self->{pool_pipes}{$pool_num}->{writer_one}, $pool_num, + $self->{centstorage_config}->{rrd_cache_mode}, $self->{centstorage_config}->{rrd_flush_time}, $self->{centstorage_config}->{perfdata_parser_stop}, + $self->{config_file}); exit(0); } - $self->{pool_pipes}{$pool_num}->{'pid'} = $current_pid; - $self->{pool_pipes}{$pool_num}->{'running'} = 1; - close $self->{pool_pipes}{$pool_num}->{'writer_one'}; - close $self->{pool_pipes}{$pool_num}->{'reader_two'}; - $self->{fileno_save_read}{fileno($self->{pool_pipes}{$pool_num}->{'reader_one'})} = []; - $self->{read_select}->add($self->{pool_pipes}{$pool_num}->{'reader_one'}); + $self->{pool_pipes}{$pool_num}->{pid} = $current_pid; + $self->{pool_pipes}{$pool_num}->{running} = 1; + close $self->{pool_pipes}{$pool_num}->{writer_one}; + close $self->{pool_pipes}{$pool_num}->{reader_two}; + $self->{fileno_save_read}{fileno($self->{pool_pipes}{$pool_num}->{reader_one})} = []; + $self->{read_select}->add($self->{pool_pipes}{$pool_num}->{reader_one}); } sub create_delete_child { @@ -327,16 +331,16 @@ sub create_delete_child { $writer_pipe_one->autoflush(1); $writer_pipe_two->autoflush(1); - $self->{delete_pipes}{'reader_one'} = \*$reader_pipe_one; - $self->{delete_pipes}{'writer_one'} = \*$writer_pipe_one; - $self->{delete_pipes}{'reader_two'} = \*$reader_pipe_two; - $self->{delete_pipes}{'writer_two'} = \*$writer_pipe_two; + $self->{delete_pipes}{reader_one} = \*$reader_pipe_one; + $self->{delete_pipes}{writer_one} = \*$writer_pipe_one; + $self->{delete_pipes}{reader_two} = \*$reader_pipe_two; + $self->{delete_pipes}{writer_two} = \*$writer_pipe_two; $self->{logger}->writeLogInfo("Create delete child"); my $current_pid = fork(); if (!$current_pid) { - close $self->{delete_pipes}{'reader_one'}; - close $self->{delete_pipes}{'writer_two'}; + close $self->{delete_pipes}{reader_one}; + close $self->{delete_pipes}{writer_two}; my $centreon_db_centreon = centreon::common::db->new(db => $self->{centreon_config}->{centreon_db}, host => $self->{centreon_config}->{db_host}, port => $self->{centreon_config}->{db_port}, @@ -354,17 +358,18 @@ sub create_delete_child { logger => $self->{logger}); $centreon_db_centstorage->connect(); - my $centstorage_action = centreon::centstorage::CentstorageAction->new($self->{logger}, $self->{rebuild_progress}); + my $centstorage_action = centreon::centstorage::CentstorageAction->new($self->{logger}, $self->{rebuild_progress}, $self->{centstorage_config}); $centstorage_action->main($centreon_db_centreon, $centreon_db_centstorage, - $self->{delete_pipes}{'reader_two'}, $self->{delete_pipes}{'writer_one'}, $self->{config_file}); + $self->{delete_pipes}{reader_two}, $self->{delete_pipes}{writer_one}, + $self->{config_file}); exit(0); } $self->{pid_delete_child} = $current_pid; - close $self->{delete_pipes}{'writer_one'}; - close $self->{delete_pipes}{'reader_two'}; - $self->{delete_pipes}{'running'} = 1; - $self->{fileno_save_read}{fileno($self->{delete_pipes}{'reader_one'})} = []; - $self->{read_select}->add($self->{delete_pipes}{'reader_one'}); + close $self->{delete_pipes}{writer_one}; + close $self->{delete_pipes}{reader_two}; + $self->{delete_pipes}{running} = 1; + $self->{fileno_save_read}{fileno($self->{delete_pipes}{reader_one})} = []; + $self->{read_select}->add($self->{delete_pipes}{reader_one}); } sub handle_CHLD { @@ -372,7 +377,7 @@ sub handle_CHLD { my $child_pid; while (($child_pid = waitpid(-1, &WNOHANG)) > 0) { - $self->{return_child}{$child_pid} = {'exit_code' => $? >> 8}; + $self->{return_child}{$child_pid} = {exit_code => $? >> 8}; } $SIG{CHLD} = \&class_handle_CHLD; } @@ -398,6 +403,10 @@ sub run { force => 1, logger => $self->{logger}); $self->{centreon_db_centreon}->connect(); + + centreon::common::misc::get_all_options_config($self->{centstorage_config}, $self->{centreon_db_centreon}, + "centstorage"); + $self->handle_DIE("Censtorage option is '0'. Don't have to start") if (centreon::centstorage::CentstorageLib::start_or_not($self->{centreon_db_centreon}) == 0); while (!defined($main_perfdata) || $main_perfdata eq "") { ($status, $main_perfdata) = centreon::centstorage::CentstorageLib::get_main_perfdata_file($self->{centreon_db_centreon}); @@ -451,7 +460,8 @@ sub run { # Do main file ### $self->{centstorage_perfdata_file} = centreon::centstorage::CentstoragePerfdataFile->new($self->{logger}); - $self->{centstorage_perfdata_file}->compute($main_perfdata, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}); + $self->{centstorage_perfdata_file}->compute($main_perfdata, \%{$self->{pool_pipes}}, \%{$self->{routing_services}}, \$self->{roundrobin_pool_current}, $self->{centstorage_config}->{pool_childs}, + $self->{centstorage_config}->{auto_duplicate}, $self->{centstorage_config}->{duplicate_file}); ### # Check response from rebuild From afb94a6c94de6843b4fdc8e6f057cc7305cbf526 Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Fri, 12 Jul 2013 16:50:16 +0200 Subject: [PATCH 089/458] refs #4623; pollers now have their own trapd conf path --- centreon/lib/perl/centreon/script/centcore.pm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index 911d0b66605..5da7b3094b2 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -749,7 +749,7 @@ sub syncTraps($) { } } else { # synchronize Archives for all pollers - my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `id` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `id`, `snmp_trapd_path_conf` FROM `nagios_server` WHERE `ns_activate` = '1' AND `localhost` = '0'"); return if ($status == -1); while (my $server = $sth->fetchrow_hashref()) { # Get configuration @@ -757,7 +757,7 @@ sub syncTraps($) { my $port = checkSSHPort($ns_server->{'ssh_port'}); if ($id == 0) { - $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/$id/centreontrapd.sdb $ns_server->{'ns_ip_address'}:/etc/snmp/centreon_traps/ 2>&1"; + $cmd = "$self->{scp} -P $port /etc/snmp/centreon_traps/$id/centreontrapd.sdb $ns_server->{'ns_ip_address'}:$ns_server->{'snmp_trapd_path_conf'} 2>&1"; $self->{logger}->writeLogDebug($cmd); ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, logger => $self->{logger}, From 4084d94dea0ee2ecb9dcc274685b4eb786fe4199 Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Tue, 16 Jul 2013 16:01:25 +0200 Subject: [PATCH 090/458] fixes #4507; handles new centreon perl packages --- centreon/lib/perl/centreon/script.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script.pm b/centreon/lib/perl/centreon/script.pm index 557c1fa33f0..37c3e963dc5 100644 --- a/centreon/lib/perl/centreon/script.pm +++ b/centreon/lib/perl/centreon/script.pm @@ -21,7 +21,7 @@ sub new { my ($class, $name, %options) = @_; my %defaults = ( - config_file => "/etc/centreon/centreon-config.pm", + config_file => "@CENTREON_ETC@/centreon-config.pm", log_file => undef, centreon_db_conn => 0, centstorage_db_conn => 0, From 2fc4d96179172f768ce37ee6aacc0c1f2a2fd6db Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Tue, 16 Jul 2013 17:47:09 +0200 Subject: [PATCH 091/458] refs #4507; remove macro --- centreon/lib/perl/centreon/script.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script.pm b/centreon/lib/perl/centreon/script.pm index 37c3e963dc5..557c1fa33f0 100644 --- a/centreon/lib/perl/centreon/script.pm +++ b/centreon/lib/perl/centreon/script.pm @@ -21,7 +21,7 @@ sub new { my ($class, $name, %options) = @_; my %defaults = ( - config_file => "@CENTREON_ETC@/centreon-config.pm", + config_file => "/etc/centreon/centreon-config.pm", log_file => undef, centreon_db_conn => 0, centstorage_db_conn => 0, From 91380bc7c5c16be60647969cd83a471b44602489 Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Thu, 18 Jul 2013 16:57:49 +0200 Subject: [PATCH 092/458] fixes #4609; +centcore cmd timeout --- centreon/lib/perl/centreon/script/centcore.pm | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index 5da7b3094b2..91ada6102bd 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -956,7 +956,7 @@ sub parseRequest($){ sub checkProfile() { my $self = shift; - my $request = "SELECT * FROM options WHERE `key` IN ('enable_perfdata_sync', 'enable_logs_sync')"; + my $request = "SELECT * FROM options WHERE `key` IN ('enable_perfdata_sync', 'enable_logs_sync', 'centcore_cmd_timeout')"; my ($status, $sth) = $self->{centreon_dbc}->query($request); return -1 if ($status == -1); while ((my $data = $sth->fetchrow_hashref())) { @@ -967,6 +967,9 @@ sub checkProfile() { if ($data->{'key'} eq "enable_logs_sync") { $self->{logSync} = $data->{'value'}; } + if ($data->{'key'} eq "centcore_cmd_timeout") { + $self->{cmd_timeout} = $data->{'value'}; + } } } return 0; From 2ea18a7765e56155d2b0402a1911c9e67054be15 Mon Sep 17 00:00:00 2001 From: Julien Mathis Date: Thu, 18 Jul 2013 17:31:54 +0200 Subject: [PATCH 093/458] fix #4222 --- centreon/lib/perl/centreon/script/centcore.pm | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index 5da7b3094b2..d64804ae807 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -863,11 +863,13 @@ sub getInfos($) { if ($str =~ m/(Nagios) Core ([\.0-9]*[a-zA-Z0-9\-\.]+)/) { $self->{logger}->writeLogInfo("Engine: $1"); $self->{logger}->writeLogInfo("Version: $2"); + $self->updateEngineInformation($id, $1, $2); last; } if ($str =~ m/(Centreon Engine) ([\.0-9]*[a-zA-Z0-9\-\.]+)/) { $self->{logger}->writeLogInfo("Engine: $1"); $self->{logger}->writeLogInfo("Version: $2"); + $self->updateEngineInformation($id, $1, $2); last; } } @@ -876,6 +878,18 @@ sub getInfos($) { } } +############################### +## Update Engine informations +# +sub updateEngineInformation($$$) { + my $self = shift; + my $id = $_[0]; + my $engine_nane = $_[1]; + my $engine_version = $_[2]; + + $self->{centreon_dbc}->query("UPDATE `nagios_server` SET `engine_name` = '$engine_name', `engine_version` = '$engine_version' WHERE `id` = '$id'"); +} + ################################ ## Reload CentreonTrapd Daemon # From 2e0b4b506aa65fba2b73800b482150617127bab0 Mon Sep 17 00:00:00 2001 From: Lionel Assepo Date: Fri, 19 Jul 2013 14:41:38 +0200 Subject: [PATCH 094/458] refs #4222 Change name --- centreon/lib/perl/centreon/script/centcore.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index cddeef746e5..b4d47de9f10 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -884,7 +884,7 @@ sub getInfos($) { sub updateEngineInformation($$$) { my $self = shift; my $id = $_[0]; - my $engine_nane = $_[1]; + my $engine_name = $_[1]; my $engine_version = $_[2]; $self->{centreon_dbc}->query("UPDATE `nagios_server` SET `engine_name` = '$engine_name', `engine_version` = '$engine_version' WHERE `id` = '$id'"); From 82f820292dacccc18bd0cb5bd24bca00ee0fa712 Mon Sep 17 00:00:00 2001 From: Lionel Assepo Date: Fri, 19 Jul 2013 15:18:01 +0200 Subject: [PATCH 095/458] refs #4222 add support for localhost --- centreon/lib/perl/centreon/script/centcore.pm | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index b4d47de9f10..e879d2778ce 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -852,12 +852,21 @@ sub getInfos($) { if (defined($ns_server->{'ns_ip_address'}) && $ns_server->{'ns_ip_address'}) { # Launch command - $cmd = "$self->{ssh} -p $port ". $ns_server->{'ns_ip_address'} ." ".$ns_server->{'nagios_bin'}; - $self->{logger}->writeLogDebug($cmd); - ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + if (defined($ns_server->{'localhost'}) && $ns_server->{'localhost'}) { + $cmd = "$self->{sudo} ".$ns_server->{'nagios_bin'}; + $self->{logger}->writeLogDebug($cmd); + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, + logger => $self->{logger}, + timeout => 60 + ); + } else { + $cmd = "$self->{ssh} -p $port ". $ns_server->{'ns_ip_address'} ." ".$ns_server->{'nagios_bin'}; + $self->{logger}->writeLogDebug($cmd); + ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd, logger => $self->{logger}, timeout => 60 ); + } my @tab = split("\n", $stdout); foreach my $str (@tab) { if ($str =~ m/(Nagios) Core ([\.0-9]*[a-zA-Z0-9\-\.]+)/) { From 22de7c8efa60d46b59db0d17f5ff6d6d83c255bf Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Mon, 22 Jul 2013 15:46:55 +0200 Subject: [PATCH 096/458] centreon::logger -> centreon::common::logger --- centreon/lib/perl/centreon/common/logger.pm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/centreon/lib/perl/centreon/common/logger.pm b/centreon/lib/perl/centreon/common/logger.pm index b13cfe613fd..3a875aeab65 100644 --- a/centreon/lib/perl/centreon/common/logger.pm +++ b/centreon/lib/perl/centreon/common/logger.pm @@ -2,7 +2,7 @@ package centreon::common::logger; =head1 NOM -centreon::logger - Simple logging module +centreon::common::logger - Simple logging module =head1 SYNOPSIS @@ -13,7 +13,7 @@ centreon::logger - Simple logging module use centreon::polling; - my $logger = new centreon::logger(); + my $logger = new centreon::common::logger(); $logger->writeLogInfo("information"); From 991d2ccbb208a2461dd1b07e561f5554add3d563 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 25 Jul 2013 15:54:36 +0200 Subject: [PATCH 097/458] Some minor fixes --- centreon/lib/perl/centreon/script/centreontrapd.pm | 3 ++- centreon/lib/perl/centreon/trapd/lib.pm | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index e16fe8644cd..60033864d52 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -311,7 +311,7 @@ sub create_logdb_child { $self->{logdb_pipes}{'reader'} = \*$reader_pipe; $self->{logdb_pipes}{'writer'} = \*$writer_pipe; - $self->{logger}->writeLogInfo("Create delete child"); + $self->{logger}->writeLogInfo("Create logdb child"); my $current_pid = fork(); if (!$current_pid) { # Unhandle die in child @@ -436,6 +436,7 @@ sub manage_exec { #### Fork And manage exec #### ####### Check Interval ###### if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type}) && + $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type} ne '' && defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval})) { # OID type if ($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type} == 1 && diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 1eebed38780..506a9bcd459 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -511,6 +511,7 @@ sub readtrap { #Process varbinds #Separate everything out, keeping both the variable name and the value my $linenum = 1; + my $variable_fix; while (defined(my $line = <$input>)) { push(@rawtrap, $line); $line =~ s(`)(')g; #` Replace any back ticks with regular single quote @@ -529,7 +530,6 @@ sub readtrap { chomp ($temp2); # Variable VALUE chomp ($line); - my $variable_fix; if ($linenum == 1) { # Check if line 1 contains 'variable value' or just 'value' if (defined($temp2)) { From 02303a2ae1a7a9d76d4a2e87f015b27103068d01 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 2 Aug 2013 17:25:16 +0200 Subject: [PATCH 098/458] Fix #4673 --- .../lib/perl/centreon/script/centreontrapd.pm | 306 +++++++++++------- centreon/lib/perl/centreon/trapd/lib.pm | 3 +- 2 files changed, 195 insertions(+), 114 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 60033864d52..d15f363d29a 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -4,6 +4,7 @@ package centreon::script::centreontrapd; use strict; use warnings; use POSIX; +use Storable; use centreon::script; use centreon::common::db; use centreon::common::misc; @@ -59,16 +60,31 @@ sub new { log_purge_time => 600 ); - $self->{htmlentities} = 0; - @{$self->{var}} = undef; # Variables of trap received by SNMPTRAPD - @{$self->{entvar}} = undef; # Enterprise variable values of trap received by SNMPTRAPD - @{$self->{entvarname}} = undef; # Enterprise variable names of trap received by SNMPTRAPD - @{$self->{preexec}} = (); # Result from PREEXEC - $self->{agent_dns_name} = undef; - $self->{trap_date} = undef; - $self->{trap_time} = undef; - $self->{trap_date_time} = undef; - $self->{trap_date_time_epoch} = undef; + # save trap_data + @{$self->{trap_data_save}} = (); + + $self->{trap_data} = { + var => [], # Variables of trap received by SNMPTRAPD + entvar => [], # Enterprise variable values of trap received by SNMPTRAPD + entvarname => [], # Enterprise variable names of trap received by SNMPTRAPD + preexec => [], # Result from PREEXEC + agent_dns_name => undef, + trap_date => undef, + trap_time => undef, + trap_date_time => undef, + trap_date_time_epoch => undef, + + ref_oids => undef, + ref_hosts => undef, + ref_services => undef, + ref_macro_hosts => undef, + + current_trap_id => undef, + current_host_id => undef, + current_service_id => undef + }; + + $self->{htmlentities} = 0; %{$self->{duplicate_traps}} = (); $self->{timetoreload} = 0; @{$self->{filenames}} = undef; @@ -76,15 +92,16 @@ sub new { $self->{last_cache_time} = undef; $self->{whoami} = undef; - $self->{ref_oids} = undef; - $self->{ref_hosts} = undef; - $self->{ref_services} = undef; - $self->{ref_macro_hosts} = undef; - + # Fork manage %{$self->{return_child}} = (); %{$self->{running_processes}} = (); + $self->{sequential_processes} = { + pid => {}, + trap_id => {} + }; %{$self->{last_time_exec}} = ('oid' => {}, 'host' => {}); + # Current ID of working $self->{current_host_id} = undef; $self->{current_hostname} = undef; @@ -102,7 +119,7 @@ sub new { $self->{current_alarm_timeout} = undef; - # + # After in fork $self->{traps_global_output} = undef; $self->{traps_global_status} = undef; $self->{traps_global_severity_id} = undef; @@ -342,8 +359,14 @@ sub create_logdb_child { sub manage_pool { my $self = shift; my ($create_pool) = @_; - + foreach my $child_pid (keys %{$self->{return_child}}) { + + if (defined($self->{sequential_processes}->{pid}->{$child_pid})) { + delete $self->{sequential_processes}->{trap_id}->{ $self->{sequential_processes}->{pid}->{$child_pid} }; + delete $self->{sequential_processes}->{pid}->{$child_pid}; + } + if (defined($self->{running_processes}->{$child_pid})) { delete $self->{running_processes}->{$child_pid}; delete $self->{return_child}->{$child_pid}; @@ -360,6 +383,53 @@ sub manage_pool { } } +############################### +## Save and Play functions +# + +sub set_current_values { + my $self = shift; + + $self->{current_trap_id} = $self->{trap_data}->{current_trap_id}; + $self->{current_host_id} = $self->{trap_data}->{current_host_id}; + $self->{current_service_id} = $self->{trap_data}->{current_service_id}; + + $self->{current_ip} = ${$self->{trap_data}->{var}}[1]; + $self->{current_oid} = ${$self->{trap_data}->{var}}[3]; + $self->{current_trap_log} = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_log}; + $self->{current_trap_name} = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_name}; + $self->{current_vendor_name} = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{name}; + $self->{current_server_id} = $self->{trap_data}->{ref_hosts}->{ $self->{current_host_id} }->{nagios_server_id}; + $self->{current_server_ip_address} = $self->{trap_data}->{ref_hosts}->{ $self->{current_host_id} }->{ns_ip_address}; + $self->{current_hostname} = $self->{trap_data}->{ref_hosts}->{ $self->{current_host_id} }->{host_name}; + $self->{current_service_desc} = $self->{trap_data}->{ref_services}->{ $self->{current_service_id} }->{service_description}; +} + +sub check_sequential_can_exec { + my $self = shift; + + if (defined($self->{sequential_processes}->{trap_id}->{$self->{current_host_id} . "_" . $self->{current_trap_id}})) { + # We save data + $self->{logger}->writeLogInfo("Put trap in queue..."); + push @{$self->{trap_data_save}}, Storable::dclone($self->{trap_data}); + return 1; + } + return 0; +} + +sub check_sequential_todo { + my $self = shift; + + for (my $i = 0; $i <= $#{$self->{trap_data_save}}; $i++) { + if (!defined($self->{sequential_processes}->{trap_id}->{ ${$self->{trap_data_save}}[$i]->{current_host_id} . "_" . ${$self->{trap_data_save}}[$i]->{current_trap_id} })) { + $self->{logger}->writeLogInfo("Exec trap in queue..."); + $self->{trap_data} = splice @{$self->{trap_data_save}}, $i, 1; + $i--; + $self->manage_exec(); + } + } +} + ############################### ## Execute a command Nagios or Centcore # @@ -367,42 +437,42 @@ sub do_exec { my $self = shift; my $matching_result = 0; - $self->{traps_global_status} = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_status}; - $self->{traps_global_severity_id} = $self->{ref_oids}->{ $self->{current_trap_id} }->{sc_id}; - $self->{traps_global_severity_name} = $self->{ref_oids}->{ $self->{current_trap_id} }->{sc_name}; - $self->{traps_global_severity_level} = $self->{ref_oids}->{ $self->{current_trap_id} }->{level}; + $self->{traps_global_status} = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_status}; + $self->{traps_global_severity_id} = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{sc_id}; + $self->{traps_global_severity_name} = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{sc_name}; + $self->{traps_global_severity_level} = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{level}; # PREEXEC commands $self->execute_preexec(); - $self->{traps_global_output} = $self->substitute_string($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_args}); + $self->{traps_global_output} = $self->substitute_string($self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_args}); ###################################################################### # Advanced matching rules - if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment}) && - $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment} == 1) { + if (defined($self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment}) && + $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment} == 1) { $matching_result = $self->checkMatchingRules(); } ##################################################################### # Submit value to passive service - if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_submit_result_enable}) && - $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_submit_result_enable} == 1 && + if (defined($self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_submit_result_enable}) && + $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_submit_result_enable} == 1 && $matching_result == 0) { $self->submitResult(); } ###################################################################### # Force service execution with external command - if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_reschedule_svc_enable}) && - $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_reschedule_svc_enable} == 1) { + if (defined($self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_reschedule_svc_enable}) && + $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_reschedule_svc_enable} == 1) { $self->forceCheck(); } ###################################################################### # Execute special command - if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command_enable}) && - $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command_enable} == 1) { + if (defined($self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command_enable}) && + $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command_enable} == 1) { $self->executeCommand(); } @@ -410,12 +480,12 @@ sub do_exec { centreon::trapd::lib::send_logdb(pipe => $self->{logdb_pipes}{'writer'}, id => $self->{id_logdb}, cdb => $self->{cdb}, - trap_time => $self->{trap_date_time_epoch}, + trap_time => $self->{trap_data}->{trap_date_time_epoch}, timeout => 0, - host_name => ${$self->{var}}[0], + host_name => ${$self->{trap_data}->{var}}[0], ip_address => $self->{current_ip}, - agent_host_name => $self->{agent_dns_name}, - agent_ip_address => ${$self->{var}}[4], + agent_host_name => $self->{trap_data}->{agent_dns_name}, + agent_ip_address => ${$self->{trap_data}->{var}}[4], trap_oid => $self->{current_oid}, trap_name => $self->{current_trap_name}, vendor => $self->{current_vendor_name}, @@ -423,23 +493,23 @@ sub do_exec { severity_id => $self->{traps_global_severity_id}, severity_name => $self->{traps_global_severity_name}, output_message => $self->{traps_global_output}, - entvar => \@{$self->{entvar}}, - entvarname => \@{$self->{entvarname}}); + entvar => \@{$self->{trap_data}->{entvar}}, + entvarname => \@{$self->{trap_data}->{entvarname}}); } } sub manage_exec { my $self = shift; - $self->{id_logdb}++; + $self->set_current_values(); #### Fork And manage exec #### ####### Check Interval ###### - if (defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type}) && - $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type} ne '' && - defined($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval})) { + if (defined($self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type}) && + $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type} ne '' && + defined($self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval})) { # OID type - if ($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type} == 1 && + if ($self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type} == 1 && defined($self->{last_time_exec}{oid}->{$self->{current_oid}}) && $self->{trap_date_time_epoch} < ($self->{last_time_exec}{oid}->{$self->{current_oid}} + $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval})) { $self->{logger}->writeLogInfo("Skipping trap '" . $self->{current_trap_id} . "': time interval"); @@ -447,14 +517,19 @@ sub manage_exec { } # Host type - if ($self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type} == 2 && + if ($self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval_type} == 2 && defined($self->{last_time_exec}{host}->{$self->{current_host_id} . ";" . $self->{current_oid}}) && - $self->{trap_date_time_epoch} < ($self->{last_time_exec}{host}->{$self->{current_host_id} . ";" . $self->{current_oid}} + $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval})) { + $self->{trap_date_time_epoch} < ($self->{last_time_exec}{host}->{$self->{current_host_id} . ";" . $self->{current_oid}} + $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_interval})) { $self->{logger}->writeLogInfo("Skipping trap '" . $self->{current_trap_id} . "' for host ID '" . $self->{current_host_id} . "': time interval"); return 1; } } + ### Check Sequential exec ### + return 1 if ($self->check_sequential_can_exec() == 1); + + $self->{id_logdb}++; + my $current_pid = fork(); if (!$current_pid) { # Unhandle die in child @@ -472,6 +547,15 @@ sub manage_exec { } $self->{logger}->writeLogInfo("CHLD command launched: $current_pid"); + + #### + # Save to say it's sequential + if (defined($self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_method}) && + $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_exec_method} == 1) { + $self->{sequential_processes}->{pid}->{$current_pid} = $self->{current_host_id} . "_" . $self->{current_trap_id}; + $self->{sequential_processes}->{trap_id}->{$self->{current_host_id} . "_" . $self->{current_trap_id}} = $current_pid; + } + $self->{running_processes}->{$current_pid} = 1; $self->{last_time_exec}{oid}->{$self->{current_oid}} = $self->{trap_date_time_epoch}; $self->{last_time_exec}{host}->{$self->{current_host_id} . ";" . $self->{current_oid}} = $self->{trap_date_time_epoch}; @@ -557,8 +641,8 @@ sub submitResult { sub execute_preexec { my $self = shift; - foreach my $tpe_order (keys %{$self->{ref_oids}->{ $self->{current_trap_id} }->{traps_preexec}}) { - my $tpe_string = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_preexec}->{$tpe_order}->{tpe_string}; + foreach my $tpe_order (keys %{$self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_preexec}}) { + my $tpe_string = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_preexec}->{$tpe_order}->{tpe_string}; $tpe_string = $self->substitute_string($tpe_string); $tpe_string = $self->substitute_centreon_var($tpe_string); @@ -574,10 +658,10 @@ sub execute_preexec { } if (defined($output)) { chomp $output; - push @{$self->{preexec}}, $output; + push @{$self->{trap_data}->{preexec}}, $output; $self->{logger}->writeLogInfo("EXEC preexec: Output : $output"); } else { - push @{$self->{preexec}}, ""; + push @{$self->{trap_data}->{preexec}}, ""; } } } @@ -603,35 +687,35 @@ sub substitute_string { my $str = $_[0]; # Substitute @{oid_value} and $1, $2,... - for (my $i=0; $i <= $#{$self->{entvar}}; $i++) { + for (my $i=0; $i <= $#{$self->{trap_data}->{entvar}}; $i++) { my $x = $i + 1; - $str =~ s/\@\{${$self->{entvarname}}[$i]\}/${$self->{entvar}}[$i]/g; - $str =~ s/\$$x([^0-9]|$)/${$self->{entvar}}[$i]$1/g; + $str =~ s/\@\{${$self->{trap_data}->{entvarname}}[$i]\}/${$self->{trap_data}->{entvar}}[$i]/g; + $str =~ s/\$$x([^0-9]|$)/${$self->{trap_data}->{entvar}}[$i]$1/g; } # Substitute preexec var - for (my $i=0; $i <= $#{$self->{preexec}}; $i++) { + for (my $i=0; $i <= $#{$self->{trap_data}->{preexec}}; $i++) { my $x = $i + 1; - $str =~ s/\$p$x([^0-9]|$)/${$self->{preexec}}[$i]$1/g; + $str =~ s/\$p$x([^0-9]|$)/${$self->{trap_data}->{preexec}}[$i]$1/g; } # Substitute $* - my $sub_str = join($self->{centreontrapd_config}->{separator}, @{$self->{entvar}}); + my $sub_str = join($self->{centreontrapd_config}->{separator}, @{$self->{trap_data}->{entvar}}); $str =~ s/\$\*/$sub_str/g; # $A - $str =~ s/\$A/$self->{agent_dns_name}/g; + $str =~ s/\$A/$self->{trap_data}->{agent_dns_name}/g; # $aA (Trap agent IP Adress) - $str =~ s/\$aA/${$self->{var}}[4]/g; + $str =~ s/\$aA/${$self->{trap_data}->{var}}[4]/g; # $R, $r (Trap Hostname) - $str =~ s/\$R/${$self->{var}}[0]/g; - $str =~ s/\$r/${$self->{var}}[0]/g; + $str =~ s/\$R/${$self->{trap_data}->{var}}[0]/g; + $str =~ s/\$r/${$self->{trap_data}->{var}}[0]/g; # $aR, $ar (IP Adress) - $str =~ s/\$aR/${$self->{var}}[1]/g; - $str =~ s/\$ar/${$self->{var}}[1]/g; + $str =~ s/\$aR/${$self->{trap_data}->{var}}[1]/g; + $str =~ s/\$ar/${$self->{trap_data}->{var}}[1]/g; # Clean OID $str =~ s/\@\{[\.0-9]*\}//g; @@ -644,14 +728,14 @@ sub substitute_centreon_var { $str =~ s/\@HOSTNAME\@/$self->{current_hostname}/g; $str =~ s/\@HOSTADDRESS\@/$self->{current_ip}/g; - $str =~ s/\@HOSTADDRESS2\@/$self->{agent_dns_name}/g; + $str =~ s/\@HOSTADDRESS2\@/$self->{trap_data}->{agent_dns_name}/g; $str =~ s/\@SERVICEDESC\@/$self->{current_service_desc}/g; $str =~ s/\@TRAPOUTPUT\@/$self->{traps_global_output}/g; $str =~ s/\@OUTPUT\@/$self->{traps_global_output}/g; $str =~ s/\@STATUS\@/$self->{traps_global_status}/g; $str =~ s/\@SEVERITYNAME\@/$self->{traps_global_severity_name}/g; $str =~ s/\@SEVERITYLEVEL\@/$self->{traps_global_severity_level}/g; - $str =~ s/\@TIME\@/$self->{trap_date_time_epoch}/g; + $str =~ s/\@TIME\@/$self->{trap_data}->{trap_date_time_epoch}/g; $str =~ s/\@POLLERID\@/$self->{current_server_id}/g; $str =~ s/\@POLLERADDRESS\@/$self->{current_server_ip_address}/g; $str =~ s/\@CMDFILE\@/$self->{cmdFile}/g; @@ -686,13 +770,13 @@ sub checkMatchingRules { my $matching_boolean = 0; # Check matching options - foreach my $tmo_id (keys %{$self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}}) { - my $tmoString = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_string}; - my $regexp = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_regexp}; - my $tmoStatus = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_status}; - my $severity_level = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{level}; - my $severity_name = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{sc_name}; - my $severity_id = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{sc_id}; + foreach my $tmo_id (keys %{$self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}}) { + my $tmoString = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_string}; + my $regexp = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_regexp}; + my $tmoStatus = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{tmo_status}; + my $severity_level = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{level}; + my $severity_name = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{sc_name}; + my $severity_id = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_matching_properties}->{$tmo_id}->{sc_id}; $self->{logger}->writeLogDebug("[$tmoString][$regexp] => $tmoStatus"); @@ -740,7 +824,7 @@ sub checkMatchingRules { } # Dont do submit if no matching - if ($matching_boolean == 0 && $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment_default} == 1) { + if ($matching_boolean == 0 && $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_advanced_treatment_default} == 1) { return 1; } return 0; @@ -752,7 +836,7 @@ sub checkMatchingRules { sub executeCommand { my $self = shift; my $datetime = time(); - my $traps_execution_command = $self->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command}; + my $traps_execution_command = $self->{trap_data}->{ref_oids}->{ $self->{current_trap_id} }->{traps_execution_command}; $traps_execution_command = $self->substitute_string($traps_execution_command); @@ -798,61 +882,52 @@ sub executeCommand { sub getTrapsInfos { my $self = shift; my ($fstatus); - - $self->{current_ip} = ${$self->{var}}[1]; - $self->{current_oid} = ${$self->{var}}[3]; - # Use $self->{agent_dns_name} (IP or HOSTNAME with split) ### Get OIDS - ($fstatus, $self->{ref_oids}) = centreon::trapd::lib::get_oids($self->{cdb}, $self->{current_oid}); + ($fstatus, $self->{trap_data}->{ref_oids}) = centreon::trapd::lib::get_oids($self->{cdb}, ${$self->{trap_data}->{var}}[3]); return 0 if ($fstatus == -1); - foreach my $trap_id (keys %{$self->{ref_oids}}) { - $self->{current_trap_id} = $trap_id; - $self->{current_trap_log} = $self->{ref_oids}->{$trap_id}->{traps_log}; - $self->{current_trap_name} = $self->{ref_oids}->{$trap_id}->{traps_name}; - $self->{current_vendor_name} = $self->{ref_oids}->{$trap_id}->{name}; - ($fstatus, $self->{ref_hosts}) = centreon::trapd::lib::get_hosts(logger => $self->{logger}, + foreach my $trap_id (keys %{$self->{trap_data}->{ref_oids}}) { + $self->{trap_data}->{current_trap_id} = $trap_id; + + ($fstatus, $self->{trap_data}->{ref_hosts}) = centreon::trapd::lib::get_hosts(logger => $self->{logger}, cdb => $self->{cdb}, - trap_info => $self->{ref_oids}->{$trap_id}, - agent_dns_name => $self->{agent_dns_name}, - ip_address => $self->{current_ip}, - entvar => \@{$self->{entvar}}, - entvarname => \@{$self->{entvarname}}, + trap_info => $self->{trap_data}->{ref_oids}->{$trap_id}, + agent_dns_name => $self->{trap_data}->{agent_dns_name}, + ip_address => ${$self->{trap_data}->{var}}[1], centreontrapd => $self); return 0 if ($fstatus == -1); - foreach my $host_id (keys %{$self->{ref_hosts}}) { - if (!defined($self->{ref_hosts}->{$host_id}->{nagios_server_id})) { + foreach my $host_id (keys %{$self->{trap_data}->{ref_hosts}}) { + if (!defined($self->{trap_data}->{ref_hosts}->{$host_id}->{nagios_server_id})) { $self->{logger}->writeLogError("Cant get server associated for host '" . $self->{ref_hosts}->{$host_id}->{host_name} . "'"); next; } - $self->{current_host_id} = $host_id; - $self->{current_server_id} = $self->{ref_hosts}->{$host_id}->{nagios_server_id}; - $self->{current_server_ip_address} = $self->{ref_hosts}->{$host_id}->{ns_ip_address}; - $self->{current_hostname} = $self->{ref_hosts}->{$host_id}->{host_name}; + $self->{trap_data}->{current_host_id} = $host_id; #### Get Services #### - ($fstatus, $self->{ref_services}) = centreon::trapd::lib::get_services($self->{cdb}, $trap_id, $host_id); + ($fstatus, $self->{trap_data}->{ref_services}) = centreon::trapd::lib::get_services($self->{cdb}, $trap_id, $host_id); return 0 if ($fstatus == -1); #### If none, we stop #### - my $size = keys %{$self->{ref_services}}; + my $size = keys %{$self->{trap_data}->{ref_services}}; if ($size < 1) { - $self->{logger}->writeLogDebug("Trap without service associated for host " . $self->{current_hostname} . ". Skipping..."); + $self->{logger}->writeLogDebug("Trap without service associated for host " . $self->{trap_data}->{ref_hosts}->{$host_id}->{host_name} . ". Skipping..."); next; } #### Check if macro $_HOST*$ needed - $self->{ref_macro_hosts} = undef; - if (defined($self->{ref_oids}->{$trap_id}->{traps_execution_command_enable}) && $self->{ref_oids}->{$trap_id}->{traps_execution_command_enable} == 1 && - defined($self->{ref_oids}->{$trap_id}->{traps_execution_command}) && $self->{ref_oids}->{$trap_id}->{traps_execution_command} =~ /\$_HOST.*?\$/) { - ($fstatus, $self->{ref_macro_hosts}) = centreon::trapd::lib::get_macros_host($self->{cdb}, $host_id); + $self->{trap_data}->{ref_macro_hosts} = undef; + if (defined($self->{trap_data}->{ref_oids}->{$trap_id}->{traps_execution_command_enable}) && $self->{trap_data}->{ref_oids}->{$trap_id}->{traps_execution_command_enable} == 1 && + defined($self->{trap_data}->{ref_oids}->{$trap_id}->{traps_execution_command}) && $self->{trap_data}->{ref_oids}->{$trap_id}->{traps_execution_command} =~ /\$_HOST.*?\$/) { + ($fstatus, $self->{trap_data}->{ref_macro_hosts}) = centreon::trapd::lib::get_macros_host($self->{cdb}, $host_id); return 0 if ($fstatus == -1); } - foreach my $service_id (keys %{$self->{ref_services}}) { - $self->{current_service_id} = $service_id; - $self->{current_service_desc} = $self->{ref_services}->{$service_id}->{service_description}; - $self->{logger}->writeLogDebug("Trap found on service '" . $self->{ref_services}->{$service_id}->{service_description} . "' for host '" . $self->{ref_hosts}->{$host_id}->{host_name} . "'."); + foreach my $service_id (keys %{$self->{trap_data}->{ref_services}}) { + $self->{trap_data}->{current_service_id} = $service_id; + $self->{logger}->writeLogDebug("Trap found on service '" . + $self->{trap_data}->{ref_services}->{$service_id}->{service_description} . + "' for host '" . + $self->{trap_data}->{ref_hosts}->{$host_id}->{host_name} . "'."); $self->manage_exec(); } } @@ -912,27 +987,31 @@ sub run { } } + ### Check pool finish and check old ones + $self->manage_pool(1); + $self->check_sequential_todo(); + if (open FILE, $self->{centreontrapd_config}->{spool_directory} . $file) { my $unlink_trap = 1; my $trap_is_a_duplicate = 0; my $readtrap_result = centreon::trapd::lib::readtrap(logger => $self->{logger}, config => $self->{centreontrapd_config}, handle => \*FILE, - agent_dns_name => \$self->{agent_dns_name}, - trap_date => \$self->{trap_date}, - trap_time => \$self->{trap_time}, - trap_date_time => \$self->{trap_date_time}, - trap_date_time_epoch => \$self->{trap_date_time_epoch}, + agent_dns_name => \$self->{trap_data}->{agent_dns_name}, + trap_date => \$self->{trap_data}->{trap_date}, + trap_time => \$self->{trap_data}->{trap_time}, + trap_date_time => \$self->{trap_data}->{trap_date_time}, + trap_date_time_epoch => \$self->{trap_data}->{trap_date_time_epoch}, duplicate_traps => \%{$self->{duplicate_traps}}, digest_trap => \$self->{digest_trap}, - var => \@{$self->{var}}, - entvar => \@{$self->{entvar}}, - entvarname => \@{$self->{entvarname}}); + var => \@{$self->{trap_data}->{var}}, + entvar => \@{$self->{trap_data}->{entvar}}, + entvarname => \@{$self->{trap_data}->{entvarname}}); if ($readtrap_result == 1) { if (centreon::trapd::lib::check_known_trap(logger => $self->{logger}, config => $self->{centreontrapd_config}, - oid2verif => ${$self->{var}}[3], + oid2verif => ${$self->{trap_data}->{var}}[3], cdb => $self->{cdb}, last_cache_time => \$self->{last_cache_time}, oids_cache => \$self->{oids_cache}) == 1) { @@ -979,7 +1058,10 @@ sub run { if ($self->{timetoreload} == 1) { $self->reload(); } + + ### Check pool finish and check old ones $self->manage_pool(1); + $self->check_sequential_todo(); } } diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index 506a9bcd459..e21be1d81d6 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -96,6 +96,7 @@ sub get_oids { traps_oid, traps_name, traps_advanced_treatment, traps_advanced_treatment_default, traps_execution_command_enable, traps_submit_result_enable, traps_status, traps_timeout, traps_exec_interval, traps_exec_interval_type, traps_routing_mode, traps_routing_value, + traps_exec_method, service_categories.level, service_categories.sc_name, service_categories.sc_id FROM traps LEFT JOIN traps_vendor ON (traps_vendor.id = traps.manufacturer_id) @@ -131,8 +132,6 @@ sub get_hosts { # trap_info => ref # agent_dns_name => value # ip_address => value - # entvar => ref array - # entvarname => ref array my %args = @_; my ($dstatus, $sth); my $ref_result; From d0fc4dc70a648364908d1e582bfbe07cb4138dc3 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 27 Aug 2013 15:28:40 +0200 Subject: [PATCH 099/458] Fix centstorage2 cache issue --- .../lib/perl/centreon/centstorage/CentstorageAction.pm | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm index 2d4a3a61cb7..929108e3f18 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm @@ -176,6 +176,7 @@ sub delete_rrd_file { sub purge_mysql_and_rrd { my $self = shift; + my $pipe_write = $_[0]; my ($status, $stmt, $rows, $data); my %cache_index_data = (); my %cache_services = (); @@ -212,7 +213,7 @@ sub purge_mysql_and_rrd { $self->{logger}->writeLogError("Can't opendir " . $self->{"rrd_status_path"} . ": $!"); } - ($status, $stmt) = $self->{dbcentstorage}->query("SELECT host_id, service_id, id FROM index_data"); + ($status, $stmt) = $self->{dbcentstorage}->query("SELECT host_id, service_id, id, host_name, service_description FROM index_data"); return -1 if ($status); $rows = []; while ($data = (shift(@$rows) || @@ -226,6 +227,8 @@ sub purge_mysql_and_rrd { $self->delete_rrd_file($self->{"rrd_metrics_path"}, $data2->{metric_id}); } $self->{dbcentstorage}->query("DELETE FROM index_data WHERE id = '" . $$data[2] . "'"); + print $pipe_write "DELETECLEAN\t" . $$data[3] . "\t" . $$data[4] . "\n"; + $self->{logger}->writeLogInfo("Delete MySQL metrics " . $$data[0] . "/" . $$data[1]); $self->delete_rrd_file($self->{rrd_status_path}, $$data[2]); } @@ -281,12 +284,13 @@ sub get_centstorage_information { sub check_purge { my $self = shift; + my $pipe_write = $_[0]; if (time() < ($self->{last_purge_time} + $self->{purge_delay})) { return ; } - $self->purge_mysql_and_rrd(); + $self->purge_mysql_and_rrd($pipe_write); $self->{last_purge_time} = time(); } @@ -326,7 +330,7 @@ sub main { } else { $self->check_rebuild($pipe_write); $self->check_deleted($pipe_write); - $self->check_purge(); + $self->check_purge($pipe_write); } if ($self->{reload} == 0) { From d22c85a4b08f8bbe6b7a8e1b68bf552535f96236 Mon Sep 17 00:00:00 2001 From: Julien Mathis Date: Fri, 30 Aug 2013 17:52:39 +0200 Subject: [PATCH 100/458] fix #4713 --- centreon/lib/perl/centreon/script/centcore.pm | 2 ++ 1 file changed, 2 insertions(+) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index e879d2778ce..f3f6a8fe833 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -951,6 +951,8 @@ sub parseRequest($){ $self->initEngine($1, "restart"); } elsif ($action =~ /^RELOAD\:([0-9]*)/){ $self->initEngine($1, "reload"); + } elsif ($action =~ /^FORCERELOAD\:([0-9]*)/){ + $self->initEngine($1, "force-reload"); } elsif ($action =~ /^START\:([0-9]*)/){ $self->initEngine($1, "start"); } elsif ($action =~ /^STOP\:([0-9]*)/){ From 2a969f71510ae3f18517a412366ccff78727bd86 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 11 Sep 2013 10:38:12 +0200 Subject: [PATCH 101/458] Fix config extra options for perl daemons --- centreon/lib/perl/centreon/script/centreontrapd.pm | 2 +- centreon/lib/perl/centreon/script/centstorage.pm | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index d15f363d29a..36cecc342c8 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -25,7 +25,7 @@ sub new { bless $self, $class; $self->add_options( - "config-extra" => \$self->{opt_extra}, + "config-extra=s" => \$self->{opt_extra}, ); %{$self->{centreontrapd_default_config}} = diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index 8922cef4328..fd3e7cd218c 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -29,7 +29,7 @@ sub new { bless $self, $class; $self->add_options( - "config-extra" => \$self->{opt_extra}, + "config-extra=s" => \$self->{opt_extra}, ); %{$self->{pool_pipes}} = (); From bdcb63fe4bde86bbaab6ec099decc3438d3e9a98 Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Fri, 20 Sep 2013 10:32:40 +0200 Subject: [PATCH 102/458] remove silly debug\! --- centreon/lib/perl/centreon/common/misc.pm | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/centreon/lib/perl/centreon/common/misc.pm b/centreon/lib/perl/centreon/common/misc.pm index 58d32ee69e4..c4356f5d3cf 100644 --- a/centreon/lib/perl/centreon/common/misc.pm +++ b/centreon/lib/perl/centreon/common/misc.pm @@ -170,16 +170,6 @@ sub get_line_pipe { return -1; } -sub plop { - my $child_pid; - - while (($child_pid = waitpid(-1, &WNOHANG)) > 0) { - print "SIGCHLD received: $child_pid\n"; - } - print "SIGCHLD received: $child_pid\n"; - #print "LAAAAAAAAAAAAAAAAAA\n"; -} - sub backtick { my %arg = ( command => undef, From 3e6e5963b7cb807c6208b092173408c9f5dce76a Mon Sep 17 00:00:00 2001 From: Mat Sugumaran Date: Thu, 3 Oct 2013 11:56:54 +0200 Subject: [PATCH 103/458] bug fix #4913 --- centreon/lib/perl/centreon/reporting/CentreonLog.pm | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/centreon/lib/perl/centreon/reporting/CentreonLog.pm b/centreon/lib/perl/centreon/reporting/CentreonLog.pm index c11ad4a6017..f740cb823ad 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonLog.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonLog.pm @@ -87,7 +87,7 @@ sub getLogOfHosts { " AND `ctime` < ".$end. " AND (`type` = 1 OR (`status` = 0 AND `type` = 0))". " AND `msg_type` IN ('0', '1', '6', '7', '8', '9')". - " AND `service_id` IS NULL". + " AND `service_description` IS NULL". " ORDER BY `ctime`"; } my ($status, $result) = $centstorage->query($query); @@ -114,4 +114,4 @@ sub getFirstLastLogTime { return ($start, $end); } -1; \ No newline at end of file +1; From e69084eae63cd3ad6b0799373c20f4820997efb6 Mon Sep 17 00:00:00 2001 From: Julien Mathis Date: Thu, 17 Oct 2013 11:59:26 +0200 Subject: [PATCH 104/458] fix #4943 --- centreon/lib/perl/centreon/script/centcore.pm | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index f3f6a8fe833..d725d2e9be9 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -40,6 +40,7 @@ sub new { $self->{timeBetween2SyncPerf} = 60; $self->{perfdataSync} = 0; $self->{logSync} = 0; + $self->{enable_broker_stats} = 0; $self->{stop} = 1; $self->{reload} = 1; @@ -166,6 +167,7 @@ sub moveCmdFile($){ # sub GetAllNagiosServerPerfData { my $self = shift; + my ($status, $sth) = $self->{centreon_dbc}->query("SELECT `id` FROM `nagios_server` WHERE `localhost` = '0' AND `ns_activate` = '1'"); if ($status == -1) { $self->{logger}->writeLogError("Error when getting server properties"); @@ -181,9 +183,10 @@ sub GetAllNagiosServerPerfData { if ($self->{logSync} == 1) { $self->GetLogFile($data->{'id'}); } - $self->getBrokerStats($data->{'id'}); + if ($self->{enable_broker_stats} == 1) { + $self->getBrokerStats($data->{'id'}); + } } - return 0; } @@ -351,7 +354,7 @@ sub sendExternalCommand($$){ ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd2, logger => $self->{logger}, timeout => $self->{cmd_timeout} - ); + ); if ($lerror == -1) { $self->{logger}->writeLogError("Could not write into pipe file ".$command_file." on poller ".$id); } @@ -981,7 +984,7 @@ sub parseRequest($){ sub checkProfile() { my $self = shift; - my $request = "SELECT * FROM options WHERE `key` IN ('enable_perfdata_sync', 'enable_logs_sync', 'centcore_cmd_timeout')"; + my $request = "SELECT * FROM options WHERE `key` IN ('enable_perfdata_sync', 'enable_logs_sync', 'centcore_cmd_timeout', 'enable_broker_stats')"; my ($status, $sth) = $self->{centreon_dbc}->query($request); return -1 if ($status == -1); while ((my $data = $sth->fetchrow_hashref())) { @@ -995,6 +998,9 @@ sub checkProfile() { if ($data->{'key'} eq "centcore_cmd_timeout") { $self->{cmd_timeout} = $data->{'value'}; } + if ($data->{'key'} eq "enable_broker_stats") { + $self->{enable_broker_stats} = $data->{'value'}; + } } } return 0; From fdbf993ebd046322c1b62c2cc31656ecda21d9de Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 23 Oct 2013 18:19:07 +0200 Subject: [PATCH 105/458] Initial version: Centreon plugin library --- centreon/lib/perl/centreon/plugins/mode.pm | 53 ++ centreon/lib/perl/centreon/plugins/options.pm | 104 ++++ centreon/lib/perl/centreon/plugins/output.pm | 473 +++++++++++++++ .../lib/perl/centreon/plugins/perfdata.pm | 219 +++++++ centreon/lib/perl/centreon/plugins/script.pm | 132 ++++ .../lib/perl/centreon/plugins/script_snmp.pm | 110 ++++ centreon/lib/perl/centreon/plugins/snmp.pm | 566 ++++++++++++++++++ .../lib/perl/centreon/plugins/statefile.pm | 93 +++ centreon/lib/perl/plugins/centreon_plugins.pl | 50 ++ centreon/lib/perl/plugins/os_linux/snmp.pm | 29 + .../lib/perl/plugins/snmp_standard/storage.pm | 375 ++++++++++++ .../lib/perl/plugins/snmp_standard/traffic.pm | 434 ++++++++++++++ 12 files changed, 2638 insertions(+) create mode 100644 centreon/lib/perl/centreon/plugins/mode.pm create mode 100644 centreon/lib/perl/centreon/plugins/options.pm create mode 100644 centreon/lib/perl/centreon/plugins/output.pm create mode 100644 centreon/lib/perl/centreon/plugins/perfdata.pm create mode 100644 centreon/lib/perl/centreon/plugins/script.pm create mode 100644 centreon/lib/perl/centreon/plugins/script_snmp.pm create mode 100644 centreon/lib/perl/centreon/plugins/snmp.pm create mode 100644 centreon/lib/perl/centreon/plugins/statefile.pm create mode 100644 centreon/lib/perl/plugins/centreon_plugins.pl create mode 100644 centreon/lib/perl/plugins/os_linux/snmp.pm create mode 100644 centreon/lib/perl/plugins/snmp_standard/storage.pm create mode 100644 centreon/lib/perl/plugins/snmp_standard/traffic.pm diff --git a/centreon/lib/perl/centreon/plugins/mode.pm b/centreon/lib/perl/centreon/plugins/mode.pm new file mode 100644 index 00000000000..6c304abe4dc --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/mode.pm @@ -0,0 +1,53 @@ +package centreon::plugins::mode; + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + + $self->{perfdata} = centreon::plugins::perfdata->new(output => $options{output}); + %{$self->{option_results}} = (); + $self->{output} = $options{output}; + $self->{mode} = $options{mode}; + $self->{version} = undef; + + return $self; +} + +sub init { + my ($self, %options) = @_; + # options{default} = [ {option_name => '', option_value => '' }, ] + + %{$self->{option_results}} = %{$options{option_results}}; + # Manage default value + return if (!defined($options{default})); + foreach (@{$options{default}}) { + if (defined($_->{option_mode}) && $_->{option_mode} eq $self->{mode} && !defined($self->{option_results}->{$_->{option_name}})) { + $self->{option_results}->{$_->{option_name}} = $_->{option_value}; + } + } +} + +sub version { + my ($self, %options) = @_; + + $self->{output}->add_option_msg(short_msg => "Mode Version: " . $self->{version}); +} + +sub disco_format { + my ($self, %options) = @_; + +} + +sub disco_show { + my ($self, %options) = @_; + +} + +1; + +__END__ + diff --git a/centreon/lib/perl/centreon/plugins/options.pm b/centreon/lib/perl/centreon/plugins/options.pm new file mode 100644 index 00000000000..c3840d00481 --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/options.pm @@ -0,0 +1,104 @@ + +package centreon::plugins::options; +use Pod::Usage; +use Pod::Find qw(pod_where); +use Getopt::Long; +Getopt::Long::Configure("pass_through"); +Getopt::Long::Configure('bundling'); + +sub new { + my $class = shift; + my $self = {}; + bless $self, $class; + + $self->{options_stored} = {}; + $self->{options} = {}; + @{$self->{pod_package}} = (); + return $self; +} + +sub set_output { + my ($self, %options) = @_; + + $self->{output} = $options{output}; +} + +sub display_help { + my ($self, %options) = @_; + + foreach (@{$self->{pod_package}}) { + my $stdout; + + { + local *STDOUT; + open STDOUT, '>', \$stdout; + pod2usage(-exitval => 'NOEXIT', -input => pod_where({-inc => 1}, $_->{package}), + -verbose => 99, + -sections => $_->{sections}); + } + + $self->{output}->add_option_msg(long_msg => $stdout) if (defined($stdout)); + } +} + +sub add_help { + my ($self, %options) = @_; + # $options{package} = string package + # $options{sections} = string sections + # $options{help_first} = put at the beginning + + if (defined($options{help_first})) { + shift @{$self->{pod_package}}, {package => $options{package}, sections => $options{sections}}; + } else { + push @{$self->{pod_package}}, {package => $options{package}, sections => $options{sections}}; + } +} + +sub add_options { + my ($self, %options) = @_; + # $options{arguments} = ref to hash table with string and name to store (example: { 'mode:s' => { name => 'mode', default => 'defaultvalue' ) + + foreach (keys %{$options{arguments}}) { + if (defined($options{arguments}->{$_}->{default})) { + $self->{options_stored}->{$options{arguments}->{$_}->{name}} = $options{arguments}->{$_}->{default}; + } else { + $self->{options_stored}->{$options{arguments}->{$_}->{name}} = undef; + } + $self->{options}->{$_} = \$self->{options_stored}->{$options{arguments}->{$_}->{name}}; + } +} + +sub parse_options { + my $self = shift; + #%{$self->{options_stored}} = (); + + # Need to save to check multiples times (centos 5 Getopt don't have 'GetOptionsFromArray' + my @save_argv = @ARGV; + GetOptions( + %{$self->{options}} + ); + @ARGV = @save_argv; + %{$self->{options}} = (); +} + +sub get_option { + my ($self, %options) = @_; + + return $self->{options_stored}->{$options{argument}}; +} + +sub get_options { + my $self = shift; + + return $self->{options_stored}; +} + +sub clean { + my $self = shift; + + $self->{options_stored} = {}; +} + +1; + +__END__ diff --git a/centreon/lib/perl/centreon/plugins/output.pm b/centreon/lib/perl/centreon/plugins/output.pm new file mode 100644 index 00000000000..33fafcd73e8 --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/output.pm @@ -0,0 +1,473 @@ + +package centreon::plugins::output; + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + # $options->{options} = options object + if (!defined($options{options})) { + print "Class Output: Need to specify 'options' argument to load.\n"; + exit 3; + } + + $options{options}->add_options(arguments => + { + "ignore-perfdata" => { name => 'ignore_perfdata' }, + "verbose" => { name => 'verbose' }, + "opt-exit:s" => { name => 'opt_exit', default => 'unknown' }, + "output-xml" => { name => 'output_xml' }, + "disco-format" => { name => 'disco_format' }, + "disco-show" => { name => 'disco_show' }, + }); + %{$self->{option_results}} = (); + + $self->{option_msg} = []; + + $self->{is_output_xml} = 0; + $self->{errors} = {OK => 0, WARNING => 1, CRITICAL => 2, UNKNOWN => 3, PENDING => 4}; + $self->{myerrors} = {0 => "OK", 1 => "WARNING", 3 => "CRITICAL", 7 => "UNKNOWN"}; + $self->{myerrors_mask} = {CRITICAL => 3, WARNING => 1, UNKNOWN => 7, OK => 0}; + $self->{global_short_concat_outputs} = {OK => undef, WARNING => undef, CRITICAL => undef, UNKNOWN => undef, UNQUALIFIED_YET => undef}; + $self->{global_short_outputs} = {OK => [], WARNING => [], CRITICAL => [], UNKNOWN => [], UNQUALIFIED_YET => []}; + $self->{global_long_output} = []; + $self->{perfdatas} = []; + $self->{global_status} = 0; + + $self->{disco_elements} = []; + $self->{disco_entries} = []; + + $self->{plugin} = ''; + $self->{mode} = ''; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + # $options{option_results} = ref to options result + + %{$self->{option_results}} = %{$options{option_results}}; + $self->{option_results}->{opt_exit} = lc($self->{option_results}->{opt_exit}); + if (!$self->is_litteral_status(status => $self->{option_results}->{opt_exit})) { + $self->add_option_msg(short_msg => "Unknown value '" . $self->{option_results}->{opt_exit} . "' for --opt-exit."); + $self->option_exit(exit_litteral => 'unknown'); + } + # Go in XML Mode + if ($self->is_disco_show() || $self->is_disco_format()) { + $self->{option_results}->{output_xml} = 1; + } +} + +sub add_option_msg { + my ($self, %options) = @_; + # $options{short_msg} = string msg + # $options{long_msg} = string msg + $options{severity} = 'UNQUALIFIED_YET'; + + $self->output_add(%options); +} + +sub set_status { + my ($self, %options) = @_; + # $options{exit_litteral} = string litteral exit + + # Nothing to do for 'UNQUALIFIED_YET' + if (!$self->{myerrors_mask}->{uc($options{exit_litteral})}) { + return ; + } + $self->{global_status} |= $self->{myerrors_mask}->{uc($options{exit_litteral})}; +} + +sub output_add { + my ($self, %params) = @_; + my %args = ( + severity => 'OK', + separator => ' - ', + short_msg => undef, + long_msg => undef + ); + my $options = {%args, %params}; + + if (defined($options->{short_msg})) { + chomp $options->{short_msg}; + if (defined($self->{global_short_concat_outputs}->{uc($options->{severity})})) { + $self->{global_short_concat_outputs}->{uc($options->{severity})} .= $options->{separator} . $options->{short_msg}; + } else { + $self->{global_short_concat_outputs}->{uc($options->{severity})} = $options->{short_msg}; + } + + push @{$self->{global_short_outputs}->{uc($options->{severity})}}, $options->{short_msg}; + $self->set_status(exit_litteral => $options->{severity}); + } + if (defined($options->{long_msg})) { + chomp $options->{long_msg}; + push @{$self->{global_long_output}}, $options->{long_msg}; + } +} + +sub perfdata_add { + my ($self, %options) = @_; + my $perfdata = {'label' => '', 'value' => '', unit => '', warning => '', critical => '', min => '', max => ''}; + $perfdata = {%$perfdata, %options}; + push @{$self->{perfdatas}}, $perfdata; +} + +sub output_xml { + my ($self, %options) = @_; + my ($child_plugin_name, $child_plugin_mode, $child_plugin_exit, $child_plugin_output, $child_plugin_perfdata); + + my $root = $self->{xml_output}->createElement('plugin'); + $self->{xml_output}->setDocumentElement($root); + + $child_plugin_name = $self->{xml_output}->createElement("name"); + $child_plugin_name->appendText($self->{plugin}); + + $child_plugin_mode = $self->{xml_output}->createElement("mode"); + $child_plugin_mode->appendText($self->{mode}); + + $child_plugin_exit = $self->{xml_output}->createElement("exit"); + $child_plugin_exit->appendText($options{exit_litteral}); + + $child_plugin_output = $self->{xml_output}->createElement("outputs"); + $child_plugin_perfdata = $self->{xml_output}->createElement("perfdatas"); + + $root->addChild($child_plugin_name); + $root->addChild($child_plugin_mode); + $root->addChild($child_plugin_exit); + $root->addChild($child_plugin_output); + $root->addChild($child_plugin_perfdata); + + foreach my $code_litteral (keys %{$self->{global_short_outputs}}) { + foreach (@{$self->{global_short_outputs}->{$code_litteral}}) { + my ($child_output, $child_type, $child_msg, $child_exit); + my $lcode_litteral = ($code_litteral eq 'UNQUALIFIED_YET' ? uc($options{exit_litteral}) : $code_litteral); + + $child_output = $self->{xml_output}->createElement("output"); + $child_plugin_output->addChild($child_output); + + $child_type = $self->{xml_output}->createElement("type"); + $child_type->appendText(1); # short + + $child_msg = $self->{xml_output}->createElement("msg"); + $child_msg->appendText(($options{nolabel} == 0 ? ($lcode_litteral . ': ') : '') . $_); + $child_exit = $self->{xml_output}->createElement("exit"); + $child_exit->appendText($lcode_litteral); + + $child_output->addChild($child_type); + $child_output->addChild($child_exit); + $child_output->addChild($child_msg); + } + } + + if (defined($self->{option_results}->{verbose}) || defined($options{force_long_output})) { + foreach (@{$self->{global_long_output}}) { + my ($child_output, $child_type, $child_msg); + + $child_output = $self->{xml_output}->createElement("output"); + $child_plugin_output->addChild($child_output); + + $child_type = $self->{xml_output}->createElement("type"); + $child_type->appendText(2); # long + + $child_msg = $self->{xml_output}->createElement("msg"); + $child_msg->appendText($_); + + $child_output->addChild($child_type); + $child_output->addChild($child_msg); + } + } + + if (!defined($self->{option_results}->{ignore_perfdata}) && !defined($options{force_ignore_perfdata})) { + foreach (@{$self->{perfdatas}}) { + my ($child_perfdata); + $child_perfdata = $self->{xml_output}->createElement("perfdata"); + $child_plugin_perfdata->addChild($child_perfdata); + foreach my $key (keys %$_) { + my $child = $self->{xml_output}->createElement($key); + $child->appendText($_->{$key}); + $child_perfdata->addChild($child); + } + } + } + + print $self->{xml_output}->toString(1); +} + +sub output_txt { + my ($self, %options) = @_; + + if (defined($self->{global_short_concat_outputs}->{UNQUALIFIED_YET})) { + $self->output_add(severity => uc($options{exit_litteral}), short_msg => $self->{global_short_concat_outputs}->{UNQUALIFIED_YET}); + } + + if (defined($self->{global_short_concat_outputs}->{CRITICAL})) { + print (($options{nolabel} == 0 ? 'CRITICAL: ' : '') . $self->{global_short_concat_outputs}->{CRITICAL} . " "); + } + if (defined($self->{global_short_concat_outputs}->{WARNING})) { + print (($options{nolabel} == 0 ? 'WARNING: ' : '') . $self->{global_short_concat_outputs}->{WARNING} . " "); + } + if (defined($self->{global_short_concat_outputs}->{UNKNOWN})) { + print (($options{nolabel} == 0 ? 'UNKNOWN: ' : '') . $self->{global_short_concat_outputs}->{UNKNOWN} . " "); + } + if (uc($options{exit_litteral}) eq 'OK') { + print (($options{nolabel} == 0 ? 'OK: ' : '') . $self->{global_short_concat_outputs}->{OK}); + } + + if (defined($options{force_ignore_perfdata}) || defined($self->{option_results}->{ignore_perfdata})) { + print "\n"; + } else { + print "|"; + foreach (@{$self->{perfdatas}}) { + print " '" . $_->{label} . "'=" . $_->{value} . $_->{unit} . ";" . $_->{warning} . ";" . $_->{critical} . ";" . $_->{min} . ";" . $_->{max} . ";"; + } + print "\n"; + } + + if (defined($self->{option_results}->{verbose}) || defined($options{force_long_output})) { + if (scalar(@{$self->{global_long_output}})) { + print join("\n", @{$self->{global_long_output}}); + print "\n"; + } + } +} + +sub display { + my ($self, %options) = @_; + + if (defined($self->{option_results}->{output_xml})) { + $self->create_xml_document(); + if ($self->{is_output_xml}) { + $self->output_xml(exit_litteral => $self->get_litteral_status()); + } else { + $self->output_txt(exit_litteral => $self->get_litteral_status()); + } + } else { + $self->output_txt(exit_litteral => $self->get_litteral_status()); + } +} + +sub option_exit { + my ($self, %options) = @_; + # $options{exit_litteral} = string litteral exit + # $options{nolabel} = interger label display + my $exit_litteral = defined($options{exit_litteral}) ? $options{exit_litteral} : $self->{option_results}->{opt_exit}; + my $nolabel = defined($options{nolabel}) ? 1 : 0; + + if (defined($self->{option_results}->{output_xml})) { + $self->create_xml_document(); + if ($self->{is_output_xml}) { + $self->output_xml(exit_litteral => $exit_litteral, nolabel => $nolabel, force_ignore_perfdata => 1, force_long_output => 1); + } else { + $self->output_txt(exit_litteral => $exit_litteral, nolabel => $nolabel, force_ignore_perfdata => 1, force_long_output => 1); + } + } else { + $self->output_txt(exit_litteral => $exit_litteral, nolabel => $nolabel, force_ignore_perfdata => 1, force_long_output => 1); + } + + $self->exit(exit_litteral => $exit_litteral); +} + +sub exit { + my ($self, %options) = @_; + # $options{exit_litteral} = exit + + if (defined($options{exit_litteral})) { + exit $self->{errors}->{uc($options{exit_litteral})}; + } + exit $self->{errors}->{$self->{myerrors}->{$self->{global_status}}}; +} + +sub get_most_critical { + my ($self, %options) = @_; + my $current_status = 0; # For 'OK' + + foreach (@{$options{status}}) { + if ($self->{myerrors_mask}->{uc($_)} > $current_status) { + $current_status = $self->{myerrors_mask}->{uc($_)}; + } + } + return $self->{myerrors}->{$current_status}; +} + +sub get_litteral_status { + my ($self, %options) = @_; + + return $self->{myerrors}->{$self->{global_status}}; +} + +sub is_status { + my ($self, %options) = @_; + # $options{value} = string status + # $options{litteral} = value is litteral + # $options{compare} = string status + + if (defined($options{litteral})) { + my $value = defined($options{value}) ? $options{value} : $self->get_litteral_status(); + + if (uc($value) eq uc($options{compare})) { + return 1; + } + return 0; + } + + my $value = defined($options{value}) ? $options{value} : $self->{global_status}; + my $dec_val = $self->{myerrors_mask}->{$value}; + my $lresult = $value & $dec_val; + # Need to manage 0 + if ($lresult > 0 || ($dec_val == 0 && $value == 0)) { + return 1; + } + return 0; +} + +sub is_litteral_status { + my ($self, %options) = @_; + # $options{status} = string status + + if (defined($self->{errors}->{uc($options{status})})) { + return 1; + } + + return 0; +} + +sub create_xml_document { + my ($self) = @_; + + require XML::LibXML; + $self->{is_output_xml} = 1; + $self->{xml_output} = XML::LibXML::Document->new('1.0', 'utf-8'); +} + +sub plugin { + my ($self, %options) = @_; + # $options{name} = string name + + if (defined($options{name})) { + $self->{plugin} = $options{name}; + } + return $self->{plugin}; +} + +sub mode { + my ($self, %options) = @_; + # $options{name} = string name + + if (defined($options{name})) { + $self->{mode} = $options{name}; + } + return $self->{mode}; +} + +sub add_disco_format { + my ($self, %options) = @_; + + push @{$self->{disco_elements}}, @{$options{elements}}; +} + +sub display_disco_format { + my ($self, %options) = @_; + + $self->create_xml_document(); + + my $root = $self->{xml_output}->createElement('data'); + $self->{xml_output}->setDocumentElement($root); + + foreach (@{$self->{disco_elements}}) { + my $child = $self->{xml_output}->createElement("element"); + $child->appendText($_); + $root->addChild($child); + } + + print $self->{xml_output}->toString(1); +} + +sub display_disco_show { + my ($self, %options) = @_; + + $self->create_xml_document(); + + my $root = $self->{xml_output}->createElement('data'); + $self->{xml_output}->setDocumentElement($root); + + foreach (@{$self->{disco_entries}}) { + my $child = $self->{xml_output}->createElement("label"); + foreach my $key (keys %$_) { + $child->setAttribute($key, $_->{$key}); + } + $root->addChild($child); + } + + print $self->{xml_output}->toString(1); +} + +sub add_disco_entry { + my ($self, %options) = @_; + + push @{$self->{disco_entries}}, {%options}; +} + +sub is_disco_format { + my ($self) = @_; + + if (defined($self->{option_results}->{disco_format}) ) { + return 1; + } + return 0; +} + +sub is_disco_show { + my ($self) = @_; + + if ( defined($self->{option_results}->{disco_show}) ) { + return 1; + } + return 0; +} + +1; + +__END__ + +=head1 NAME + +Output class + +=head1 SYNOPSIS + +- + +=head1 OUTPUT OPTIONS + +=over 8 + +=item B<--verbose> + +Display long output. + +=item B<--ignore-perfdata> + +Don't display perfdata. + +=item B<--opt-exit> + +Exit code for an option error, usage (default: unknown). + +=item B<--output-xml> + +Display output in XML Format. + +=item B<--disco-format> + +Display discovery arguments (if the mode manages it). + +=item B<--disco-show> + +Display discovery values (if the mode manages it). + +=head1 DESCRIPTION + +B. + +=cut diff --git a/centreon/lib/perl/centreon/plugins/perfdata.pm b/centreon/lib/perl/centreon/plugins/perfdata.pm new file mode 100644 index 00000000000..d52cbac38d9 --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/perfdata.pm @@ -0,0 +1,219 @@ + +package centreon::plugins::perfdata; + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + + $self->{output} = $options{output}; + # Typical Nagios Perfdata 'with ~ @ ..' + $self->{threshold_label} = {}; + + return $self; +} + +sub get_perfdata_for_output { + my ($self, %options) = @_; + # $options{label} : threshold label + # $options{total} : percent threshold to transform in global + # $options{cast_int} : cast absolute to int + + my $perf_output = $self->{threshold_label}->{$options{label}}->{value}; + if (defined($perf_output) && $perf_output ne '' && defined($options{total})) { + $perf_output = ($self->{threshold_label}->{$options{label}}->{arobase} == 1 ? "@" : "") . + (($self->{threshold_label}->{$options{label}}->{infinite_neg} == 0) ? (defined($options{cast_int}) ? sprintf("%d", ($self->{threshold_label}->{$options{label}}->{start} * $options{total} / 100)) : sprintf("%.2f", ($self->{threshold_label}->{$options{label}}->{start} * $options{total} / 100))) : "") . + ":" . + (($self->{threshold_label}->{$options{label}}->{infinite_pos} == 0) ? (defined($options{cast_int}) ? sprintf("%d", ($self->{threshold_label}->{$options{label}}->{end} * $options{total} / 100)) : sprintf("%.2f", ($self->{threshold_label}->{$options{label}}->{end} * $options{total} / 100))) : ""); + } + + if (!defined($perf_output)) { + $perf_output = ''; + } + return $perf_output; +} + +sub threshold_validate { + my ($self, %options) = @_; + # $options{label} : threshold label + # $options{value} : threshold value + + my $status = 1; + $self->{threshold_label}->{$options{label}} = {'value' => $options{value}, 'start' => undef, 'end' => undef, 'arobase' => undef, infinite_neg => undef, intinite_pos => undef}; + if (!defined($options{value}) || $options{value} eq '') { + return $status; + } + + ($status, $self->{threshold_label}->{$options{label}}->{start}, $self->{threshold_label}->{$options{label}}->{end}, $self->{threshold_label}->{$options{label}}->{arobase}, $self->{threshold_label}->{$options{label}}->{infinite_neg}, $self->{threshold_label}->{$options{label}}->{infinite_pos}) = $self->parse_threshold($options{value}); + + return $status; +} + +sub threshold_check { + my ($self, %options) = @_; + # Can check multiple threshold. First match: out. Order is important + # options{value}: value to compare + # options{threshold}: ref to an array (example: [ {label => 'warning', exit_litteral => 'warning' }, {label => 'critical', exit_litteral => 'critical'} ] + foreach (@{$options{threshold}}) { + next if (!defined($self->{threshold_label}->{$_->{label}})); + next if (!defined($self->{threshold_label}->{$_->{label}}->{value}) || $self->{threshold_label}->{$_->{label}}->{value} eq ''); + if ($self->{threshold_label}->{$_->{label}}->{arobase} == 0 && ($options{value} < $self->{threshold_label}->{$_->{label}}->{start} || $options{value} > $self->{threshold_label}->{$_->{label}}->{end})) { + return $_->{exit_litteral}; + } elsif ($self->{threshold_label}->{$_->{label}}->{arobase} == 1 && ($options{value} >= $self->{threshold_label}->{$_->{label}}->{end} && $options{value} <= $self->{threshold_label}->{$_->{label}}->{end})) { + return $_->{exit_litteral}; + } + } + + return 'ok'; +} + +sub trim { + my ($self, $value) = @_; + + $value =~ s/^[ \t]+//; + $value =~ s/[ \t]+$//; + return $value; +} + +sub continue_to { + my $self = shift; + my ($forbidden, $stop1, $not_stop_after) = @_; + my $value = ""; + + while ($self->{perfdata_pos} < $self->{perfdata_size}) { + if (defined($forbidden) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] =~ /$forbidden/) { + return undef; + } + if (${$self->{perfdata_chars}}[$self->{perfdata_pos}] =~ /$stop1/) { + if (!defined($not_stop_after)) { + return $value; + } + if (!($self->{perfdata_pos} + 1 < $self->{perfdata_size} && ${$self->{perfdata_chars}}[$self->{perfdata_pos} + 1] =~ /$not_stop_after/)) { + $self->{perfdata_pos}++; + return $value; + } + $self->{perfdata_pos}++; + } + + $value .= ${$self->{perfdata_chars}}[$self->{perfdata_pos}]; + $self->{perfdata_pos}++; + } + + return $value; +} + +sub parse_threshold { + my $self = shift; + + @{$self->{perfdata_chars}} = split //, $self->trim($_[0]); + $self->{perfdata_pos} = 0; + $self->{perfdata_size} = scalar(@{$self->{perfdata_chars}}); + + my $neg = 1; + my $value_tmp = ""; + + my $arobase = 0; + my $infinite_neg = 0; + my $infinite_pos = 0; + my $value_start = ""; + my $value_end = ""; + my $global_status = 1; + + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq "@") { + $arobase = 1; + $self->{perfdata_pos}++; + } + + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq "~") { + $infinite_neg = 1; + $self->{perfdata_pos}++; + } else { + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq "-") { + $neg = -1; + $self->{perfdata_pos}++; + } + $value_tmp = $self->continue_to(undef, "[^0-9\.,]"); + if (defined($value_tmp) && $value_tmp ne "") { + $value_tmp =~ s/,/./g; + $value_tmp = $value_tmp * $neg; + } + $neg = 1; + } + + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq ":") { + if ($value_tmp ne "") { + $value_start = $value_tmp; + } else { + $value_start = 0; + } + $self->{perfdata_pos}++; + + if (defined(${$self->{perfdata_chars}}[$self->{perfdata_pos}]) && ${$self->{perfdata_chars}}[$self->{perfdata_pos}] eq "-") { + $neg = -1; + $self->{perfdata_pos}++; + } + $value_end = $self->continue_to(undef, "[^0-9\.,]"); + if (defined($value_tmp) && $value_end ne "") { + $value_end =~ s/,/./g; + $value_end = $value_end * $neg; + } else { + $infinite_pos = 1; + } + } else { + $value_start = 0; + $value_end = $value_tmp; + } + + my $value = $self->continue_to(undef, "[ \t;]"); + if ($value ne '') { + $global_status = 0; + } + + if ($infinite_neg == 1) { + $value_start = '-1e500'; + } + if ($infinite_pos == 1) { + $value_end = '1e500'; + } + + return ($global_status, $value_start, $value_end, $arobase, $infinite_neg, $infinite_pos); +} + +sub change_bytes { + my ($self, %options) = @_; + + my $unit = defined($options{network}) ? 'b' : 'B'; + my $divide = defined($options{network}) ? 1000 : 1024; + + if (($options{value} / $divide) >= 1) { + $options{value} = $options{value} / $divide; + $unit = defined($options{network}) ? 'Kb' : 'KB'; + } + if (($options{value} / $divide) >= 1) { + $options{value} = $options{value} / $divide; + $unit = defined($options{network}) ? 'Mb' : 'MB'; + } + if (($options{value} / $divide) >= 1) { + $value = $options{value} / $divide; + $unit = defined($options{network}) ? 'Gb' : 'GB'; + } + return (sprintf("%.2f", $options{value}), $unit); +} + +1; + +__END__ + +=head1 NAME + +Perfdata class + +=head1 SYNOPSIS + +- + +=head1 DESCRIPTION + +B. + +=cut diff --git a/centreon/lib/perl/centreon/plugins/script.pm b/centreon/lib/perl/centreon/plugins/script.pm new file mode 100644 index 00000000000..834fa8d770c --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/script.pm @@ -0,0 +1,132 @@ +package centreon::plugins::script; + +use strict; +use warnings; +use centreon::plugins::options; +use centreon::plugins::output; +use FindBin; +use Pod::Usage; + +my %handlers = ('DIE' => {}); + +sub new { + my $class = shift; + my $self = {}; + bless $self, $class; + + $self->{options} = undef; + $self->{plugin} = undef; + $self->{help} = undef; + + $self->set_signal_handlers; + return $self; +} + +sub set_signal_handlers { + my $self = shift; + + $SIG{__DIE__} = \&class_handle_DIE; + $handlers{DIE}->{$self} = sub { $self->handle_DIE($_[0]) }; +} + +sub class_handle_DIE { + my ($msg) = @_; + + foreach (keys %{$handlers{DIE}}) { + &{$handlers{DIE}->{$_}}($msg); + } +} + +sub handle_DIE { + my ($self, $msg) = @_; + + $self->{output}->add_option_msg(short_msg => $msg); + $self->{output}->option_exit(); +} + +sub get_plugin { + my $self = shift; + + $self->{options} = centreon::plugins::options->new(); + $self->{output} = centreon::plugins::output->new(options => $self->{options}); + $self->{options}->set_output(output => $self->{output}); + + $self->{options}->add_options(arguments => { + 'plugin:s' => { name => 'plugin' }, + 'mode:s' => { name => 'mode' }, + 'help' => { name => 'help' }, + 'list' => { name => 'list' }, + 'version' => { name => 'version' } } ); + + $self->{options}->parse_options(); + + $self->{plugin} = $self->{options}->get_option(argument => 'plugin' ); + $self->{mode} = $self->{options}->get_option(argument => 'mode' ); + $self->{list} = $self->{options}->get_option(argument => 'list' ); + $self->{help} = $self->{options}->get_option(argument => 'help' ); + $self->{version} = $self->{options}->get_option(argument => 'version' ); + + $self->{output}->mode(name => $self->{mode}); + $self->{output}->plugin(name => $self->{plugin}); + + $self->{output}->check_options(option_results => $self->{options}->get_options()); + + $self->{options}->clean(); +} + +sub display_local_help { + my $self = shift; + + my $stdout; + if ($self->{help}) { + local *STDOUT; + open STDOUT, '>', \$stdout; + pod2usage(-exitval => "NOEXIT", -input => $FindBin::Bin . "/" . $FindBin::Script); + } + + $self->{output}->add_option_msg(long_msg => $stdout) if (defined($stdout)); +} + +sub run { + my $self = shift; + + $self->get_plugin(); + + if (!defined($self->{plugin}) || $self->{plugin} eq '') { + $self->{output}->add_option_msg(short_msg => "Need to specify '--plugin' option."); + $self->display_local_help(); + $self->{output}->option_exit(); + } + (my $file = $self->{plugin} . ".pm") =~ s{::}{/}g; + require $file; + my $plugin = $self->{plugin}->new(options => $self->{options}, output => $self->{output}); + + if (defined($self->{version}) && !defined($self->{mode})) { + $plugin->version(); + } + if (defined($self->{list})) { + $plugin->list(); + } + if (!defined($self->{mode}) || $self->{mode} eq '') { + $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' option."); + $self->display_local_help(); + $self->{output}->option_exit(); + } + + $plugin->is_mode(mode => $self->{mode}); + + $plugin->init(mode => $self->{mode}, + help => $self->{help}, + version => $self->{version}); + $plugin->run(); +} + +1; + +__END__ + +=head1 NAME + +Class global script. + +=cut diff --git a/centreon/lib/perl/centreon/plugins/script_snmp.pm b/centreon/lib/perl/centreon/plugins/script_snmp.pm new file mode 100644 index 00000000000..82ad8d9e438 --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/script_snmp.pm @@ -0,0 +1,110 @@ +package centreon::plugins::script_snmp; + +use strict; +use warnings; +use centreon::plugins::snmp; +use centreon::plugins::output; + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + # $options{options} = options object + # $options{output} = output object + + $self->{version} = '1.0'; + %{$self->{modes}} = (); + $self->{default} = undef; + + $self->{options} = $options{options}; + $self->{output} = $options{output}; + $self->{options}->add_help(package => $options{package}, sections => 'PLUGIN DESCRIPTION'); + + return $self; +} + +sub init { + my ($self, %options) = @_; + # $options{mode} = string mode + # $options{help} = string help + + # Load output + $self->{options}->add_help(package => 'centreon::plugins::output', sections => 'OUTPUT OPTIONS'); + + # SNMP + $self->{snmp} = centreon::plugins::snmp->new(options => $self->{options}, output => $self->{output}); + + # Load mode + (my $file = $self->{modes}{$options{mode}} . ".pm") =~ s{::}{/}g; + require $file; + $self->{mode} = $self->{modes}{$options{mode}}->new(options => $self->{options}, output => $self->{output}, mode => $options{mode}); + + if (defined($options{help})) { + $self->{options}->add_help(package => $self->{modes}{$options{mode}}, sections => 'MODE'); + $self->{options}->display_help(); + $self->{output}->option_exit(); + } + if (defined($options{version})) { + $self->{mode}->version(); + $self->{output}->option_exit(nolabel => 1); + } + + $self->{options}->parse_options(); + $self->{option_results} = $self->{options}->get_options(); + + $self->{snmp}->check_options(option_results => $self->{option_results}); + $self->{mode}->check_options(option_results => $self->{option_results}, default => $self->{default}); +} + +sub run { + my $self = shift; + + if ($self->{output}->is_disco_format()) { + $self->{mode}->disco_format(); + $self->{output}->display_disco_format(); + $self->{output}->exit(exit_litteral => 'ok'); + } + + $self->{snmp}->connect(); + if ($self->{output}->is_disco_show()) { + $self->{mode}->disco_show(snmp => $self->{snmp}); + $self->{output}->display_disco_show(); + $self->{output}->exit(exit_litteral => 'ok'); + } else { + $self->{mode}->run(snmp => $self->{snmp}); + } +} + +sub is_mode { + my ($self, %options) = @_; + + # $options->{mode} = mode + if (!defined($self->{modes}{$options{mode}})) { + $self->{output}->add_option_msg(short_msg => "mode '" . $options{mode} . "' doesn't exist (use --list option to show available modes)."); + $self->{output}->option_exit(); + } +} + +sub version { + my $self = shift; + $self->{options}->display_help(); + + $self->{output}->add_option_msg(long_msg => "Plugin Version: " . $self->{version}); + $self->{output}->option_exit(nolabel => 1); +} + +sub list { + my $self = shift; + $self->{options}->display_help(); + + $self->{output}->add_option_msg(long_msg => "Modes Available:"); + foreach (keys %{$self->{modes}}) { + $self->{output}->add_option_msg(long_msg => " " . $_); + } + $self->{output}->option_exit(nolabel => 1); +} + +1; + +__END__ + diff --git a/centreon/lib/perl/centreon/plugins/snmp.pm b/centreon/lib/perl/centreon/plugins/snmp.pm new file mode 100644 index 00000000000..1b85f8f93d3 --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/snmp.pm @@ -0,0 +1,566 @@ + +# use net-snmp api. + +package centreon::plugins::snmp; + +use strict; +use warnings; +use SNMP; +use Socket; + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + # $options{options} = options object + # $options{output} = output object + # $options{exit_value} = integer + + if (!defined($options{output})) { + print "Class SNMP: Need to specify 'output' argument.\n"; + exit 3; + } + if (!defined($options{options})) { + $options{output}->add_option_msg(short_msg => "Class SNMP: Need to specify 'options' argument."); + $options{output}->option_exit(); + } + + $options{options}->add_options(arguments => + { "H|hostname|host:s" => { name => 'host' }, + "C|community:s" => { name => 'snmp_community', default => 'public' }, + "v|snmp|snmp-version:s" => { name => 'snmp_version', default => 1 }, + "P|snmpport|snmp-port:i" => { name => 'snmp_port', default => 161 }, + "snmp-timeout:s" => { name => 'snmp_timeout', default => 1 }, + "snmp-retries:s" => { name => 'snmp_retries', default => 5 }, + "maxrepetitions:s" => { name => 'maxrepetitions', default => 50 }, + "u|username:s" => { name => 'snmp_security_name' }, + "authpassphrase:s" => { name => 'snmp_auth_passphrase' }, + "authprotocol:s" => { name => 'snmp_auth_protocol' }, + "privpassphrase:s" => { name => 'snmp_priv_passphrase' }, + "privprotocol:s" => { name => 'snmp_priv_protocol' }, + "contextname:s" => { name => 'snmp_context_name' }, + "contextengineid:s" => { name => 'snmp_context_engine_id' }, + "securityengineid:s" => { name => 'snmp_security_engine_id' }, + "snmp-errors-exit:s" => { name => 'snmp_errors_exit', default => 'unknown' }, + }); + $options{options}->add_help(package => __PACKAGE__, sections => 'SNMP OPTIONS'); + + ##### + $self->{session} = undef; + $self->{output} = $options{output}; + $self->{maxrepetitions} = undef; + $self->{snmp_params} = {}; + + # Dont load MIB + $SNMP::auto_init_mib = 0; + # For snmpv v1 - get request retries when you have "NoSuchName" + $self->{RetryNoSuch} = 1; + # Dont try to translate OID (we keep value) + $self->{UseNumeric} = 1; + + return $self; +} + +sub connect { + my ($self, %options) = @_; + # $options{exit_value} = integer + + my ($exit_value) = defined($options{exit_value}) ? $options{exit_value} : $self->{global_exit_value}; + + $self->{snmp_params}->{RetryNoSuch} = $self->{RetryNoSuch}; + $self->{snmp_params}->{UseNumeric} = $self->{UseNumeric}; + + if (!$self->{output}->is_litteral_status(status => $self->{snmp_errors_exit})) { + $self->{output}->add_option_msg(short_msg => "Unknown value '" . $self->{snmp_errors_exit} . "' for --snmp-errors-exit."); + $self->{output}->option_exit(exit_litteral => 'unknown'); + } + + $self->{session} = new SNMP::Session(%{$self->{snmp_params}}); + if ($self->{session}->{ErrorNum}) { + $self->{output}->add_option_msg(short_msg => 'UNKNOWN: SNMP Session : ' . $self->{session}->{ErrorStr}); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); + } +} + +sub load { + my ($self, %options) = @_; + # $options{oids} = ref to array of oids (example: ['.1.2', '.1.2']) + # $options{instances} = ref to array of oids instances + # $options{begin}, $args->{end} = integer instance end + # 3 way to use: with instances, with end, none + + if (defined($options{end})) { + for (my $i = $options{begin}; $i <= $options{end}; $i++) { + foreach (@{$options{oids}}) { + push @{$self->{oids_loaded}}, $_ . "." . $i; + } + } + return ; + } + + if (defined($options{instances})) { + foreach my $instance (@{$options{instances}}) { + $instance =~ /(\d+)$/; + foreach (@{$options{oids}}) { + push @{$self->{oids_loaded}}, $_ . "." . $1; + } + } + return ; + } + + push @{$self->{oids_loaded}}, @{$options{oids}}; +} + +sub get_leef { + my ($self, %options) = @_; + # $options{dont_quit} = integer + # $options{nothing_quit} = integer + # $options{oids} = ref to array of oids (example: ['.1.2', '.1.2']) + + # Returns array + # 'undef' value for an OID means NoSuchValue + + my ($dont_quit) = (defined($options{dont_quit}) && $options{dont_quit} == 1) ? 1 : 0; + my ($nothing_quit) = (defined($options{nothing_quit}) && $options{nothing_quit} == 1) ? 1 : 0; + + if (!defined($options{oids})) { + if ($#{$self->{oids_loaded}} < 0) { + if ($dont_quit == 1) { + return (-1, undef, "Need to specify OIDs"); + } + $self->{output}->add_option_msg(short_msg => 'Need to specify OIDs'); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); + } + push @{$options{oids}}, @{$self->{oids_loaded}}; + @{$self->{oids_loaded}} = (); + } + + my $results = {}; + my @array_ref_ar = (); + foreach my $oid (@{$options{oids}}) { + # Get last value + next if ($oid !~ /(.*)\.(\d+)([\.\s]*)$/); + + my ($oid, $instance) = ($1, $2); + $results->{$oid . "." . $instance} = undef; + push @array_ref_ar, [$oid, $instance]; + } + + ############################ + # If wrong oid with SNMP v1, packet resent (2 packets more). Not the case with SNMP > 1. + # Can have "NoSuchName", if nothing works... + # = v1: wrong oid + # bless( [ + # '.1.3.6.1.2.1.1.3', + # '0', + # '199720062', + # 'TICKS' + # ], 'SNMP::Varbind' ), + # bless( [ + # '.1.3.6.1.2.1.1.999', + # '0' + # ], 'SNMP::Varbind' ), + # bless( [ + # '.1.3.6.1.2.1.1', + # '1000' + # ], 'SNMP::Varbind' ) + # > v1: wrong oid + # bless( [ + # '.1.3.6.1.2.1.1.3', + # '0', + # '199728713', + # 'TICKS' + # ], 'SNMP::Varbind' ), + # bless( [ + # '.1.3.6.1.2.1.1', + # '3', + # 'NOSUCHINSTANCE', + # 'TICKS' + # ], 'SNMP::Varbind' ) + # bless( [ + # '.1.3.6.1.2.1.1.999', + # '0', + # 'NOSUCHOBJECT', + # 'NOSUCHOBJECT' + # ], 'SNMP::Varbind' ), + # bless( [ + # '.1.3.6.1.2.1.1', + # '1000', + # 'NOSUCHOBJECT', + # 'NOSUCHOBJECT' + # ], 'SNMP::Varbind' ) + ############################ + + my $vb = new SNMP::VarList(@array_ref_ar); + $self->{session}->get($vb); + if ($self->{session}->{ErrorNum}) { + my $msg = 'SNMP GET Request : ' . $self->{session}->{ErrorStr}; + + if ($dont_quit == 0) { + $self->{output}->add_option_msg(short_msg => $msg); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); + } + + return (-1, undef, $msg); + } + + my $total = 0; + foreach my $entry (@$vb) { + if ($#$entry < 3) { + # Can be snmpv1 not find + next; + } + if (${$entry}[2] eq 'NOSUCHOBJECT' || ${$entry}[2] eq 'NOSUCHINSTANCE') { + # Error in snmp > 1 + next; + } + + $total++; + $results->{${$entry}[0] . "." . ${$entry}[1]} = ${$entry}[2]; + } + + if ($nothing_quit == 1 && $total == 0) { + $self->{output}->add_option_msg(short_msg => "SNMP GET Request : Cant get a single value."); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); + } + + return (0, $results); +} + +sub get_table { + my ($self, %options) = @_; + # $options{dont_quit} = integer + # $options{oid} = string (example: '.1.2') + # $options{start} = string (example: '.1.2') + # $options{end} = string (example: '.1.2') + + my ($dont_quit) = (defined($options{dont_quit}) && $options{dont_quit} == 1) ? 1 : 0; + if (defined($options{start})) { + $options{start} = $self->clean_oid($options{start}); + } + my ($end_base, $end_instance); + if (defined($options{end})) { + $options{end} = $self->clean_oid($options{end}); + } + + # we use a medium (UDP have a PDU limit. SNMP protcol cant send multiples for one request) + # So we need to manage + # It's for "bulk". We ask 50 next values. If you set 1, it's like a getnext (snmp v1) + my $repeat_count = 50; + if (defined($self->{maxrepetitions}) && + $self->{maxrepetitions} =~ /^d+$/) { + $repeat_count = $self->{maxrepetitions}; + } + + # Transform asking + if ($options{oid} !~ /(.*)\.(\d+)([\.\s]*)$/) { + if ($dont_quit == 1) { + return (-1, undef, "Method 'get_table': Wrong OID '" . $options{oid} . "'."); + } + $self->{output}->add_option_msg(short_msg => "Method 'get_table': Wrong OID '" . $options{oid} . "'."); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); + } + + my $main_indice = $1 . "." . $2; + my $results = {}; + + # Quit if base not the same or 'ENDOFMIBVIEW' value + my $leave = 1; + my $last_oid; + + if (defined($options{start})) { + $last_oid = $options{start}; + } else { + $last_oid = $options{oid}; + } + while ($leave) { + $last_oid =~ /(.*)\.(\d+)([\.\s]*)$/; + my $vb = new SNMP::VarList([$1, $2]); + + if ($self->is_snmpv1()) { + $self->{session}->getnext($vb); + } else { + $self->{session}->getbulk(0, $repeat_count, $vb); + } + + # Error + if ($self->{session}->{ErrorNum}) { + # 0 noError Pas d'erreurs. + # 1 tooBig Rénse de taille trop grande. + # 2 noSuchName Variable inexistante. + if ($self->{session}->{ErrorNum} == 2) { + # We are at the end with snmpv1. We quit. + last; + } + my $msg = 'SNMP Table Request : ' . $self->{session}->{ErrorStr}; + + if ($dont_quit == 0) { + $self->{output}->add_option_msg(short_msg => $msg); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); + } + + return (-1, undef, $msg); + } + + # Manage + foreach my $entry (@$vb) { + if (${$entry}[2] eq 'ENDOFMIBVIEW') { + # END mib + $leave = 0; + last; + } + + # Not in same table + my $complete_oid = ${$entry}[0] . "." . ${$entry}[1]; + if ($complete_oid !~ /^$main_indice\./ || + (defined($options{end}) && $self->check_oid_up($complete_oid, $options{end}) )) { + $leave = 0; + last; + } + + $results->{$complete_oid} = ${$entry}[2]; + $last_oid = $complete_oid; + } + } + + return (0, $results); +} + +sub is_snmpv1 { + my $self = shift; + + if ($self->{snmp_params}->{Version} eq '1') { + return 1; + } + return 0; +} + +sub clean_oid { + my $self = shift; + + $_[0] =~ s/\.$//; + $_[0] =~ s/^(\d)/\.$1/; + return $_[0]; +} + +sub check_oid_up { + my $self = shift; + my ($current_oid, $end_oid) = @_; + + my @current_oid_splitted = split /\./, $current_oid; + my @end_oid_splitted = split /\./, $end_oid; + # Skip first value (before first '.' empty) + for (my $i = 1; $i <= $#current_oid_splitted && $i <= $#end_oid_splitted; $i++) { + if (int($current_oid_splitted[$i]) > int($end_oid_splitted[$i])) { + return 1; + } + } + + return 0; +} + +sub check_options { + my ($self, %options) = @_; + # $options{option_results} = ref to options result + + if (!defined($options{option_results}->{host})) { + $self->{output}->add_option_msg(short_msg => "Missing parameter -H (--host)."); + $self->{output}->option_exit(); + } + + $options{option_results}->{snmp_version} =~ s/^v//; + if ($options{option_results}->{snmp_version} !~ /1|2c|2|3/) { + $self->{output}->add_option_msg(short_msg => "Unknown snmp version."); + $self->{output}->option_exit(); + } + + $self->{maxrepetitions} = $options{option_results}->{maxrepetitions}; + $self->{snmp_errors_exit} = $options{option_results}->{snmp_errors_exit}; + + %{$self->{snmp_params}} = (DestHost => $options{option_results}->{host}, + Community => $options{option_results}->{snmp_community}, + Version => $options{option_results}->{snmp_version}, + RemotePort => $options{option_results}->{snmp_port}); + + if (defined($options{option_results}->{snmp_timeout}) && $options{option_results}->{snmp_timeout} =~ /^[0-9]+$/) { + $self->{snmp_params}->{Timeout} = $options{option_results}->{snmp_timeout} * (10**6); + } + if (defined($options{option_results}->{snmp_retries}) && $options{option_results}->{snmp_retries} =~ /^[0-9]+$/) { + $self->{snmp_params}->{Retries} = $options{option_results}->{snmp_retries}; + } + + if ($options{option_results}->{snmp_version} eq "3") { + + $self->{snmp_params}->{Context} = $options{option_results}->{snmp_context_name} if (defined($options{option_results}->{snmp_context_name})); + $self->{snmp_params}->{ContextEngineId} = $options{option_results}->{snmp_context_engine_id} if (defined($options{option_results}->{snmp_context_engine_id})); + $self->{snmp_params}->{SecEngineId} = $options{option_results}->{snmp_security_engine_id} if (defined($options{option_results}->{snmp_security_engine_id})); + $self->{snmp_params}->{SecName} = $options{option_results}->{snmp_security_name} if (defined($options{option_results}->{snmp_security_name})); + + # Certificate SNMPv3. Need net-snmp > 5.6 + if ($options{option_results}->{host} =~ /^(dtls|tls|ssh).*:/) { + $self->{snmp_params}->{OurIdentity} = $options{option_results}->{snmp_our_identity} if (defined($options{option_results}->{snmp_our_identity})); + $self->{snmp_params}->{TheirIdentity} = $options{option_results}->{snmp_their_identity} if (defined($options{option_results}->{snmp_their_identity})); + $self->{snmp_params}->{TheirHostname} = $options{option_results}->{snmp_their_hostname} if (defined($options{option_results}->{snmp_their_hostname})); + $self->{snmp_params}->{TrustCert} = $options{option_results}->{snmp_trust_cert} if (defined($options{option_results}->{snmp_trust_cert})); + $self->{snmp_params}->{SecLevel} = 'authPriv'; + return ; + } + + + if (!defined($options{option_results}->{snmp_security_name})) { + $self->{output}->add_option_msg(short_msg => "Missing paramater Security Name."); + $self->{output}->option_exit(); + } + + # unauthenticated and unencrypted + if (!defined($options{option_results}->{snmp_auth_passphrase}) && !defined($options{option_results}->{snmp_priv_passphrase})) { + $self->{snmp_params}->{SecLevel} = 'noAuthNoPriv'; + return ; + } + + if (defined($options{option_results}->{snmp_auth_passphrase}) && !defined($options{option_results}->{snmp_auth_protocol})) { + $self->{output}->add_option_msg(short_msg => "Missing parameter authenticate protocol."); + $self->{output}->option_exit(); + } + $options{option_results}->{snmp_auth_protocol} = lc($options{option_results}->{snmp_auth_protocol}); + if ($options{option_results}->{snmp_auth_protocol} ne "md5" && $options{option_results}->{snmp_auth_protocol} ne "sha") { + $self->{output}->add_option_msg(short_msg => "Wrong authentication protocol. Must be MD5 or SHA."); + $self->{output}->option_exit(); + } + + $self->{snmp_params}->{SecLevel} = 'authNoPriv'; + $self->{snmp_params}->{AuthProto} = $options{option_results}->{snmp_auth_protocol}; + $self->{snmp_params}->{AuthPass} = $options{option_results}->{snmp_auth_passphrase}; + + if (defined($options{option_results}->{snmp_priv_passphrase}) && !defined($options{option_results}->{snmp_priv_protocol})) { + $self->{output}->add_option_msg(short_msg => "Missing parameter privacy protocol."); + $self->{output}->option_exit(); + } + + if (defined($options{option_results}->{snmp_priv_protocol})) { + $options{option_results}->{snmp_priv_protocol} = lc($options{option_results}->{snmp_priv_protocol}); + if ($options{option_results}->{snmp_priv_protocol} ne 'des' && $options{option_results}->{snmp_priv_protocol} ne 'aes') { + $self->{output}->add_option_msg(short_msg => "Wrong privacy protocol. Must be DES or AES."); + $self->{output}->option_exit(); + } + + $self->{snmp_params}->{SecLevel} = 'authPriv'; + $self->{snmp_params}->{PrivPass} = $options{option_results}->{snmp_priv_passphrase}; + $self->{snmp_params}->{PrivProto} = $options{option_results}->{snmp_priv_protocol}; + } + } +} + +sub get_hostname { + my ($self) = @_; + + my $host = $self->{snmp_params}->{DestHost}; + $host =~ s/.*://; + return $host; +} + +sub oid_lex_sort { + my $self = shift; + + if (@_ <= 1) { + return @_; + } + + return map { $_->[0] } + sort { $a->[1] cmp $b->[1] } + map + { + my $oid = $_; + $oid =~ s/^\.//; + $oid =~ s/ /\.0/g; + [$_, pack 'N*', split m/\./, $oid] + } @_; +} + +1; + +__END__ + +=head1 NAME + +SNMP global + +=head1 SYNOPSIS + +snmp class + +=head1 SNMP OPTIONS + +=over 8 + +=item B<--hostname> + +Hostname to query (required). + +=item B<--community> + +Read community (defaults to public). + +=item B<--snmp-version> + +Version: 1 for SNMP v1 (default), 2 for SNMP v2c, 3 for SNMP v3. + +=item B<--snmp-port> + +Port (default: 161). + +=item B<--snmp-timeout> + +Timeout in secondes (default: 1) before retries. + +=item B<--snmp-retries> + +Set the number of retries (default: 5) before failure. + +=item B<--maxrepetitions> + +Max repititions value (default: 50) (only for SNMP v2 and v3). + +=item B<--username> + +Security name (only for SNMP v3). + +=item B<--authpassphrase> + +Authentication protocol pass phrase. + +=item B<--authprotocol> + +Authentication protocol (MD5|SHA) + +=item B<--privpassphrase> + +Privacy protocol pass phrase + +=item B<--privprotocol> + +Privacy protocol (DES|AES) + +=item B<--contextname> + +Context name + +=item B<--contextengineid> + +Context engine ID + +=item B<--securityengineid> + +Security engine ID + +=item B<--snmp-errors-exit> + +Exit code for SNMP Errors (default: unknown) + +=back + +=head1 DESCRIPTION + +B. + +=cut diff --git a/centreon/lib/perl/centreon/plugins/statefile.pm b/centreon/lib/perl/centreon/plugins/statefile.pm new file mode 100644 index 00000000000..69602e095f8 --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/statefile.pm @@ -0,0 +1,93 @@ + +package centreon::plugins::statefile; +use Data::Dumper; +use vars qw($datas); + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + + $self->{output} = $options{output}; + $self->{statefile_dir} = '/var/lib/centreon/centplugins'; + $self->{datas} = {}; + + return $self; +} + +sub read { + my ($self, %options) = @_; + $self->{statefile_dir} = defined($options{statefile_dir}) ? $options{statefile_dir} : $self->{statefile_dir}; + $self->{statefile} = defined($options{statefile}) ? $options{statefile} : $self->{statefile}; + + if (! -e $self->{statefile_dir} . "/" . $self->{statefile}) { + if (! -w $self->{statefile_dir}) { + $self->{output}->add_option_msg(short_msg => "Cannot write statefile '" . $self->{statefile_dir} . "/" . $self->{statefile} . "'. Need write permissions on directory."); + $self->{output}->option_exit(); + } + return 0; + } elsif (! -w $self->{statefile_dir} . "/" . $self->{statefile}) { + $self->{output}->add_option_msg(short_msg => "Cannot write statefile '" . $self->{statefile_dir} . "/" . $self->{statefile} . "'. Need write permissions on file."); + $self->{output}->option_exit(); + } + + unless (my $return = do $self->{statefile_dir} . "/" . $self->{statefile}) { + if ($@) { + $self->{output}->add_option_msg(short_msg => "Couldn't parse '" . $self->{statefile_dir} . "/" . $self->{statefile} . "': $@"); + $self->{output}->option_exit(); + } + unless (defined($return)) { + $self->{output}->add_option_msg(short_msg => "Couldn't do '" . $self->{statefile_dir} . "/" . $self->{statefile} . "': $!"); + $self->{output}->option_exit(); + } + unless ($return) { + $self->{output}->add_option_msg(short_msg => "Couldn't run '" . $self->{statefile_dir} . "/" . $self->{statefile} . "': $!"); + $self->{output}->option_exit(); + } + } + $self->{datas} = $datas; + $datas = {}; + + return 1; +} + +sub get_string_content { + my ($self, %options) = @_; + + return Data::Dumper::Dumper($self->{datas}); +} + +sub get { + my ($self, %options) = @_; + + if (defined($self->{datas}->{$options{name}})) { + return $self->{datas}->{$options{name}}; + } + return undef; +} + +sub write { + my ($self, %options) = @_; + + open FILE, ">", $self->{statefile_dir} . "/" . $self->{statefile}; + print FILE Data::Dumper->Dump([$options{data}], ["datas"]); + close FILE; +} + +1; + +__END__ + +=head1 NAME + +Statefile class + +=head1 SYNOPSIS + +- + +=head1 DESCRIPTION + +B. + +=cut diff --git a/centreon/lib/perl/plugins/centreon_plugins.pl b/centreon/lib/perl/plugins/centreon_plugins.pl new file mode 100644 index 00000000000..084976a144f --- /dev/null +++ b/centreon/lib/perl/plugins/centreon_plugins.pl @@ -0,0 +1,50 @@ + +use strict; +use warnings; +use centreon::plugins::script; + +centreon::plugins::script->new()->run(); + +__END__ + +=head1 NAME + +centreon_plugins.pl - main program to call Merethis plugins. + +=head1 SYNOPSIS + +centreon_plugins.pl [options] + +=head1 OPTIONS + +=over 8 + +=item B<--plugin> + +Specify the path to the plugin. + +=item B<--mode> + +Specify the mode of the plugin. + +=item B<--list> + +List mode available for the plugin. + +=item B<--version> + +Print plugin version. + +=item B<--help> + +Print a brief help message and exits. + +=back + +=head1 DESCRIPTION + +B . + +=cut + + diff --git a/centreon/lib/perl/plugins/os_linux/snmp.pm b/centreon/lib/perl/plugins/os_linux/snmp.pm new file mode 100644 index 00000000000..1717d9e546f --- /dev/null +++ b/centreon/lib/perl/plugins/os_linux/snmp.pm @@ -0,0 +1,29 @@ +package os_linux::snmp; + +use strict; +use warnings; +use base qw(centreon::plugins::script_snmp); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '0.1'; + %{$self->{modes}} = ('traffic' => 'snmp_standard::traffic'); + %{$self->{modes}} = ('storage' => 'snmp_standard::storage'); + #$self->{default} = [{option_mode => 'traffic', option_name => 'warning', option_value => '-1'}]; + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check Linux Operating systems in SNMP. + +=cut diff --git a/centreon/lib/perl/plugins/snmp_standard/storage.pm b/centreon/lib/perl/plugins/snmp_standard/storage.pm new file mode 100644 index 00000000000..0612a8b98f1 --- /dev/null +++ b/centreon/lib/perl/plugins/snmp_standard/storage.pm @@ -0,0 +1,375 @@ +package snmp_standard::storage; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; +use centreon::plugins::perfdata; +use Digest::MD5 qw(md5_hex); + +my @operstatus = ("up", "down", "testing", "unknown", "dormant", "notPresent", "lowerLayerDown"); +my %oids_hrStorageTable = ( + 'hrstoragedescr' => '.1.3.6.1.2.1.25.2.3.1.3', + 'hrstoragetype' => '.1.3.6.1.2.1.25.2.3.1.2', +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + "units:s" => { name => 'units', default => '%' }, + "free" => { name => 'free' }, + "reload-cache-time:s" => { name => 'reload_cache_time' }, + "name" => { name => 'use_name' }, + "storage:s" => { name => 'storage' }, + "regexp" => { name => 'use_regexp' }, + "regexp-isensitive" => { name => 'use_regexpi' }, + "statefiledir-cache:s" => { name => 'statefiledir_cache' }, + "statefiledir-values:s" => { name => 'statefiledir_values' }, + "oid-filter:s" => { name => 'oid_filter', default => 'hrStorageDescr'}, + "oid-display:s" => { name => 'oid_display', default => 'hrStorageDescr'}, + "display-transform-src:s" => { name => 'display_transform_src' }, + "display-transform-dst:s" => { name => 'display_transform_dst' }, + "show-cache" => { name => 'show_cache' }, + }); + + $self->{storage_id_selected} = []; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } + $self->{option_results}->{oid_filter} = lc($self->{option_results}->{oid_filter}); + if ($self->{option_results}->{oid_filter} !~ /^(hrstoragedescr)$/) { + $self->{output}->add_option_msg(short_msg => "Unsupported --oid-filter option."); + $self->{output}->option_exit(); + } + $self->{option_results}->{oid_display} = lc($self->{option_results}->{oid_display}); + if ($self->{option_results}->{oid_display} !~ /^(hrstoragedescr)$/) { + $self->{output}->add_option_msg(short_msg => "Unsupported --oid-display option."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + $self->{hostname} = $self->{snmp}->get_hostname(); + + $self->manage_selection(); + + my $oid_hrStorageAllocationUnits = '.1.3.6.1.2.1.25.2.3.1.4'; + my $oid_hrStorageSize = '.1.3.6.1.2.1.25.2.3.1.5'; + my $oid_hrStorageUsed = '.1.3.6.1.2.1.25.2.3.1.6'; + my $oid_hrStorageType = '.1.3.6.1.2.1.25.2.3.1.2'; + my $oid_hrStorageFixedDisk = '.1.3.6.1.2.1.25.2.1.4'; + my $oid_hrStorageNetworkDisk = '.1.3.6.1.2.1.25.2.1.10'; + + $self->{snmp}->load(oids => [$oid_hrStorageAllocationUnits, $oid_hrStorageSize, $oid_hrStorageUsed], instances => $self->{storage_id_selected}); + my $result = $self->{snmp}->get_leef(); + + if (!defined($self->{option_results}->{storage}) || defined($self->{option_results}->{use_regexp})) { + $self->{output}->output_add(severity => 'OK', + short_msg => 'All storages are ok.'); + } + + my $num_disk_check = 0; + foreach (sort @{$self->{storage_id_selected}}) { + # Skipped disks + my $storage_type = $self->{statefile_cache}->get(name => "type_" . $_); + next if (!defined($storage_type) || ($storage_type ne $oid_hrStorageFixedDisk && $storage_type ne $oid_hrStorageNetworkDisk)); + + my $name_storage = $self->get_display_value(id => $_); + $num_disk_check++; + + # in bytes hrStorageAllocationUnits + my $total_size = $result->{$oid_hrStorageSize . "." . $_} * $result->{$oid_hrStorageAllocationUnits . "." . $_}; + next if ($total_size == 0); + my $total_used = $result->{$oid_hrStorageUsed . "." . $_} * $result->{$oid_hrStorageAllocationUnits . "." . $_}; + my $total_free = $total_size - $total_used; + my $prct_used = $total_used * 100 / $total_size; + my $prct_free = 100 - $prct_used; + + my ($exit, $threshold_value); + + $threshold_value = $total_used; + $threshold_value = $total_free if (defined($self->{option_results}->{free})); + if ($self->{option_results}->{units} eq '%') { + $threshold_value = $prct_used; + $threshold_value = $prct_free if (defined($self->{option_results}->{free})); + } + $exit = $self->{perfdata}->threshold_check(value => $threshold_value, threshold => [ { label => 'warning', 'exit_litteral' => 'warning' }, { label => 'critical', exit_litteral => 'critical' } ]); + + my ($total_size_value, $total_size_unit) = $self->{perfdata}->change_bytes(value => $total_size); + my ($total_used_value, $total_used_unit) = $self->{perfdata}->change_bytes(value => $total_used); + my ($total_free_value, $total_free_unit) = $self->{perfdata}->change_bytes(value => ($total_size - $total_used)); + + $self->{output}->output_add(long_msg => sprintf("Storage '%s' Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", $name_storage, + $total_size_value . " " . $total_size_unit, + $total_used_value . " " . $total_used_unit, $prct_used, + $total_free_value . " " . $total_free_unit, $prct_free)); + if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1) || (defined($self->{option_results}->{storage}) && !defined($self->{option_results}->{use_regexp}))) { + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Storage '%s' Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", $name_storage, + $total_size_value . " " . $total_size_unit, + $total_used_value . " " . $total_used_unit, $prct_used, + $total_free_value . " " . $total_free_unit, $prct_free)); + } + + my $label = 'used'; + my $value_perf = $total_used; + if (defined($self->{option_results}->{free})) { + $label = 'free'; + $value_perf = $total_free; + } + my $extra_label = ''; + $extra_label = '_' . $name_storage if (!defined($self->{option_results}->{storage}) || defined($self->{option_results}->{use_regexp})); + my %total_options = (); + $total_options{total} = $total_size if ($self->{option_results}->{units} eq '%'); + $self->{output}->perfdata_add(label => $label . $extra_label, unit => 'o', + value => $value_perf, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', %total_options), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', %total_options), + min => 0, max => $total_size); + } + + if ($num_disk_check == 0) { + $self->{output}->add_option_msg(short_msg => "Not a disk with a good 'type'."); + $self->{output}->option_exit(); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub reload_cache { + my ($self) = @_; + my $datas = {}; + + $datas->{oid_filter} = $self->{option_results}->{oid_filter}; + $datas->{oid_display} = $self->{option_results}->{oid_display}; + my ($exit, $result) = $self->{snmp}->get_table(oid => $oids_hrStorageTable{$self->{option_results}->{oid_filter}}); + my $last_num = 0; + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($key !~ /\.([0-9]+)$/); + $datas->{$self->{option_results}->{oid_filter} . "_" . $1} = $result->{$key}; + $last_num = $1; + } + + if (scalar(keys %$datas) <= 0) { + $self->{output}->add_option_msg(short_msg => "Can't construct cache..."); + $self->{output}->option_exit(); + } + + if ($self->{option_results}->{oid_filter} ne $self->{option_results}->{oid_display}) { + ($exit, $result) = $self->{snmp}->get_table(oid => $oids_hrStorageTable{$self->{option_results}->{oid_display}}); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($key !~ /\.([0-9]+)$/); + $datas->{$self->{option_results}->{oid_display} . "_" . $1} = $result->{$key}; + } + } + + ($exit, $result) = $self->{snmp}->get_table(oid => $oids_hrStorageTable{hrstoragetype}); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($key !~ /\.([0-9]+)$/); + $datas->{"type_" . $1} = $result->{$key}; + } + + $datas->{total_storage} = $last_num; + $self->{statefile_cache}->write(data => $datas); +} + +sub manage_selection { + my ($self, %options) = @_; + + # init cache file + $self->{statefile_cache} = centreon::plugins::statefile->new(output => $self->{output}); + my $has_cache_file = $self->{statefile_cache}->read(statefile_dir => $self->{option_results}->{statefiledir_cache}, + statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + if (defined($self->{option_results}->{show_cache})) { + $self->{output}->add_option_msg(long_msg => $self->{statefile_cache}->get_string_content()); + $self->{output}->option_exit(); + } + + my $timestamp_cache = $self->{statefile_cache}->get(name => 'last_timestamp'); + my $oid_display = $self->{statefile_cache}->get(name => 'oid_display'); + my $oid_filter = $self->{statefile_cache}->get(name => 'oid_filter'); + if ($has_cache_file == 0 || + ($self->{option_results}->{oid_display} !~ /^($oid_display|$oid_filter)$/i || $self->{option_results}->{oid_filter} !~ /^($oid_display|$oid_filter)$/i) || + (defined($timestamp_cache) && (time() - $timestamp_cache) > (($self->{option_results}->{reload_cache_time}) * 60))) { + $self->reload_cache(); + $self->{statefile_cache}->read(); + } + + my $total_storage = $self->{statefile_cache}->get(name => 'total_storage'); + if (!defined($self->{option_results}->{use_name}) && defined($self->{option_results}->{storage})) { + # get by ID + push @{$self->{storage_id_selected}}, $self->{option_results}->{storage}; + my $name = $self->{statefile_cache}->get(name => $self->{option_results}->{oid_display} . "_" . $self->{option_results}->{storage}); + if (!defined($name)) { + $self->{output}->add_option_msg(short_msg => "No storage found for id '" . $self->{option_results}->{storage} . "'."); + $self->{output}->option_exit(); + } + } else { + for (my $i = 0; $i <= $total_storage; $i++) { + my $filter_name = $self->{statefile_cache}->get(name => $self->{option_results}->{oid_filter} . "_" . $i); + next if (!defined($filter_name)); + if (!defined($self->{option_results}->{storage})) { + push @{$self->{storage_id_selected}}, $i; + next; + } + if (defined($self->{option_results}->{use_regexp}) && defined($self->{option_results}->{use_regexpi}) && $filter_name =~ /$self->{option_results}->{storage}/i) { + push @{$self->{storage_id_selected}}, $i; + } + if (defined($self->{option_results}->{use_regexp}) && !defined($self->{option_results}->{use_regexpi}) && $filter_name =~ /$self->{option_results}->{storage}/) { + push @{$self->{storage_id_selected}}, $i; + } + if (!defined($self->{option_results}->{use_regexp}) && !defined($self->{option_results}->{use_regexpi}) && $filter_name eq $self->{option_results}->{storage}) { + push @{$self->{storage_id_selected}}, $i; + } + } + + if (scalar(@{$self->{storage_id_selected}}) < 0) { + $self->{output}->add_option_msg(short_msg => "No storage found for name '" . $self->{option_results}->{storage} . "' (maybe you should reload cache file)."); + $self->{output}->option_exit(); + } + } +} + +sub get_display_value { + my ($self, %options) = @_; + my $value = $self->{statefile_cache}->get(name => $self->{option_results}->{oid_display} . "_" . $options{id}); + + if (defined($self->{option_results}->{display_transform_src})) { + $self->{option_results}->{display_transform_dst} = '' if (!defined($self->{option_results}->{display_transform_dst})); + eval "\$value =~ s{$self->{option_results}->{display_transform_src}}{$self->{option_results}->{display_transform_dst}}"; + } + return $value; +} + +sub disco_format { + my ($self, %options) = @_; + + $self->{output}->add_disco_format(elements => ['name', 'total', 'storageid']); +} + +sub disco_show { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + $self->{hostname} = $self->{snmp}->get_hostname(); + + my $oid_hrStorageAllocationUnits = '.1.3.6.1.2.1.25.2.3.1.4'; + my $oid_hrStorageSize = '.1.3.6.1.2.1.25.2.3.1.5'; + my $oid_hrStorageType = '.1.3.6.1.2.1.25.2.3.1.2'; + my $oid_hrStorageFixedDisk = '.1.3.6.1.2.1.25.2.1.4'; + my $oid_hrStorageNetworkDisk = '.1.3.6.1.2.1.25.2.1.10'; + + $self->manage_selection(); + $self->{snmp}->load(oids => [$oid_hrStorageAllocationUnits, $oid_hrStorageSize], instances => $self->{storage_id_selected}); + my $result = $self->{snmp}->get_leef(); + foreach (sort @{$self->{storage_id_selected}}) { + my $display_value = $self->get_display_value(id => $_); + my $storage_type = $self->{statefile_cache}->get(name => "type_" . $_); + next if (!defined($storage_type) || ($storage_type ne $oid_hrStorageFixedDisk && $storage_type ne $oid_hrStorageNetworkDisk)); + + $self->{output}->add_disco_entry(name => $display_value, + total => $result->{$oid_hrStorageSize . "." . $_} * $result->{$oid_hrStorageAllocationUnits . "." . $_}, + storageid => $_); + } +} + +1; + +__END__ + +=head1 MODE + +=over 8 + +=item B<--warning> + +Threshold warning. + +=item B<--critical> + +Threshold critical. + +=item B<--units> + +Units of thresholds (Default: '%') ('%', 'B'). + +=item B<--free> + +Thresholds are on free space left. + +=item B<--storage> + +Set the storage (number expected) ex: 1, 2,... (empty means 'check all storage'). + +=item B<--name> + +Allows to use storage name with option --storage instead of storage oid index. + +=item B<--regexp> + +Allows to use regexp to filter storage (with option --name). + +=item B<--regexp-isensitive> + +Allows to use regexp non case-sensitive (with --regexp). + +=item B<--statefiledir-cache> + +Directory path of statefile 'cache'. + +=item B<--statefiledir-values> + +Directory path of statefile 'values'. + +=item B<--reload-cache-time> + +Time in seconds before reloading cache file (default: 180). + +=item B<--oid-filter> + +Choose OID used to filter storage (default: hrstoragedescr) (values: hrstoragedescr). + +=item B<--oid-display> + +Choose OID used to display storage (default: hrstoragedescr) (values: hrstoragedescr). + +=item B<--display-transform-src> + +Regexp src to transform display value. (security risk!!!) + +=item B<--display-transform-dst> + +Regexp dst to transform display value. (security risk!!!) + +=item B<--show-cache> + +Display cache storage datas. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/snmp_standard/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/traffic.pm new file mode 100644 index 00000000000..8c361ae284d --- /dev/null +++ b/centreon/lib/perl/plugins/snmp_standard/traffic.pm @@ -0,0 +1,434 @@ +package snmp_standard::traffic; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; +use centreon::plugins::perfdata; +use Digest::MD5 qw(md5_hex); + +my @operstatus = ("up", "down", "testing", "unknown", "dormant", "notPresent", "lowerLayerDown"); +my %oids_iftable = ( + 'ifdesc' => '.1.3.6.1.2.1.2.2.1.2', + 'ifalias' => '.1.3.6.1.2.1.31.1.1.1.18', + 'ifname' => '.1.3.6.1.2.1.31.1.1.1.1' +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + "reload-cache-time:s" => { name => 'reload_cache_time' }, + "name" => { name => 'use_name' }, + "interface:s" => { name => 'interface' }, + "speed:s" => { name => 'speed' }, + "skip" => { name => 'skip' }, + "regexp" => { name => 'use_regexp' }, + "regexp-isensitive" => { name => 'use_regexpi' }, + "statefiledir-cache:s" => { name => 'statefiledir_cache' }, + "statefiledir-values:s" => { name => 'statefiledir_values' }, + "oid-filter:s" => { name => 'oid_filter', default => 'ifDesc'}, + "oid-display:s" => { name => 'oid_display', default => 'ifDesc'}, + "display-transform-src:s" => { name => 'display_transform_src' }, + "display-transform-dst:s" => { name => 'display_transform_dst' }, + "show-cache" => { name => 'show_cache' }, + }); + + $self->{interface_id_selected} = []; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } + $self->{option_results}->{oid_filter} = lc($self->{option_results}->{oid_filter}); + if ($self->{option_results}->{oid_filter} !~ /^(ifdesc|ifalias|ifname)$/) { + $self->{output}->add_option_msg(short_msg => "Unsupported --oid-filter option."); + $self->{output}->option_exit(); + } + $self->{option_results}->{oid_display} = lc($self->{option_results}->{oid_display}); + if ($self->{option_results}->{oid_display} !~ /^(ifdesc|ifalias|ifname)$/) { + $self->{output}->add_option_msg(short_msg => "Unsupported --oid-display option."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + $self->{hostname} = $self->{snmp}->get_hostname(); + + $self->manage_selection(); + + my $oid_adminstatus = '.1.3.6.1.2.1.2.2.1.7'; + my $oid_operstatus = '.1.3.6.1.2.1.2.2.1.8'; + my $oid_speed32 = '.1.3.6.1.2.1.2.2.1.5'; # in b/s + my $oid_in32 = '.1.3.6.1.2.1.2.2.1.10'; # in B + my $oid_out32 = '.1.3.6.1.2.1.2.2.1.16'; # in B + my $oid_speed64 = '.1.3.6.1.2.1.31.1.1.1.15'; # in b/s + my $oid_in64 = '.1.3.6.1.2.1.31.1.1.1.6'; # in B + my $oid_out64 = '.1.3.6.1.2.1.31.1.1.1.10'; # in B + + my $new_datas = {}; + $self->{statefile_value} = centreon::plugins::statefile->new(output => $self->{output}); + $self->{statefile_value}->read(statefile_dir => $self->{option_results}->{statefiledir_values}, + statefile => $self->{hostname} . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{interface}) ? md5_hex($self->{option_results}->{interface}) : md5_hex('all'))); + + foreach (@{$self->{interface_id_selected}}) { + $self->{snmp}->load(oids => [$oid_adminstatus . "." . $_, $oid_operstatus . "." . $_, $oid_in32 . "." . $_, $oid_out32 . "." . $_]); + if (!defined($self->{option_results}->{speed}) || $self->{option_results}->{speed} eq '') { + $self->{snmp}->load(oids => [$oid_speed32 . "." . $_]); + } + if (!$self->{snmp}->is_snmpv1()) { + $self->{snmp}->load(oids => [$oid_in64 . "." . $_, $oid_out64 . "." . $_]); + if (!defined($self->{option_results}->{speed}) || $self->{option_results}->{speed} eq '') { + $self->{snmp}->load(oids => [$oid_speed64 . "." . $_]); + } + } + } + + my $result = $self->{snmp}->get_leef(); + $new_datas->{last_timestamp} = time(); + my $old_timestamp; + if (!defined($self->{option_results}->{interface}) || defined($self->{option_results}->{use_regexp})) { + $self->{output}->output_add(severity => 'OK', + short_msg => 'All traffic are ok.'); + } + + foreach (sort @{$self->{interface_id_selected}}) { + my $display_value = $self->get_display_value(id => $_); + + my $interface_speed; + if (defined($self->{option_results}->{speed}) && $self->{option_results}->{speed} ne '') { + $interface_speed = $self->{option_results}->{speed} * 1024 * 1024; + } else { + if ((!defined($result->{$oid_speed32 . "." . $_}) || $result->{$oid_speed32 . "." . $_} !~ /^[0-9]+$/) && + (!defined($result->{$oid_speed64 . "." . $_}) || $result->{$oid_speed64 . "." . $_} !~ /^[0-9]+$/)) { + $self->{output}->output_add(severity => 'UNKNOWN', + short_msg => "Interface '" . $display_value . "' Speed is null or incorrect. You should force the value with --speed option"); + next; + } + $interface_speed = (defined($result->{$oid_speed64 . "." . $_}) && $result->{$oid_speed64 . "." . $_} ne '' ? ($result->{$oid_speed64 . "." . $_}) : ($result->{$oid_speed32 . "." . $_})); + if ($interface_speed == 0) { + next; + } + } + if ($operstatus[$result->{$oid_operstatus . "." . $_} - 1] ne "up") { + if (!defined($self->{option_results}->{skip}) && (!defined($result->{$oid_adminstatus . "." . $_}) || $operstatus[$result->{$oid_adminstatus . "." . $_} - 1] eq 'up') ) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Interface '" . $display_value . "' is not ready: " . $operstatus[$result->{$oid_operstatus . "." . $_} - 1]); + } else { + $self->{output}->output_add(long_msg => "Skip interface '" . $display_value . "'."); + } + next; + } + my $old_mode = $self->{statefile_value}->get(name => 'mode'); + $new_datas->{mode} = '32'; + + $new_datas->{'in_' . $_} = $result->{$oid_in32 . "." . $_} * 8; + if (defined($result->{$oid_in64 . "." . $_}) && $result->{$oid_in64 . "." . $_} ne '') { + $new_datas->{'in_' . $_} = $result->{$oid_in64 . "." . $_} * 8; + $new_datas->{mode} = '64'; + } + $new_datas->{'out_' . $_} = $result->{$oid_out32 . "." . $_} * 8; + if (defined($result->{$oid_out64 . "." . $_}) && $result->{$oid_out64 . "." . $_} ne '') { + $new_datas->{'out_' . $_} = $result->{$oid_out64 . "." . $_} * 8; + $new_datas->{mode} = '64'; + } + # We change mode. need to recreate a buffer + if (!defined($old_mode) || $new_datas->{mode} ne $old_mode) { + next; + } + + $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); + my $old_in = $self->{statefile_value}->get(name => 'in_' . $_); + my $old_out = $self->{statefile_value}->get(name => 'out_' . $_); + if (!defined($old_timestamp) || !defined($old_in) || !defined($old_out)) { + next; + } + if ($new_datas->{'in_' . $_} < $old_in) { + # We set 0. Has reboot. + $old_in = 0; + } + if ($new_datas->{'out_' . $_} < $old_out) { + # We set 0. Has reboot. + $old_out = 0; + } + + my $time_delta = $new_datas->{last_timestamp} - $old_timestamp; + if ($time_delta <= 0) { + # At least one second. two fast calls ;) + $time_delta = 1; + } + my $in_absolute_per_sec = ($new_datas->{'in_' . $_} - $old_in) / $time_delta; + my $out_absolute_per_sec = ($new_datas->{'out_' . $_} - $old_out) / $time_delta; + my $in_prct = $in_absolute_per_sec * 100 / $interface_speed; + my $out_prct = $out_absolute_per_sec * 100 / $interface_speed; + + ########### + # Manage Output + ########### + my $exit1 = $self->{perfdata}->threshold_check(value => $in_prct, threshold => [ { label => 'warning', 'exit_litteral' => 'warning' }, { label => 'critical', exit_litteral => 'critical' } ]); + my $exit2 = $self->{perfdata}->threshold_check(value => $out_prct, threshold => [ { label => 'warning', 'exit_litteral' => 'warning' }, { label => 'critical', exit_litteral => 'critical' } ]); + + my ($in_value, $in_unit) = $self->{perfdata}->change_bytes(value => $in_absolute_per_sec, network => 1); + my ($out_value, $out_unit) = $self->{perfdata}->change_bytes(value => $out_absolute_per_sec, network => 1); + my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2 ]); + $self->{output}->output_add(long_msg => sprintf("Interface '%s' Traffic In : %s/s (%.2f %%), Out : %s/s (%.2f %%) ", $display_value, + $in_value . $in_unit, $in_prct, + $out_value . $out_unit, $out_prct)); + if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1) || (defined($self->{option_results}->{interface}) && !defined($self->{option_results}->{use_regexp}))) { + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Interface '%s' Traffic In : %s/s (%.2f %%), Out : %s/s (%.2f %%) ", $display_value, + $in_value . $in_unit, $in_prct, + $out_value . $out_unit, $out_prct)); + } + + my $extra_label = ''; + $extra_label = '_' . $display_value if (!defined($self->{option_results}->{interface}) || defined($self->{option_results}->{use_regexp})); + $self->{output}->perfdata_add(label => 'traffic_in' . $extra_label, unit => 'b/s', + value => sprintf("%.2f", $in_absolute_per_sec), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $interface_speed), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $interface_speed), + min => 0, max => $interface_speed); + $self->{output}->perfdata_add(label => 'traffic_out' . $extra_label, unit => 'b/s', + value => sprintf("%.2f", $out_absolute_per_sec), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $interface_speed), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $interface_speed), + min => 0, max => $interface_speed); + } + + $self->{statefile_value}->write(data => $new_datas); + if (!defined($old_timestamp)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub get_display_value { + my ($self, %options) = @_; + my $value = $self->{statefile_cache}->get(name => $self->{option_results}->{oid_display} . "_" . $options{id}); + + if (defined($self->{option_results}->{display_transform_src})) { + $self->{option_results}->{display_transform_dst} = '' if (!defined($self->{option_results}->{display_transform_dst})); + eval "\$value =~ s{$self->{option_results}->{display_transform_src}}{$self->{option_results}->{display_transform_dst}}"; + } + return $value; +} + +sub reload_cache { + my ($self) = @_; + my $datas = {}; + + $datas->{oid_filter} = $self->{option_results}->{oid_filter}; + $datas->{oid_display} = $self->{option_results}->{oid_display}; + my ($exit, $result) = $self->{snmp}->get_table(oid => $oids_iftable{$self->{option_results}->{oid_filter}}); + my $last_num = 0; + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($key !~ /\.([0-9]+)$/); + $datas->{$self->{option_results}->{oid_filter} . "_" . $1} = $result->{$key}; + $last_num = $1; + } + + if (scalar(keys %$datas) <= 0) { + $self->{output}->add_option_msg(short_msg => "Can't construct cache..."); + $self->{output}->option_exit(); + } + + if ($self->{option_results}->{oid_filter} ne $self->{option_results}->{oid_display}) { + ($exit, $result) = $self->{snmp}->get_table(oid => $oids_iftable{$self->{option_results}->{oid_display}}); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($key !~ /\.([0-9]+)$/); + $datas->{$self->{option_results}->{oid_display} . "_" . $1} = $result->{$key}; + } + } + + $datas->{total_interface} = $last_num; + $self->{statefile_cache}->write(data => $datas); +} + +sub manage_selection { + my ($self, %options) = @_; + + # init cache file + $self->{statefile_cache} = centreon::plugins::statefile->new(output => $self->{output}); + my $has_cache_file = $self->{statefile_cache}->read(statefile_dir => $self->{option_results}->{statefiledir_cache}, + statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + if (defined($self->{option_results}->{show_cache})) { + $self->{output}->add_option_msg(long_msg => $self->{statefile_cache}->get_string_content()); + $self->{output}->option_exit(); + } + + my $timestamp_cache = $self->{statefile_cache}->get(name => 'last_timestamp'); + my $oid_display = $self->{statefile_cache}->get(name => 'oid_display'); + my $oid_filter = $self->{statefile_cache}->get(name => 'oid_filter'); + if ($has_cache_file == 0 || + ($self->{option_results}->{oid_display} !~ /^($oid_display|$oid_filter)$/i || $self->{option_results}->{oid_filter} !~ /^($oid_display|$oid_filter)$/i) || + (defined($timestamp_cache) && (time() - $timestamp_cache) > (($self->{option_results}->{reload_cache_time}) * 60))) { + $self->reload_cache(); + $self->{statefile_cache}->read(); + } + + my $total_interface = $self->{statefile_cache}->get(name => 'total_interface'); + if (!defined($self->{option_results}->{use_name}) && defined($self->{option_results}->{interface})) { + # get by ID + push @{$self->{interface_id_selected}}, $self->{option_results}->{interface}; + my $name = $self->{statefile_cache}->get(name => $self->{option_results}->{oid_display} . "_" . $self->{option_results}->{interface}); + if (!defined($name)) { + $self->{output}->add_option_msg(short_msg => "No interface found for id '" . $self->{option_results}->{interface} . "'."); + $self->{output}->option_exit(); + } + } else { + for (my $i = 0; $i <= $total_interface; $i++) { + my $filter_name = $self->{statefile_cache}->get(name => $self->{option_results}->{oid_filter} . "_" . $i); + next if (!defined($filter_name)); + if (!defined($self->{option_results}->{interface})) { + push @{$self->{interface_id_selected}}, $i; + next; + } + if (defined($self->{option_results}->{use_regexp}) && defined($self->{option_results}->{use_regexpi}) && $filter_name =~ /$self->{option_results}->{interface}/i) { + push @{$self->{interface_id_selected}}, $i; + } + if (defined($self->{option_results}->{use_regexp}) && !defined($self->{option_results}->{use_regexpi}) && $filter_name =~ /$self->{option_results}->{interface}/) { + push @{$self->{interface_id_selected}}, $i; + } + if (!defined($self->{option_results}->{use_regexp}) && !defined($self->{option_results}->{use_regexpi}) && $filter_name eq $self->{option_results}->{interface}) { + push @{$self->{interface_id_selected}}, $i; + } + } + + if (scalar(@{$self->{interface_id_selected}}) < 0) { + $self->{output}->add_option_msg(short_msg => "No interface found for name '" . $self->{option_results}->{interface} . "' (maybe you should reload cache file)."); + $self->{output}->option_exit(); + } + } +} + +sub disco_format { + my ($self, %options) = @_; + + $self->{output}->add_disco_format(elements => ['name', 'total', 'status', 'interfaceid']); +} + +sub disco_show { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + $self->{hostname} = $self->{snmp}->get_hostname(); + + my $oid_operstatus = '.1.3.6.1.2.1.2.2.1.8'; + my $oid_speed32 = '.1.3.6.1.2.1.2.2.1.5'; # in b/s + + $self->manage_selection(); + $self->{snmp}->load(oids => [$oid_operstatus, $oid_speed32], instances => $self->{interface_id_selected}); + my $result = $self->{snmp}->get_leef(); + foreach (sort @{$self->{interface_id_selected}}) { + my $display_value = $self->get_display_value(id => $_); + my $interface_speed = int($result->{$oid_speed32 . "." . $_} / 1000 / 1000); + if (defined($self->{option_results}->{speed}) && $self->{option_results}->{speed} ne '') { + $interface_speed = $self->{option_results}->{speed}; + } + + $self->{output}->add_disco_entry(name => $display_value, + total => $interface_speed, + status => $result->{$oid_operstatus . "." . $_}, + interfaceid => $_); + } +} + +1; + +__END__ + +=head1 MODE + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=item B<--interface> + +Set the interface (number expected) ex: 1, 2,... (empty means 'check all interface'). + +=item B<--name> + +Allows to use interface name with option --interface instead of interface oid index. + +=item B<--regexp> + +Allows to use regexp to filter interfaces (with option --name). + +=item B<--regexp-isensitive> + +Allows to use regexp non case-sensitive (with --regexp). + +=item B<--speed> + +Set interface speed (in Mb). + +=item B<--skip> + +Skip errors on interface status. + +=item B<--statefiledir-cache> + +Directory path of statefile 'cache'. + +=item B<--statefiledir-values> + +Directory path of statefile 'values'. + +=item B<--reload-cache-time> + +Time in seconds before reloading cache file (default: 180). + +=item B<--oid-filter> + +Choose OID used to filter interface (default: ifDesc) (values: ifDesc, ifAlias, ifName). + +=item B<--oid-display> + +Choose OID used to display interface (default: ifDesc) (values: ifDesc, ifAlias, ifName). + +=item B<--display-transform-src> + +Regexp src to transform display value. (security risk!!!) + +=item B<--display-transform-dst> + +Regexp dst to transform display value. (security risk!!!) + +=item B<--show-cache> + +Display cache interface datas. + +=back + +=cut From e9b92db30f848690d906ce98315b8545109ce489 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 23 Oct 2013 18:42:18 +0200 Subject: [PATCH 106/458] manage for AIX --- centreon/lib/perl/plugins/snmp_standard/storage.pm | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/plugins/snmp_standard/storage.pm b/centreon/lib/perl/plugins/snmp_standard/storage.pm index 0612a8b98f1..d0974375fd6 100644 --- a/centreon/lib/perl/plugins/snmp_standard/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/storage.pm @@ -11,6 +11,7 @@ use Digest::MD5 qw(md5_hex); my @operstatus = ("up", "down", "testing", "unknown", "dormant", "notPresent", "lowerLayerDown"); my %oids_hrStorageTable = ( 'hrstoragedescr' => '.1.3.6.1.2.1.25.2.3.1.3', + 'hrfsmountpoint' => '.1.3.6.1.2.1.25.3.8.1.2', 'hrstoragetype' => '.1.3.6.1.2.1.25.2.3.1.2', ); @@ -58,12 +59,12 @@ sub check_options { $self->{output}->option_exit(); } $self->{option_results}->{oid_filter} = lc($self->{option_results}->{oid_filter}); - if ($self->{option_results}->{oid_filter} !~ /^(hrstoragedescr)$/) { + if ($self->{option_results}->{oid_filter} !~ /^(hrstoragedescr|hrfsmountpoint)$/) { $self->{output}->add_option_msg(short_msg => "Unsupported --oid-filter option."); $self->{output}->option_exit(); } $self->{option_results}->{oid_display} = lc($self->{option_results}->{oid_display}); - if ($self->{option_results}->{oid_display} !~ /^(hrstoragedescr)$/) { + if ($self->{option_results}->{oid_display} !~ /^(hrstoragedescr|hrfsmountpoint)$/) { $self->{output}->add_option_msg(short_msg => "Unsupported --oid-display option."); $self->{output}->option_exit(); } @@ -352,11 +353,11 @@ Time in seconds before reloading cache file (default: 180). =item B<--oid-filter> -Choose OID used to filter storage (default: hrstoragedescr) (values: hrstoragedescr). +Choose OID used to filter storage (default: hrStorageDescr) (values: hrStorageDescr, hrFSRemoteMountPoint). =item B<--oid-display> -Choose OID used to display storage (default: hrstoragedescr) (values: hrstoragedescr). +Choose OID used to display storage (default: hrStorageDescr) (values: hrStorageDescr, hrFSRemoteMountPoint). =item B<--display-transform-src> From 86063d38bb9eb60cab630fc7d898ea9075bd22f4 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 24 Oct 2013 11:32:34 +0200 Subject: [PATCH 107/458] + examples command + refactor path --- centreon/lib/perl/centreon/plugins/misc.pm | 73 +++++++++++++++ centreon/lib/perl/centreon/plugins/mode.pm | 1 + .../perl/centreon/plugins/script_simple.pm | 92 +++++++++++++++++++ .../perl/plugins/plugin/example/command.pm | 29 ++++++ .../plugins/plugin/example/mode/getvalue.pm | 91 ++++++++++++++++++ .../plugins/plugin/example/mode/launchcmd.pm | 87 ++++++++++++++++++ .../lib/perl/plugins/plugin/example/snmp.pm | 29 ++++++ .../{os_linux => plugin/linux}/snmp.pm | 8 +- .../snmp_standard/{ => mode}/storage.pm | 5 +- .../snmp_standard/{ => mode}/traffic.pm | 53 +++++++---- 10 files changed, 444 insertions(+), 24 deletions(-) create mode 100644 centreon/lib/perl/centreon/plugins/misc.pm create mode 100644 centreon/lib/perl/centreon/plugins/script_simple.pm create mode 100644 centreon/lib/perl/plugins/plugin/example/command.pm create mode 100644 centreon/lib/perl/plugins/plugin/example/mode/getvalue.pm create mode 100644 centreon/lib/perl/plugins/plugin/example/mode/launchcmd.pm create mode 100644 centreon/lib/perl/plugins/plugin/example/snmp.pm rename centreon/lib/perl/plugins/{os_linux => plugin/linux}/snmp.pm (68%) rename centreon/lib/perl/plugins/snmp_standard/{ => mode}/storage.pm (98%) rename centreon/lib/perl/plugins/snmp_standard/{ => mode}/traffic.pm (89%) diff --git a/centreon/lib/perl/centreon/plugins/misc.pm b/centreon/lib/perl/centreon/plugins/misc.pm new file mode 100644 index 00000000000..e08121c404c --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/misc.pm @@ -0,0 +1,73 @@ +package centreon::plugins::misc; + +use strict; +use warnings; + +sub backtick { + my %arg = ( + command => undef, + timeout => 30, + wait_exit => 0, + @_, + ); + my @output; + my $pid; + my $return_code; + + my $sig_do; + if ($arg{wait_exit} == 0) { + $sig_do = 'IGNORE'; + $return_code = undef; + } else { + $sig_do = 'DEFAULT'; + } + local $SIG{CHLD} = $sig_do; + if (!defined($pid = open( KID, "-|" ))) { + return (-1001, "Cant fork: $!", -1); + } + + if ($pid) { + + eval { + local $SIG{ALRM} = sub { die "Timeout by signal ALARM\n"; }; + alarm( $arg{timeout} ); + while () { + chomp; + push @output, $_; + } + + alarm(0); + }; + + if ($@) { + if ($pid != -1) { + kill -9, $pid; + } + + alarm(0); + return (-1000, "Command too long to execute (timeout)...", -1); + } else { + if ($arg{wait_exit} == 1) { + # We're waiting the exit code + waitpid($pid, 0); + $return_code = ($? >> 8); + } + close KID; + } + } else { + # child + # set the child process to be a group leader, so that + # kill -9 will kill it and all its descendents + setpgrp( 0, 0 ); + + exec($arg{command}); + exit(0); + } + + return (0, join("\n", @output), $return_code); +} + +1; + +__END__ + diff --git a/centreon/lib/perl/centreon/plugins/mode.pm b/centreon/lib/perl/centreon/plugins/mode.pm index 6c304abe4dc..ecb7dd371b8 100644 --- a/centreon/lib/perl/centreon/plugins/mode.pm +++ b/centreon/lib/perl/centreon/plugins/mode.pm @@ -2,6 +2,7 @@ package centreon::plugins::mode; use strict; use warnings; +use centreon::plugins::perfdata; sub new { my ($class, %options) = @_; diff --git a/centreon/lib/perl/centreon/plugins/script_simple.pm b/centreon/lib/perl/centreon/plugins/script_simple.pm new file mode 100644 index 00000000000..6b6072405cd --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/script_simple.pm @@ -0,0 +1,92 @@ +package centreon::plugins::script_simple; + +use strict; +use warnings; +use centreon::plugins::output; + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + # $options{options} = options object + # $options{output} = output object + + $self->{version} = '1.0'; + %{$self->{modes}} = (); + $self->{default} = undef; + + $self->{options} = $options{options}; + $self->{output} = $options{output}; + $self->{options}->add_help(package => $options{package}, sections => 'PLUGIN DESCRIPTION'); + + return $self; +} + +sub init { + my ($self, %options) = @_; + # $options{mode} = string mode + # $options{help} = string help + + # Load output + $self->{options}->add_help(package => 'centreon::plugins::output', sections => 'OUTPUT OPTIONS'); + + # Load mode + (my $file = $self->{modes}{$options{mode}} . ".pm") =~ s{::}{/}g; + require $file; + $self->{mode} = $self->{modes}{$options{mode}}->new(options => $self->{options}, output => $self->{output}, mode => $options{mode}); + + if (defined($options{help})) { + $self->{options}->add_help(package => $self->{modes}{$options{mode}}, sections => 'MODE'); + $self->{options}->display_help(); + $self->{output}->option_exit(); + } + if (defined($options{version})) { + $self->{mode}->version(); + $self->{output}->option_exit(nolabel => 1); + } + + $self->{options}->parse_options(); + $self->{option_results} = $self->{options}->get_options(); + + $self->{mode}->check_options(option_results => $self->{option_results}, default => $self->{default}); +} + +sub run { + my $self = shift; + + $self->{mode}->run(); +} + +sub is_mode { + my ($self, %options) = @_; + + # $options->{mode} = mode + if (!defined($self->{modes}{$options{mode}})) { + $self->{output}->add_option_msg(short_msg => "mode '" . $options{mode} . "' doesn't exist (use --list option to show available modes)."); + $self->{output}->option_exit(); + } +} + +sub version { + my $self = shift; + $self->{options}->display_help(); + + $self->{output}->add_option_msg(long_msg => "Plugin Version: " . $self->{version}); + $self->{output}->option_exit(nolabel => 1); +} + +sub list { + my $self = shift; + $self->{options}->display_help(); + + $self->{output}->add_option_msg(long_msg => "Modes Available:"); + foreach (keys %{$self->{modes}}) { + $self->{output}->add_option_msg(long_msg => " " . $_); + } + $self->{output}->option_exit(nolabel => 1); +} + +1; + +__END__ + diff --git a/centreon/lib/perl/plugins/plugin/example/command.pm b/centreon/lib/perl/plugins/plugin/example/command.pm new file mode 100644 index 00000000000..21bb597c5f5 --- /dev/null +++ b/centreon/lib/perl/plugins/plugin/example/command.pm @@ -0,0 +1,29 @@ +package plugin::example::command; + +use strict; +use warnings; +use base qw(centreon::plugins::script_simple); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '0.1'; + %{$self->{modes}} = ( + 'launchcmd' => 'plugin::example::mode::launchcmd' + ); + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +An example of local command plugin. + +=cut diff --git a/centreon/lib/perl/plugins/plugin/example/mode/getvalue.pm b/centreon/lib/perl/plugins/plugin/example/mode/getvalue.pm new file mode 100644 index 00000000000..b9534cf8680 --- /dev/null +++ b/centreon/lib/perl/plugins/plugin/example/mode/getvalue.pm @@ -0,0 +1,91 @@ +package plugin::example::mode::getvalue; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "oid:s" => { name => 'oid' }, + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (!defined($self->{option_results}->{oid})) { + $self->{output}->add_option_msg(short_msg => "Need to specify an OID."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } + +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + $self->{hostname} = $self->{snmp}->get_hostname(); + + my $result = $self->{snmp}->get_leef(oids => [$self->{option_results}->{oid}]); + my $value = $result->{$self->{option_results}->{oid}}; + + my $exit = $self->{perfdata}->threshold_check(value => $value, + threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("SNMP Value is %s.", $value)); + + $self->{output}->perfdata_add(label => 'value', unit => undef, + value => $value, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => undef, max => undef); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check an SNMP Integer value. + +=over 8 + +=item B<--oid> + +Check OID Integer value. + +=item B<--warning> + +Threshold warning. + +=item B<--critical> + +Threshold critical. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/plugin/example/mode/launchcmd.pm b/centreon/lib/perl/plugins/plugin/example/mode/launchcmd.pm new file mode 100644 index 00000000000..d24bf6f84c5 --- /dev/null +++ b/centreon/lib/perl/plugins/plugin/example/mode/launchcmd.pm @@ -0,0 +1,87 @@ +package plugin::example::mode::launchcmd; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::misc; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "cmd:s" => { name => 'cmd' }, + "timeout:s" => { name => 'timeout', default => 30 } + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (!defined($self->{option_results}->{cmd})) { + $self->{output}->add_option_msg(short_msg => "Need to specify a command."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + + my ($lerror, $stdout, $exit_code) = centreon::plugins::misc::backtick( + command => $self->{option_results}->{cmd}, + timeout => $self->{option_results}->{timeout}, + wait_exit => 1 + ); + $stdout =~ s/\r//g; + if ($exit_code <= -1000) { + if ($exit_code == -1000) { + $self->{output}->output_add(severity => 'UNKNOWN', + short_msg => $stdout); + } + $self->{output}->display(); + $self->{output}->exit(); + } + if ($exit_code != 0) { + $stdout =~ s/\n/ - /g; + $self->{output}->output_add(severity => 'UNKNOWN', + short_msg => "Command error: $stdout"); + $self->{output}->display(); + $self->{output}->exit(); + } + + $self->{output}->output_add(severity => 'OK', + short_msg => 'Command executed with no errors.'); + $self->{output}->output_add(long_msg => $stdout); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Launch a local command. Use --verbose to see the command output. + +=over 8 + +=item B<--cmd> + +Command to execute. + +=item B<--timeout> + +Timeout in seconds for the command (Default: 30). + +=back + +=cut diff --git a/centreon/lib/perl/plugins/plugin/example/snmp.pm b/centreon/lib/perl/plugins/plugin/example/snmp.pm new file mode 100644 index 00000000000..71273d38f41 --- /dev/null +++ b/centreon/lib/perl/plugins/plugin/example/snmp.pm @@ -0,0 +1,29 @@ +package plugin::example::snmp; + +use strict; +use warnings; +use base qw(centreon::plugins::script_snmp); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '0.1'; + %{$self->{modes}} = ( + 'getvalue' => 'plugin::example::mode::getvalue' + ); + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +An example of SNMP plugin type. + +=cut diff --git a/centreon/lib/perl/plugins/os_linux/snmp.pm b/centreon/lib/perl/plugins/plugin/linux/snmp.pm similarity index 68% rename from centreon/lib/perl/plugins/os_linux/snmp.pm rename to centreon/lib/perl/plugins/plugin/linux/snmp.pm index 1717d9e546f..dc79aef1c35 100644 --- a/centreon/lib/perl/plugins/os_linux/snmp.pm +++ b/centreon/lib/perl/plugins/plugin/linux/snmp.pm @@ -1,4 +1,4 @@ -package os_linux::snmp; +package plugin::linux::snmp; use strict; use warnings; @@ -11,8 +11,10 @@ sub new { # $options->{options} = options object $self->{version} = '0.1'; - %{$self->{modes}} = ('traffic' => 'snmp_standard::traffic'); - %{$self->{modes}} = ('storage' => 'snmp_standard::storage'); + %{$self->{modes}} = ( + 'traffic' => 'snmp_standard::mode::traffic', + 'storage' => 'snmp_standard::mode::storage' + ); #$self->{default} = [{option_mode => 'traffic', option_name => 'warning', option_value => '-1'}]; return $self; diff --git a/centreon/lib/perl/plugins/snmp_standard/storage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm similarity index 98% rename from centreon/lib/perl/plugins/snmp_standard/storage.pm rename to centreon/lib/perl/plugins/snmp_standard/mode/storage.pm index d0974375fd6..cc6484bfc57 100644 --- a/centreon/lib/perl/plugins/snmp_standard/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm @@ -1,11 +1,10 @@ -package snmp_standard::storage; +package snmp_standard::mode::storage; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::plugins::statefile; -use centreon::plugins::perfdata; use Digest::MD5 qw(md5_hex); my @operstatus = ("up", "down", "testing", "unknown", "dormant", "notPresent", "lowerLayerDown"); @@ -118,7 +117,7 @@ sub run { $threshold_value = $prct_used; $threshold_value = $prct_free if (defined($self->{option_results}->{free})); } - $exit = $self->{perfdata}->threshold_check(value => $threshold_value, threshold => [ { label => 'warning', 'exit_litteral' => 'warning' }, { label => 'critical', exit_litteral => 'critical' } ]); + $exit = $self->{perfdata}->threshold_check(value => $threshold_value, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); my ($total_size_value, $total_size_unit) = $self->{perfdata}->change_bytes(value => $total_size); my ($total_used_value, $total_used_unit) = $self->{perfdata}->change_bytes(value => $total_used); diff --git a/centreon/lib/perl/plugins/snmp_standard/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm similarity index 89% rename from centreon/lib/perl/plugins/snmp_standard/traffic.pm rename to centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index 8c361ae284d..145fcb41850 100644 --- a/centreon/lib/perl/plugins/snmp_standard/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -1,11 +1,10 @@ -package snmp_standard::traffic; +package snmp_standard::mode::traffic; use base qw(centreon::plugins::mode); use strict; use warnings; use centreon::plugins::statefile; -use centreon::plugins::perfdata; use Digest::MD5 qw(md5_hex); my @operstatus = ("up", "down", "testing", "unknown", "dormant", "notPresent", "lowerLayerDown"); @@ -23,8 +22,10 @@ sub new { $self->{version} = '1.0'; $options{options}->add_options(arguments => { - "warning:s" => { name => 'warning' }, - "critical:s" => { name => 'critical' }, + "warning-in:s" => { name => 'warning_in' }, + "critical-in:s" => { name => 'critical_in' }, + "warning-out:s" => { name => 'warning_out' }, + "critical-out:s" => { name => 'critical_out' }, "reload-cache-time:s" => { name => 'reload_cache_time' }, "name" => { name => 'use_name' }, "interface:s" => { name => 'interface' }, @@ -50,12 +51,20 @@ sub check_options { my ($self, %options) = @_; $self->SUPER::init(%options); - if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { - $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + if (($self->{perfdata}->threshold_validate(label => 'warning-in', value => $self->{option_results}->{warning_in})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'in' threshold '" . $self->{option_results}->{warning_in} . "'."); $self->{output}->option_exit(); } - if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { - $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + if (($self->{perfdata}->threshold_validate(label => 'critical-in', value => $self->{option_results}->{critical_in})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'in' threshold '" . $self->{option_results}->{critical_in} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warning-out', value => $self->{option_results}->{warning_out})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'out' threshold '" . $self->{option_results}->{warning_out} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical-out', value => $self->{option_results}->{critical_out})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'out' threshold '" . $self->{option_results}->{critical_out} . "'."); $self->{output}->option_exit(); } $self->{option_results}->{oid_filter} = lc($self->{option_results}->{oid_filter}); @@ -186,8 +195,8 @@ sub run { ########### # Manage Output ########### - my $exit1 = $self->{perfdata}->threshold_check(value => $in_prct, threshold => [ { label => 'warning', 'exit_litteral' => 'warning' }, { label => 'critical', exit_litteral => 'critical' } ]); - my $exit2 = $self->{perfdata}->threshold_check(value => $out_prct, threshold => [ { label => 'warning', 'exit_litteral' => 'warning' }, { label => 'critical', exit_litteral => 'critical' } ]); + my $exit1 = $self->{perfdata}->threshold_check(value => $in_prct, threshold => [ { label => 'critical-in', 'exit_litteral' => 'critical' }, { label => 'warning-in', exit_litteral => 'warning' } ]); + my $exit2 = $self->{perfdata}->threshold_check(value => $out_prct, threshold => [ { label => 'critical-out', 'exit_litteral' => 'critical' }, { label => 'warning-out', exit_litteral => 'warning' } ]); my ($in_value, $in_unit) = $self->{perfdata}->change_bytes(value => $in_absolute_per_sec, network => 1); my ($out_value, $out_unit) = $self->{perfdata}->change_bytes(value => $out_absolute_per_sec, network => 1); @@ -206,13 +215,13 @@ sub run { $extra_label = '_' . $display_value if (!defined($self->{option_results}->{interface}) || defined($self->{option_results}->{use_regexp})); $self->{output}->perfdata_add(label => 'traffic_in' . $extra_label, unit => 'b/s', value => sprintf("%.2f", $in_absolute_per_sec), - warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $interface_speed), - critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $interface_speed), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-in', total => $interface_speed), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-in', total => $interface_speed), min => 0, max => $interface_speed); $self->{output}->perfdata_add(label => 'traffic_out' . $extra_label, unit => 'b/s', value => sprintf("%.2f", $out_absolute_per_sec), - warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $interface_speed), - critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $interface_speed), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-out', total => $interface_speed), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-out', total => $interface_speed), min => 0, max => $interface_speed); } @@ -365,13 +374,21 @@ __END__ =over 8 -=item B<--warning> +=item B<--warning-in> + +Threshold warning in percent for 'in' traffic. + +=item B<--critical-in> + +Threshold critical in percent for 'in' traffic. + +=item B<--warning-out> -Threshold warning in percent. +Threshold warning in percent for 'out' traffic. -=item B<--critical> +=item B<--critical-out> -Threshold critical in percent. +Threshold critical in percent for 'out' traffic. =item B<--interface> From 582b718434b1d759fd4f2abc9d56963342f5c3fa Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 24 Oct 2013 13:58:28 +0200 Subject: [PATCH 108/458] Add JSON output --- centreon/lib/perl/centreon/plugins/output.pm | 169 +++++++++++++++---- 1 file changed, 134 insertions(+), 35 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/output.pm b/centreon/lib/perl/centreon/plugins/output.pm index 33fafcd73e8..c1c5074d9d6 100644 --- a/centreon/lib/perl/centreon/plugins/output.pm +++ b/centreon/lib/perl/centreon/plugins/output.pm @@ -17,6 +17,7 @@ sub new { "verbose" => { name => 'verbose' }, "opt-exit:s" => { name => 'opt_exit', default => 'unknown' }, "output-xml" => { name => 'output_xml' }, + "output-json" => { name => 'output_json' }, "disco-format" => { name => 'disco_format' }, "disco-show" => { name => 'disco_show' }, }); @@ -25,6 +26,7 @@ sub new { $self->{option_msg} = []; $self->{is_output_xml} = 0; + $self->{is_output_json} = 0; $self->{errors} = {OK => 0, WARNING => 1, CRITICAL => 2, UNKNOWN => 3, PENDING => 4}; $self->{myerrors} = {0 => "OK", 1 => "WARNING", 3 => "CRITICAL", 7 => "UNKNOWN"}; $self->{myerrors_mask} = {CRITICAL => 3, WARNING => 1, UNKNOWN => 7, OK => 0}; @@ -55,7 +57,10 @@ sub check_options { } # Go in XML Mode if ($self->is_disco_show() || $self->is_disco_format()) { - $self->{option_results}->{output_xml} = 1; + # By Default XML + if (!defined($self->{option_results}->{output_json})) { + $self->{option_results}->{output_xml} = 1; + } } } @@ -90,7 +95,7 @@ sub output_add { my $options = {%args, %params}; if (defined($options->{short_msg})) { - chomp $options->{short_msg}; + chomp $options->{short_msg}; if (defined($self->{global_short_concat_outputs}->{uc($options->{severity})})) { $self->{global_short_concat_outputs}->{uc($options->{severity})} .= $options->{separator} . $options->{short_msg}; } else { @@ -113,6 +118,55 @@ sub perfdata_add { push @{$self->{perfdatas}}, $perfdata; } +sub output_json { + my ($self, %options) = @_; + my $json_content = {plugin => { + name => $self->{plugin}, + mode => $self->{mode}, + exit => $options{exit_litteral}, + outputs => [], + perfdatas => [] + } + }; + + foreach my $code_litteral (keys %{$self->{global_short_outputs}}) { + foreach (@{$self->{global_short_outputs}->{$code_litteral}}) { + my ($child_output, $child_type, $child_msg, $child_exit); + my $lcode_litteral = ($code_litteral eq 'UNQUALIFIED_YET' ? uc($options{exit_litteral}) : $code_litteral); + + push @{$json_content->{plugin}->{outputs}}, { + type => 1, + msg => ($options{nolabel} == 0 ? ($lcode_litteral . ': ') : '') . $_, + exit => $lcode_litteral + }; + } + } + + if (defined($self->{option_results}->{verbose}) || defined($options{force_long_output})) { + foreach (@{$self->{global_long_output}}) { + push @{$json_content->{plugin}->{outputs}}, { + type => 2, + msg => $_, + }; + } + } + + if (!defined($self->{option_results}->{ignore_perfdata}) && !defined($options{force_ignore_perfdata})) { + foreach (@{$self->{perfdatas}}) { + my %values = (); + foreach my $key (keys %$_) { + $values{$key} = $_->{$key}; + } + + push @{$json_content->{plugin}->{perfdatas}}, { + %values + }; + } + } + + print $self->{json_output}->encode($json_content); +} + sub output_xml { my ($self, %options) = @_; my ($child_plugin_name, $child_plugin_mode, $child_plugin_exit, $child_plugin_output, $child_plugin_perfdata); @@ -139,7 +193,7 @@ sub output_xml { $root->addChild($child_plugin_perfdata); foreach my $code_litteral (keys %{$self->{global_short_outputs}}) { - foreach (@{$self->{global_short_outputs}->{$code_litteral}}) { + foreach (@{$self->{global_short_outputs}->{$code_litteral}}) { my ($child_output, $child_type, $child_msg, $child_exit); my $lcode_litteral = ($code_litteral eq 'UNQUALIFIED_YET' ? uc($options{exit_litteral}) : $code_litteral); @@ -161,7 +215,7 @@ sub output_xml { } if (defined($self->{option_results}->{verbose}) || defined($options{force_long_output})) { - foreach (@{$self->{global_long_output}}) { + foreach (@{$self->{global_long_output}}) { my ($child_output, $child_type, $child_msg); $child_output = $self->{xml_output}->createElement("output"); @@ -239,12 +293,17 @@ sub display { $self->create_xml_document(); if ($self->{is_output_xml}) { $self->output_xml(exit_litteral => $self->get_litteral_status()); - } else { - $self->output_txt(exit_litteral => $self->get_litteral_status()); + return ; } - } else { - $self->output_txt(exit_litteral => $self->get_litteral_status()); - } + } elsif (defined($self->{option_results}->{output_json})) { + $self->create_json_document(); + if ($self->{is_output_json}) { + $self->output_json(exit_litteral => $self->get_litteral_status()); + return ; + } + } + + $self->output_txt(exit_litteral => $self->get_litteral_status()); } sub option_exit { @@ -258,13 +317,17 @@ sub option_exit { $self->create_xml_document(); if ($self->{is_output_xml}) { $self->output_xml(exit_litteral => $exit_litteral, nolabel => $nolabel, force_ignore_perfdata => 1, force_long_output => 1); - } else { - $self->output_txt(exit_litteral => $exit_litteral, nolabel => $nolabel, force_ignore_perfdata => 1, force_long_output => 1); + $self->exit(exit_litteral => $exit_litteral); } - } else { - $self->output_txt(exit_litteral => $exit_litteral, nolabel => $nolabel, force_ignore_perfdata => 1, force_long_output => 1); - } - + } elsif (defined($self->{option_results}->{output_json})) { + $self->create_json_document(); + if ($self->{is_output_json}) { + $self->output_json(exit_litteral => $exit_litteral, nolabel => $nolabel, force_ignore_perfdata => 1, force_long_output => 1); + $self->exit(exit_litteral => $exit_litteral); + } + } + + $self->output_txt(exit_litteral => $exit_litteral, nolabel => $nolabel, force_ignore_perfdata => 1, force_long_output => 1); $self->exit(exit_litteral => $exit_litteral); } @@ -332,6 +395,14 @@ sub is_litteral_status { return 0; } +sub create_json_document { + my ($self) = @_; + + require JSON; + $self->{is_output_json} = 1; + $self->{json_output} = JSON->new->utf8(); +} + sub create_xml_document { my ($self) = @_; @@ -369,37 +440,61 @@ sub add_disco_format { sub display_disco_format { my ($self, %options) = @_; - $self->create_xml_document(); + if (defined($self->{option_results}->{output_xml})) { + $self->create_xml_document(); - my $root = $self->{xml_output}->createElement('data'); - $self->{xml_output}->setDocumentElement($root); + my $root = $self->{xml_output}->createElement('data'); + $self->{xml_output}->setDocumentElement($root); - foreach (@{$self->{disco_elements}}) { - my $child = $self->{xml_output}->createElement("element"); - $child->appendText($_); - $root->addChild($child); - } + foreach (@{$self->{disco_elements}}) { + my $child = $self->{xml_output}->createElement("element"); + $child->appendText($_); + $root->addChild($child); + } - print $self->{xml_output}->toString(1); + print $self->{xml_output}->toString(1); + } elsif (defined($self->{option_results}->{output_json})) { + $self->create_json_document(); + my $json_content = {data => [] }; + foreach (@{$self->{disco_elements}}) { + push @{$json_content->{data}}, $_; + } + + print $self->{json_output}->encode($json_content); + } } sub display_disco_show { my ($self, %options) = @_; - $self->create_xml_document(); - - my $root = $self->{xml_output}->createElement('data'); - $self->{xml_output}->setDocumentElement($root); + if (defined($self->{option_results}->{output_xml})) { + $self->create_xml_document(); + + my $root = $self->{xml_output}->createElement('data'); + $self->{xml_output}->setDocumentElement($root); - foreach (@{$self->{disco_entries}}) { - my $child = $self->{xml_output}->createElement("label"); - foreach my $key (keys %$_) { - $child->setAttribute($key, $_->{$key}); + foreach (@{$self->{disco_entries}}) { + my $child = $self->{xml_output}->createElement("label"); + foreach my $key (keys %$_) { + $child->setAttribute($key, $_->{$key}); + } + $root->addChild($child); } - $root->addChild($child); - } - print $self->{xml_output}->toString(1); + print $self->{xml_output}->toString(1); + } elsif (defined($self->{option_results}->{output_json})) { + $self->create_json_document(); + my $json_content = {data => [] }; + foreach (@{$self->{disco_entries}}) { + my %values = (); + foreach my $key (keys %$_) { + $values{$key} = $_->{$key}; + } + push @{$json_content->{data}}, {%values}; + } + + print $self->{json_output}->encode($json_content); + } } sub add_disco_entry { @@ -458,6 +553,10 @@ Exit code for an option error, usage (default: unknown). Display output in XML Format. +=item B<--output-json> + +Display output in JSON Format. + =item B<--disco-format> Display discovery arguments (if the mode manages it). From 5c552dd9f59daa80e47f10ce95e97aae663a826d Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 24 Oct 2013 14:13:52 +0200 Subject: [PATCH 109/458] + Add SNMP load-average checks --- .../lib/perl/plugins/plugin/linux/snmp.pm | 3 +- .../plugins/snmp_standard/mode/loadaverage.pm | 118 ++++++++++++++++++ 2 files changed, 120 insertions(+), 1 deletion(-) create mode 100644 centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm diff --git a/centreon/lib/perl/plugins/plugin/linux/snmp.pm b/centreon/lib/perl/plugins/plugin/linux/snmp.pm index dc79aef1c35..308fa81801c 100644 --- a/centreon/lib/perl/plugins/plugin/linux/snmp.pm +++ b/centreon/lib/perl/plugins/plugin/linux/snmp.pm @@ -13,7 +13,8 @@ sub new { $self->{version} = '0.1'; %{$self->{modes}} = ( 'traffic' => 'snmp_standard::mode::traffic', - 'storage' => 'snmp_standard::mode::storage' + 'storage' => 'snmp_standard::mode::storage', + 'load' => 'snmp_standard::mode::loadaverage' ); #$self->{default} = [{option_mode => 'traffic', option_name => 'warning', option_value => '-1'}]; diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm new file mode 100644 index 00000000000..65ee695a18b --- /dev/null +++ b/centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm @@ -0,0 +1,118 @@ +package snmp_standard::mode::loadaverage; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', default => '' }, + "critical:s" => { name => 'critical', default => '' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + ($self->{warn1}, $self->{warn5}, $self->{warn15}) = split /,/, $self->{option_results}->{warning}; + ($self->{crit1}, $self->{crit5}, $self->{crit15}) = split /,/, $self->{option_results}->{critical}; + + if (($self->{perfdata}->threshold_validate(label => 'warn1', value => $self->{warn1})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning (1min) threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warn5', value => $self->{warn5})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning (5min) threshold '" . $self->{warn5} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warn15', value => $self->{warn15})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning (15min) threshold '" . $self->{warn15} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'crit1', value => $self->{crit1})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical (1min) threshold '" . $self->{crit1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'crit5', value => $self->{crit5})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical (5min) threshold '" . $self->{crit5} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'crit15', value => $self->{crit15})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical (15min) threshold '" . $self->{crit15} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_CpuLoad1m = '.1.3.6.1.4.1.2021.10.1.3.1'; + my $oid_CpuLoad5m = '.1.3.6.1.4.1.2021.10.1.3.2'; + my $oid_CpuLoad15m = '.1.3.6.1.4.1.2021.10.1.3.3'; + + my $result = $self->{snmp}->get_leef(oids => [$oid_CpuLoad1m, $oid_CpuLoad5m, $oid_CpuLoad15m]); + + my $exit1 = $self->{perfdata}->threshold_check(value => $result->{$oid_CpuLoad1m}, + threshold => [ { label => 'crit1', 'exit_litteral' => 'critical' }, { label => 'warn1', exit_litteral => 'warning' } ]); + my $exit2 = $self->{perfdata}->threshold_check(value => $result->{$oid_CpuLoad5m}, + threshold => [ { label => 'crit5', 'exit_litteral' => 'critical' }, { label => 'warn5', exit_litteral => 'warning' } ]); + my $exit3 = $self->{perfdata}->threshold_check(value => $result->{$oid_CpuLoad15m}, + threshold => [ { label => 'crit15', 'exit_litteral' => 'critical' }, { label => 'warn15', exit_litteral => 'warning' } ]); + + my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2, $exit3 ]); + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Load average: %s, %s, %s", $result->{$oid_CpuLoad1m}, $result->{$oid_CpuLoad5m}, $result->{$oid_CpuLoad15m})); + + $self->{output}->perfdata_add(label => 'load1', + value => $result->{$oid_CpuLoad1m}, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warn1'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'crit1'), + min => 0); + $self->{output}->perfdata_add(label => 'load5', + value => $result->{$oid_CpuLoad5m}, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warn5'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'crit5'), + min => 0); + $self->{output}->perfdata_add(label => 'load15', + value => $result->{$oid_CpuLoad15m}, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warn15'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'crit15'), + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check system load-average. + +=over 8 + +=item B<--warning> + +Threshold warning (1min,5min,15min). + +=item B<--critical> + +Threshold critical (1min,5min,15min). + +=back + +=cut From da8bf0e4a93a23ffa8131c23b5ae727465b2db1e Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 24 Oct 2013 16:00:57 +0200 Subject: [PATCH 110/458] + Add snmp processcount standard --- .../lib/perl/plugins/plugin/linux/snmp.pm | 6 +- .../perl/plugins/snmp_standard/mode/cpu.pm | 95 +++++++++ .../snmp_standard/mode/processcount.pm | 182 ++++++++++++++++++ 3 files changed, 281 insertions(+), 2 deletions(-) create mode 100644 centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm create mode 100644 centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm diff --git a/centreon/lib/perl/plugins/plugin/linux/snmp.pm b/centreon/lib/perl/plugins/plugin/linux/snmp.pm index 308fa81801c..1f19d769c81 100644 --- a/centreon/lib/perl/plugins/plugin/linux/snmp.pm +++ b/centreon/lib/perl/plugins/plugin/linux/snmp.pm @@ -12,9 +12,11 @@ sub new { $self->{version} = '0.1'; %{$self->{modes}} = ( - 'traffic' => 'snmp_standard::mode::traffic', + 'cpu' => 'snmp_standard::mode::cpu', + 'load' => 'snmp_standard::mode::loadaverage', + 'processcount' => 'snmp_standard::mode::processcount', 'storage' => 'snmp_standard::mode::storage', - 'load' => 'snmp_standard::mode::loadaverage' + 'traffic' => 'snmp_standard::mode::traffic', ); #$self->{default} = [{option_mode => 'traffic', option_name => 'warning', option_value => '-1'}]; diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm b/centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm new file mode 100644 index 00000000000..8b30467b481 --- /dev/null +++ b/centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm @@ -0,0 +1,95 @@ +package snmp_standard::mode::cpu; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_cputable = '.1.3.6.1.2.1.25.3.3.1.2'; + my $result = $self->{snmp}->get_table(oid => $oid_cputable); + + my $cpu = 0; + my $i = 0; + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + $key =~ /\.([0-9]+)$/; + my $cpu_num = $1; + + $cpu += $result->{$key}; + $i++; + + $self->{output}->output_add(long_msg => sprintf("CPU $i Usage is %.2f%%", $result->{$key})); + $self->{output}->perfdata_add(label => 'cpu' . $cpu_num, + value => sprintf("%.2f", $result->{$key}), + min => 0, max => 100); + } + + my $avg_cpu = $cpu / $i; + my $exit_code = $self->{perfdata}->threshold_check(value => $avg_cpu, + threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("CPU(s) average usage is: %.2f%%", $avg_cpu)); + $self->{output}->perfdata_add(label => 'total_cpu_avg', + value => sprintf("%.2f", $avg_cpu), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0, max => 100); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check system CPUs. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm b/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm new file mode 100644 index 00000000000..cbda70bcf3b --- /dev/null +++ b/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm @@ -0,0 +1,182 @@ +package snmp_standard::mode::processcount; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + "process-name:s" => { name => 'process_name', }, + "regexp-name" => { name => 'regexp_name', }, + "process-path:s" => { name => 'process_path', }, + "regexp-path" => { name => 'regexp_path', }, + "process-args:s" => { name => 'process_args', }, + "regexp-args" => { name => 'regexp_args', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } + if (!defined($self->{option_results}->{process_name}) && + !defined($self->{option_results}->{process_path}) && + !defined($self->{option_results}->{process_args}) + ) { + $self->{output}->add_option_msg(short_msg => "Need to specify at least one argument '--process-*'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oids = { + name => '.1.3.6.1.2.1.25.4.2.1.2', # hrSWRunName + path => '.1.3.6.1.2.1.25.4.2.1.4', # hrSWRunPath + args => '.1.3.6.1.2.1.25.4.2.1.5', # hrSWRunParameters (Warning: it's truncated. (128 characters)) + }; + + my $oid_hrSWRunStatus = '.1.3.6.1.2.1.25.4.2.1.7'; + + my $oid2check_filter; + foreach (keys %$oids) { + if (defined($self->{option_results}->{'process_' . $_})) { + $oid2check_filter = $_; + last; + } + } + # Build other + my $mores_filters = {}; + my $more_oids = [$oid_hrSWRunStatus]; + foreach (keys %$oids) { + if ($_ ne $oid2check_filter && defined($self->{option_results}->{'process_' . $_})) { + push @{$more_oids}, $oids->{$_}; + $mores_filters->{$_} = 1; + } + } + + my $result = $self->{snmp}->get_table(oid => $oids->{$oid2check_filter}); + my $instances_keep = {}; + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + my $val = $self->{option_results}->{'process_' . $oid2check_filter}; + + if ((defined($self->{option_results}->{'regexp_' . $oid2check_filter}) && $result->{$key} =~ /$val/) + || (!defined($self->{option_results}->{'regexp_' . $oid2check_filter}) && $result->{$key} eq $val)) { + $key =~ /\.([0-9]+)$/; + $instances_keep->{$1} = 1; + } + } + + if (scalar(keys %$instances_keep) > 0) { + $self->{snmp}->load(oids => $more_oids, instances => [keys %$instances_keep ]); + my $result2 = $self->{snmp}->get_leef(); + + foreach my $key (keys %$instances_keep) { + # 1 = running, 2 = runnable, 3 = notRunnable, 4 => invalid + if (!defined($result2->{$oid_hrSWRunStatus . "." . $key}) || $result2->{$oid_hrSWRunStatus . "." . $key} > 2) { + delete $instances_keep->{$key}; + next; + } + + my $long_value = '[ ' . $oid2check_filter . ' => ' . $result->{$oids->{$oid2check_filter} . '.' . $key} . ' ]'; + my $deleted = 0; + foreach (keys %$mores_filters) { + my $val = $self->{option_results}->{'process_' . $_}; + + if ((defined($self->{option_results}->{'regexp_' . $_}) && $result2->{$oids->{$_} . '.' . $key} !~ /$val/) + || (!defined($self->{option_results}->{'regexp_' . $_}) && $result2->{$oids->{$_} . '.' . $key} ne $val)) { + delete $instances_keep->{$key}; + $deleted = 1; + last; + } + + $long_value .= ' [ ' . $_ . ' => ' . $result2->{$oids->{$_} . '.' . $key} . ' ]'; + } + + if ($deleted == 0) { + $self->{output}->output_add(long_msg => 'Process: ' . $long_value); + } + } + } + + my $num_processes_match = scalar(keys(%$instances_keep)); + my $exit = $self->{perfdata}->threshold_check(value => $num_processes_match, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit, + short_msg => "Number of current processes running: $num_processes_match"); + $self->{output}->perfdata_add(label => 'nbproc', + value => $num_processes_match, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check system number of processes. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=item B<--process-name> + +Check process name. + +=item B<--regexp-name> + +Allows to use regexp to filter process name (with option --process-name). + +=item B<--process-path> + +Check process path. + +=item B<--regexp-path> + +Allows to use regexp to filter process path (with option --process-path). + +=item B<--process-args> + +Check process args. + +=item B<--regexp-args> + +Allows to use regexp to filter process args (with option --process-args). + +=back + +=cut From bef448049e0eb48988805134fc523b7919e7debc Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 24 Oct 2013 17:35:33 +0200 Subject: [PATCH 111/458] + Begin memcached integration --- centreon/lib/perl/centreon/plugins/options.pm | 8 +++++ .../lib/perl/centreon/plugins/statefile.pm | 34 ++++++++++++++++--- .../plugins/snmp_standard/mode/storage.pm | 6 ++-- .../plugins/snmp_standard/mode/traffic.pm | 9 +++-- 4 files changed, 48 insertions(+), 9 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/options.pm b/centreon/lib/perl/centreon/plugins/options.pm index c3840d00481..a06899ea7fe 100644 --- a/centreon/lib/perl/centreon/plugins/options.pm +++ b/centreon/lib/perl/centreon/plugins/options.pm @@ -14,6 +14,7 @@ sub new { $self->{options_stored} = {}; $self->{options} = {}; @{$self->{pod_package}} = (); + $self->{pod_packages_once} = {}; return $self; } @@ -46,12 +47,19 @@ sub add_help { # $options{package} = string package # $options{sections} = string sections # $options{help_first} = put at the beginning + # $options{once} = put help only one time for a package + + if (defined($options{once}) && defined($self->{pod_packages_once}->{$options{package}})) { + return ; + } if (defined($options{help_first})) { shift @{$self->{pod_package}}, {package => $options{package}, sections => $options{sections}}; } else { push @{$self->{pod_package}}, {package => $options{package}, sections => $options{sections}}; } + + $self->{pod_packages_once}->{$options{package}} = 1; } sub add_options { diff --git a/centreon/lib/perl/centreon/plugins/statefile.pm b/centreon/lib/perl/centreon/plugins/statefile.pm index 69602e095f8..ed42c9774ea 100644 --- a/centreon/lib/perl/centreon/plugins/statefile.pm +++ b/centreon/lib/perl/centreon/plugins/statefile.pm @@ -8,15 +8,33 @@ sub new { my $self = {}; bless $self, $class; + if (defined($options{options})) { + $options{options}->add_options(arguments => + { + "memcached:s" => { name => 'memcached' }, + }); + $options{options}->add_help(package => __PACKAGE__, sections => 'RETENTION OPTIONS', once => 1); + } + $self->{output} = $options{output}; $self->{statefile_dir} = '/var/lib/centreon/centplugins'; $self->{datas} = {}; - + $self->{memcached} = undef; + return $self; } +sub check_options { + my ($self, %options) = @_; + + if (defined($options{option_results}) && defined($options{option_results}->{memcached})) { + $self->{memcached} = $options{option_results}->{memcached}; + } + +} + sub read { - my ($self, %options) = @_; + my ($self, %options) = @_; $self->{statefile_dir} = defined($options{statefile_dir}) ? $options{statefile_dir} : $self->{statefile_dir}; $self->{statefile} = defined($options{statefile}) ? $options{statefile} : $self->{statefile}; @@ -37,11 +55,11 @@ sub read { $self->{output}->option_exit(); } unless (defined($return)) { - $self->{output}->add_option_msg(short_msg => "Couldn't do '" . $self->{statefile_dir} . "/" . $self->{statefile} . "': $!"); + $self->{output}->add_option_msg(short_msg => "Couldn't do '" . $self->{statefile_dir} . "/" . $self->{statefile} . "': $!"); $self->{output}->option_exit(); } unless ($return) { - $self->{output}->add_option_msg(short_msg => "Couldn't run '" . $self->{statefile_dir} . "/" . $self->{statefile} . "': $!"); + $self->{output}->add_option_msg(short_msg => "Couldn't run '" . $self->{statefile_dir} . "/" . $self->{statefile} . "': $!"); $self->{output}->option_exit(); } } @@ -86,6 +104,14 @@ Statefile class - +=head1 RETENTION OPTIONS + +=over 8 + +=item B<--memcached> + +Memcached server to use (only one server). + =head1 DESCRIPTION B. diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm index cc6484bfc57..1157e740d93 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm @@ -41,7 +41,8 @@ sub new { }); $self->{storage_id_selected} = []; - + $self->{statefile_cache} = centreon::plugins::statefile->new(%options); + return $self; } @@ -67,6 +68,8 @@ sub check_options { $self->{output}->add_option_msg(short_msg => "Unsupported --oid-display option."); $self->{output}->option_exit(); } + + $self->{statefile_cache}->check_options(%options); } sub run { @@ -202,7 +205,6 @@ sub manage_selection { my ($self, %options) = @_; # init cache file - $self->{statefile_cache} = centreon::plugins::statefile->new(output => $self->{output}); my $has_cache_file = $self->{statefile_cache}->read(statefile_dir => $self->{option_results}->{statefiledir_cache}, statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); if (defined($self->{option_results}->{show_cache})) { diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index 145fcb41850..46401c9f95a 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -43,7 +43,9 @@ sub new { }); $self->{interface_id_selected} = []; - + $self->{statefile_cache} = centreon::plugins::statefile->new(%options); + $self->{statefile_value} = centreon::plugins::statefile->new(%options); + return $self; } @@ -77,6 +79,9 @@ sub check_options { $self->{output}->add_option_msg(short_msg => "Unsupported --oid-display option."); $self->{output}->option_exit(); } + + $self->{statefile_cache}->check_options(%options); + $self->{statefile_value}->check_options(%options); } sub run { @@ -97,7 +102,6 @@ sub run { my $oid_out64 = '.1.3.6.1.2.1.31.1.1.1.10'; # in B my $new_datas = {}; - $self->{statefile_value} = centreon::plugins::statefile->new(output => $self->{output}); $self->{statefile_value}->read(statefile_dir => $self->{option_results}->{statefiledir_values}, statefile => $self->{hostname} . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{interface}) ? md5_hex($self->{option_results}->{interface}) : md5_hex('all'))); @@ -281,7 +285,6 @@ sub manage_selection { my ($self, %options) = @_; # init cache file - $self->{statefile_cache} = centreon::plugins::statefile->new(output => $self->{output}); my $has_cache_file = $self->{statefile_cache}->read(statefile_dir => $self->{option_results}->{statefiledir_cache}, statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); if (defined($self->{option_results}->{show_cache})) { From 0d2c97bf216c2d2cbeea9c6cce1675ccb709d3bd Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sat, 26 Oct 2013 23:30:21 +0200 Subject: [PATCH 112/458] + Prepare DBI class: sqlmode at last --- centreon/lib/perl/centreon/plugins/options.pm | 2 +- centreon/lib/perl/centreon/plugins/script.pm | 31 ++----- .../perl/centreon/plugins/script_simple.pm | 81 +++++++++++++++---- .../lib/perl/centreon/plugins/script_snmp.pm | 81 +++++++++++++++---- centreon/lib/perl/centreon/plugins/snmp.pm | 2 +- .../lib/perl/centreon/plugins/statefile.pm | 11 ++- centreon/lib/perl/plugins/centreon_plugins.pl | 8 -- .../plugins/plugin/example/mode/getvalue.pm | 2 +- .../plugins/snmp_standard/mode/storage.pm | 13 +-- .../plugins/snmp_standard/mode/traffic.pm | 16 +--- 10 files changed, 157 insertions(+), 90 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/options.pm b/centreon/lib/perl/centreon/plugins/options.pm index a06899ea7fe..a6b4d03fa34 100644 --- a/centreon/lib/perl/centreon/plugins/options.pm +++ b/centreon/lib/perl/centreon/plugins/options.pm @@ -29,7 +29,7 @@ sub display_help { foreach (@{$self->{pod_package}}) { my $stdout; - + { local *STDOUT; open STDOUT, '>', \$stdout; diff --git a/centreon/lib/perl/centreon/plugins/script.pm b/centreon/lib/perl/centreon/plugins/script.pm index 834fa8d770c..741118c026e 100644 --- a/centreon/lib/perl/centreon/plugins/script.pm +++ b/centreon/lib/perl/centreon/plugins/script.pm @@ -47,28 +47,26 @@ sub handle_DIE { sub get_plugin { my $self = shift; + ###### + # Need to load global 'Output' and 'Options' + ###### $self->{options} = centreon::plugins::options->new(); $self->{output} = centreon::plugins::output->new(options => $self->{options}); $self->{options}->set_output(output => $self->{output}); $self->{options}->add_options(arguments => { 'plugin:s' => { name => 'plugin' }, - 'mode:s' => { name => 'mode' }, 'help' => { name => 'help' }, - 'list' => { name => 'list' }, 'version' => { name => 'version' } } ); $self->{options}->parse_options(); $self->{plugin} = $self->{options}->get_option(argument => 'plugin' ); - $self->{mode} = $self->{options}->get_option(argument => 'mode' ); - $self->{list} = $self->{options}->get_option(argument => 'list' ); $self->{help} = $self->{options}->get_option(argument => 'help' ); $self->{version} = $self->{options}->get_option(argument => 'version' ); $self->{output}->mode(name => $self->{mode}); $self->{output}->plugin(name => $self->{plugin}); - $self->{output}->check_options(option_results => $self->{options}->get_options()); $self->{options}->clean(); @@ -92,31 +90,18 @@ sub run { $self->get_plugin(); + if (defined($self->{help}) && !defined($self->{plugin})) { + $self->display_local_help(); + $self->{output}->option_exit(); + } if (!defined($self->{plugin}) || $self->{plugin} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify '--plugin' option."); - $self->display_local_help(); $self->{output}->option_exit(); } (my $file = $self->{plugin} . ".pm") =~ s{::}{/}g; require $file; my $plugin = $self->{plugin}->new(options => $self->{options}, output => $self->{output}); - - if (defined($self->{version}) && !defined($self->{mode})) { - $plugin->version(); - } - if (defined($self->{list})) { - $plugin->list(); - } - if (!defined($self->{mode}) || $self->{mode} eq '') { - $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' option."); - $self->display_local_help(); - $self->{output}->option_exit(); - } - - $plugin->is_mode(mode => $self->{mode}); - - $plugin->init(mode => $self->{mode}, - help => $self->{help}, + $plugin->init(help => $self->{help}, version => $self->{version}); $plugin->run(); } diff --git a/centreon/lib/perl/centreon/plugins/script_simple.pm b/centreon/lib/perl/centreon/plugins/script_simple.pm index 6b6072405cd..cc37cb39580 100644 --- a/centreon/lib/perl/centreon/plugins/script_simple.pm +++ b/centreon/lib/perl/centreon/plugins/script_simple.pm @@ -2,41 +2,69 @@ package centreon::plugins::script_simple; use strict; use warnings; -use centreon::plugins::output; sub new { my ($class, %options) = @_; my $self = {}; bless $self, $class; + # $options{package} = parent package caller # $options{options} = options object # $options{output} = output object - + $self->{options} = $options{options}; + $self->{output} = $options{output}; + + $self->{options}->add_options( + arguments => { + 'mode:s' => { name => 'mode' }, + 'list-mode' => { name => 'list_mode' }, + } + ); $self->{version} = '1.0'; %{$self->{modes}} = (); $self->{default} = undef; + + $self->{options}->parse_options(); + $self->{mode_name} = $self->{options}->get_option(argument => 'mode' ); + $self->{list_mode} = $self->{options}->get_option(argument => 'list_mode' ); + $self->{options}->clean(); - $self->{options} = $options{options}; - $self->{output} = $options{output}; $self->{options}->add_help(package => $options{package}, sections => 'PLUGIN DESCRIPTION'); + $self->{options}->add_help(package => __PACKAGE__, sections => 'GLOBAL OPTIONS'); return $self; } sub init { my ($self, %options) = @_; - # $options{mode} = string mode + # $options{version} = string version # $options{help} = string help - # Load output + if (defined($options{help}) && !defined($self->{mode_name})) { + $self->{options}->display_help(); + $self->{output}->option_exit(); + } + if (defined($options{version}) && !defined($self->{mode_name})) { + $self->version(); + } + if (defined($self->{list_mode})) { + $self->list_mode(); + } + if (!defined($self->{mode_name}) || $self->{mode_name} eq '') { + $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' option."); + $self->{output}->option_exit(); + } + $self->is_mode(mode => $self->{mode_name}); + + # Output HELP $self->{options}->add_help(package => 'centreon::plugins::output', sections => 'OUTPUT OPTIONS'); # Load mode - (my $file = $self->{modes}{$options{mode}} . ".pm") =~ s{::}{/}g; + (my $file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; require $file; - $self->{mode} = $self->{modes}{$options{mode}}->new(options => $self->{options}, output => $self->{output}, mode => $options{mode}); + $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); if (defined($options{help})) { - $self->{options}->add_help(package => $self->{modes}{$options{mode}}, sections => 'MODE'); + $self->{options}->add_help(package => $self->{modes}{$self->{mode_name}}, sections => 'MODE'); $self->{options}->display_help(); $self->{output}->option_exit(); } @@ -68,14 +96,12 @@ sub is_mode { } sub version { - my $self = shift; - $self->{options}->display_help(); - - $self->{output}->add_option_msg(long_msg => "Plugin Version: " . $self->{version}); + my $self = shift; + $self->{output}->add_option_msg(short_msg => "Plugin Version: " . $self->{version}); $self->{output}->option_exit(nolabel => 1); } -sub list { +sub list_mode { my $self = shift; $self->{options}->display_help(); @@ -90,3 +116,30 @@ sub list { __END__ +=head1 NAME + +- + +=head1 SYNOPSIS + +- + +=head1 GLOBAL OPTIONS + +=over 8 + +=item B<--mode> + +Choose a mode (required). + +=item B<--list-mode> + +List available modes. + +=back + +=head1 DESCRIPTION + +B<>. + +=cut diff --git a/centreon/lib/perl/centreon/plugins/script_snmp.pm b/centreon/lib/perl/centreon/plugins/script_snmp.pm index 82ad8d9e438..553ae916469 100644 --- a/centreon/lib/perl/centreon/plugins/script_snmp.pm +++ b/centreon/lib/perl/centreon/plugins/script_snmp.pm @@ -3,44 +3,72 @@ package centreon::plugins::script_snmp; use strict; use warnings; use centreon::plugins::snmp; -use centreon::plugins::output; sub new { my ($class, %options) = @_; my $self = {}; bless $self, $class; + # $options{package} = parent package caller # $options{options} = options object # $options{output} = output object - + $self->{options} = $options{options}; + $self->{output} = $options{output}; + + $self->{options}->add_options( + arguments => { + 'mode:s' => { name => 'mode' }, + 'list-mode' => { name => 'list_mode' }, + } + ); $self->{version} = '1.0'; %{$self->{modes}} = (); $self->{default} = undef; + + $self->{options}->parse_options(); + $self->{mode_name} = $self->{options}->get_option(argument => 'mode' ); + $self->{list_mode} = $self->{options}->get_option(argument => 'list_mode' ); + $self->{options}->clean(); - $self->{options} = $options{options}; - $self->{output} = $options{output}; $self->{options}->add_help(package => $options{package}, sections => 'PLUGIN DESCRIPTION'); + $self->{options}->add_help(package => __PACKAGE__, sections => 'GLOBAL OPTIONS'); return $self; } sub init { my ($self, %options) = @_; - # $options{mode} = string mode + # $options{version} = string version # $options{help} = string help - # Load output + if (defined($options{help}) && !defined($self->{mode_name})) { + $self->{options}->display_help(); + $self->{output}->option_exit(); + } + if (defined($options{version}) && !defined($self->{mode_name})) { + $self->version(); + } + if (defined($self->{list_mode})) { + $self->list_mode(); + } + if (!defined($self->{mode_name}) || $self->{mode_name} eq '') { + $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' option."); + $self->{output}->option_exit(); + } + $self->is_mode(mode => $self->{mode_name}); + + # Output HELP $self->{options}->add_help(package => 'centreon::plugins::output', sections => 'OUTPUT OPTIONS'); # SNMP $self->{snmp} = centreon::plugins::snmp->new(options => $self->{options}, output => $self->{output}); # Load mode - (my $file = $self->{modes}{$options{mode}} . ".pm") =~ s{::}{/}g; + (my $file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; require $file; - $self->{mode} = $self->{modes}{$options{mode}}->new(options => $self->{options}, output => $self->{output}, mode => $options{mode}); + $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); if (defined($options{help})) { - $self->{options}->add_help(package => $self->{modes}{$options{mode}}, sections => 'MODE'); + $self->{options}->add_help(package => $self->{modes}{$self->{mode_name}}, sections => 'MODE'); $self->{options}->display_help(); $self->{output}->option_exit(); } @@ -86,14 +114,12 @@ sub is_mode { } sub version { - my $self = shift; - $self->{options}->display_help(); - - $self->{output}->add_option_msg(long_msg => "Plugin Version: " . $self->{version}); + my $self = shift; + $self->{output}->add_option_msg(short_msg => "Plugin Version: " . $self->{version}); $self->{output}->option_exit(nolabel => 1); } -sub list { +sub list_mode { my $self = shift; $self->{options}->display_help(); @@ -108,3 +134,30 @@ sub list { __END__ +=head1 NAME + +- + +=head1 SYNOPSIS + +- + +=head1 GLOBAL OPTIONS + +=over 8 + +=item B<--mode> + +Choose a mode (required). + +=item B<--list-mode> + +List available modes. + +=back + +=head1 DESCRIPTION + +B<>. + +=cut diff --git a/centreon/lib/perl/centreon/plugins/snmp.pm b/centreon/lib/perl/centreon/plugins/snmp.pm index 1b85f8f93d3..2d3ff8d1d3a 100644 --- a/centreon/lib/perl/centreon/plugins/snmp.pm +++ b/centreon/lib/perl/centreon/plugins/snmp.pm @@ -196,7 +196,7 @@ sub get_leef { if ($self->{session}->{ErrorNum}) { my $msg = 'SNMP GET Request : ' . $self->{session}->{ErrorStr}; - if ($dont_quit == 0) { + if ($dont_quit == 1) { $self->{output}->add_option_msg(short_msg => $msg); $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); } diff --git a/centreon/lib/perl/centreon/plugins/statefile.pm b/centreon/lib/perl/centreon/plugins/statefile.pm index ed42c9774ea..f65747a2fb6 100644 --- a/centreon/lib/perl/centreon/plugins/statefile.pm +++ b/centreon/lib/perl/centreon/plugins/statefile.pm @@ -12,14 +12,15 @@ sub new { $options{options}->add_options(arguments => { "memcached:s" => { name => 'memcached' }, + "statefile-dir:s" => { name => 'statefile_dir', default => '/var/lib/centreon/centplugins' }, }); $options{options}->add_help(package => __PACKAGE__, sections => 'RETENTION OPTIONS', once => 1); } $self->{output} = $options{output}; - $self->{statefile_dir} = '/var/lib/centreon/centplugins'; $self->{datas} = {}; $self->{memcached} = undef; + $self->{statefile_dir} = undef; return $self; } @@ -30,7 +31,7 @@ sub check_options { if (defined($options{option_results}) && defined($options{option_results}->{memcached})) { $self->{memcached} = $options{option_results}->{memcached}; } - + $self->{statefile_dir} = $options{option_results}->{statefile_dir}; } sub read { @@ -112,6 +113,12 @@ Statefile class Memcached server to use (only one server). +=item B<--statefile-dir> + +Directory for statefile (Default: '/var/lib/centreon/centplugins'). + +=back + =head1 DESCRIPTION B. diff --git a/centreon/lib/perl/plugins/centreon_plugins.pl b/centreon/lib/perl/plugins/centreon_plugins.pl index 084976a144f..6905122ca02 100644 --- a/centreon/lib/perl/plugins/centreon_plugins.pl +++ b/centreon/lib/perl/plugins/centreon_plugins.pl @@ -23,14 +23,6 @@ =head1 OPTIONS Specify the path to the plugin. -=item B<--mode> - -Specify the mode of the plugin. - -=item B<--list> - -List mode available for the plugin. - =item B<--version> Print plugin version. diff --git a/centreon/lib/perl/plugins/plugin/example/mode/getvalue.pm b/centreon/lib/perl/plugins/plugin/example/mode/getvalue.pm index b9534cf8680..463b845357a 100644 --- a/centreon/lib/perl/plugins/plugin/example/mode/getvalue.pm +++ b/centreon/lib/perl/plugins/plugin/example/mode/getvalue.pm @@ -46,7 +46,7 @@ sub run { $self->{snmp} = $options{snmp}; $self->{hostname} = $self->{snmp}->get_hostname(); - my $result = $self->{snmp}->get_leef(oids => [$self->{option_results}->{oid}]); + my $result = $self->{snmp}->get_leef(oids => [$self->{option_results}->{oid}], nothing_quit => 1); my $value = $result->{$self->{option_results}->{oid}}; my $exit = $self->{perfdata}->threshold_check(value => $value, diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm index 1157e740d93..3541eaeb111 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm @@ -31,8 +31,6 @@ sub new { "storage:s" => { name => 'storage' }, "regexp" => { name => 'use_regexp' }, "regexp-isensitive" => { name => 'use_regexpi' }, - "statefiledir-cache:s" => { name => 'statefiledir_cache' }, - "statefiledir-values:s" => { name => 'statefiledir_values' }, "oid-filter:s" => { name => 'oid_filter', default => 'hrStorageDescr'}, "oid-display:s" => { name => 'oid_display', default => 'hrStorageDescr'}, "display-transform-src:s" => { name => 'display_transform_src' }, @@ -205,8 +203,7 @@ sub manage_selection { my ($self, %options) = @_; # init cache file - my $has_cache_file = $self->{statefile_cache}->read(statefile_dir => $self->{option_results}->{statefiledir_cache}, - statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + my $has_cache_file = $self->{statefile_cache}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); if (defined($self->{option_results}->{show_cache})) { $self->{output}->add_option_msg(long_msg => $self->{statefile_cache}->get_string_content()); $self->{output}->option_exit(); @@ -340,14 +337,6 @@ Allows to use regexp to filter storage (with option --name). Allows to use regexp non case-sensitive (with --regexp). -=item B<--statefiledir-cache> - -Directory path of statefile 'cache'. - -=item B<--statefiledir-values> - -Directory path of statefile 'values'. - =item B<--reload-cache-time> Time in seconds before reloading cache file (default: 180). diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index 46401c9f95a..eb01e8c89c4 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -33,8 +33,6 @@ sub new { "skip" => { name => 'skip' }, "regexp" => { name => 'use_regexp' }, "regexp-isensitive" => { name => 'use_regexpi' }, - "statefiledir-cache:s" => { name => 'statefiledir_cache' }, - "statefiledir-values:s" => { name => 'statefiledir_values' }, "oid-filter:s" => { name => 'oid_filter', default => 'ifDesc'}, "oid-display:s" => { name => 'oid_display', default => 'ifDesc'}, "display-transform-src:s" => { name => 'display_transform_src' }, @@ -102,8 +100,7 @@ sub run { my $oid_out64 = '.1.3.6.1.2.1.31.1.1.1.10'; # in B my $new_datas = {}; - $self->{statefile_value}->read(statefile_dir => $self->{option_results}->{statefiledir_values}, - statefile => $self->{hostname} . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{interface}) ? md5_hex($self->{option_results}->{interface}) : md5_hex('all'))); + $self->{statefile_value}->read(statefile => $self->{hostname} . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{interface}) ? md5_hex($self->{option_results}->{interface}) : md5_hex('all'))); foreach (@{$self->{interface_id_selected}}) { $self->{snmp}->load(oids => [$oid_adminstatus . "." . $_, $oid_operstatus . "." . $_, $oid_in32 . "." . $_, $oid_out32 . "." . $_]); @@ -285,8 +282,7 @@ sub manage_selection { my ($self, %options) = @_; # init cache file - my $has_cache_file = $self->{statefile_cache}->read(statefile_dir => $self->{option_results}->{statefiledir_cache}, - statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + my $has_cache_file = $self->{statefile_cache}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); if (defined($self->{option_results}->{show_cache})) { $self->{output}->add_option_msg(long_msg => $self->{statefile_cache}->get_string_content()); $self->{output}->option_exit(); @@ -417,14 +413,6 @@ Set interface speed (in Mb). Skip errors on interface status. -=item B<--statefiledir-cache> - -Directory path of statefile 'cache'. - -=item B<--statefiledir-values> - -Directory path of statefile 'values'. - =item B<--reload-cache-time> Time in seconds before reloading cache file (default: 180). From 89995da539afc8f018aff839ae9b69bef4279ff3 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sun, 27 Oct 2013 18:40:31 +0100 Subject: [PATCH 113/458] + add runas et environment system --- centreon/lib/perl/centreon/plugins/misc.pm | 7 +- centreon/lib/perl/centreon/plugins/options.pm | 3 - centreon/lib/perl/centreon/plugins/script.pm | 73 ++++++++++++++++++- centreon/lib/perl/plugins/centreon_plugins.pl | 9 +++ 4 files changed, 87 insertions(+), 5 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/misc.pm b/centreon/lib/perl/centreon/plugins/misc.pm index e08121c404c..d8735f49133 100644 --- a/centreon/lib/perl/centreon/plugins/misc.pm +++ b/centreon/lib/perl/centreon/plugins/misc.pm @@ -6,6 +6,7 @@ use warnings; sub backtick { my %arg = ( command => undef, + arguments => [], timeout => 30, wait_exit => 0, @_, @@ -60,7 +61,11 @@ sub backtick { # kill -9 will kill it and all its descendents setpgrp( 0, 0 ); - exec($arg{command}); + if (scalar(@{$arg{arguments}}) <= 0) { + exec($arg{command}); + } else { + exec($arg{command}, @{$arg{arguments}}); + } exit(0); } diff --git a/centreon/lib/perl/centreon/plugins/options.pm b/centreon/lib/perl/centreon/plugins/options.pm index a6b4d03fa34..80667da8758 100644 --- a/centreon/lib/perl/centreon/plugins/options.pm +++ b/centreon/lib/perl/centreon/plugins/options.pm @@ -80,12 +80,9 @@ sub parse_options { my $self = shift; #%{$self->{options_stored}} = (); - # Need to save to check multiples times (centos 5 Getopt don't have 'GetOptionsFromArray' - my @save_argv = @ARGV; GetOptions( %{$self->{options}} ); - @ARGV = @save_argv; %{$self->{options}} = (); } diff --git a/centreon/lib/perl/centreon/plugins/script.pm b/centreon/lib/perl/centreon/plugins/script.pm index 741118c026e..dc48211cbfe 100644 --- a/centreon/lib/perl/centreon/plugins/script.pm +++ b/centreon/lib/perl/centreon/plugins/script.pm @@ -4,6 +4,7 @@ use strict; use warnings; use centreon::plugins::options; use centreon::plugins::output; +use centreon::plugins::misc; use FindBin; use Pod::Usage; @@ -57,13 +58,18 @@ sub get_plugin { $self->{options}->add_options(arguments => { 'plugin:s' => { name => 'plugin' }, 'help' => { name => 'help' }, - 'version' => { name => 'version' } } ); + 'version' => { name => 'version' }, + 'runas:s' => { name => 'runas' }, + 'environment:s%' => { name => 'environment' }, + } ); $self->{options}->parse_options(); $self->{plugin} = $self->{options}->get_option(argument => 'plugin' ); $self->{help} = $self->{options}->get_option(argument => 'help' ); $self->{version} = $self->{options}->get_option(argument => 'version' ); + $self->{runas} = $self->{options}->get_option(argument => 'runas' ); + $self->{environment} = $self->{options}->get_option(argument => 'environment' ); $self->{output}->mode(name => $self->{mode}); $self->{output}->plugin(name => $self->{plugin}); @@ -85,6 +91,68 @@ sub display_local_help { $self->{output}->add_option_msg(long_msg => $stdout) if (defined($stdout)); } +sub check_relaunch { + my $self = shift; + my $need_restart = 0; + my $cmd = $FindBin::Bin . "/" . $FindBin::Script; + my @args = (); + + if (defined($self->{environment})) { + foreach (keys %{$self->{environment}}) { + if ($_ ne '' && (!defined($ENV{$_}) || $ENV{$_} ne $self->{environment}->{$_})) { + $ENV{$_} = $self->{environment}->{$_}; + $need_restart = 1; + } + } + } + + if (defined($self->{runas}) && $self->{runas} ne '') { + # Check if it's already me and user exist ;) + my ($name, $passwd, $uid) = getpwnam($self->{runas}); + if (!defined($uid)) { + $self->{output}->add_option_msg(short_msg => "Runas user '" . $self->{runas} . "' not exist."); + $self->{output}->option_exit(); + } + if ($uid != $>) { + if ($> == 0) { + unshift @args, "-s", "/bin/bash", "-l", $self->{runas}, "-c", join(" ", $cmd, "--plugin=" . $self->{plugin}, @ARGV); + $cmd = "su"; + } else { + unshift @args, "-S", "-u", $self->{runas}, $cmd, "--plugin=" . $self->{plugin}, @ARGV; + $cmd = "sudo"; + } + $need_restart = 1; + } + } + + if ($need_restart == 1) { + if (scalar(@args) <= 0) { + unshift @args, @ARGV, "--plugin=" . $self->{plugin} + } + + my ($lerror, $stdout, $exit_code) = centreon::plugins::misc::backtick( + command => $cmd, + arguments => [@args], + timeout => 30, + wait_exit => 1 + ); + if ($exit_code <= -1000) { + if ($exit_code == -1000) { + $self->{output}->output_add(severity => 'UNKNOWN', + short_msg => $stdout); + } + $self->{output}->display(); + $self->{output}->exit(); + } + print $stdout; + # We put unknown + if (!($exit_code >= 0 && $exit_code <= 4)) { + exit 3; + } + exit $exit_code; + } +} + sub run { my $self = shift; @@ -98,6 +166,9 @@ sub run { $self->{output}->add_option_msg(short_msg => "Need to specify '--plugin' option."); $self->{output}->option_exit(); } + + $self->check_relaunch(); + (my $file = $self->{plugin} . ".pm") =~ s{::}{/}g; require $file; my $plugin = $self->{plugin}->new(options => $self->{options}, output => $self->{output}); diff --git a/centreon/lib/perl/plugins/centreon_plugins.pl b/centreon/lib/perl/plugins/centreon_plugins.pl index 6905122ca02..ca946402458 100644 --- a/centreon/lib/perl/plugins/centreon_plugins.pl +++ b/centreon/lib/perl/plugins/centreon_plugins.pl @@ -1,3 +1,4 @@ +#!/usr/bin/perl use strict; use warnings; @@ -31,6 +32,14 @@ =head1 OPTIONS Print a brief help message and exits. +=item B<--runas> + +Run the script as a different user (prefer to use directly the good user). + +=item B<--environment> + +Set environment variables for the script (prefer to set it before running it for better performance). + =back =head1 DESCRIPTION From a13b60e8822cd69b2c6c216a521fd22d48abea77 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sun, 27 Oct 2013 23:19:45 +0100 Subject: [PATCH 114/458] + Add memcached system --- .../lib/perl/centreon/plugins/statefile.pm | 29 +++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/statefile.pm b/centreon/lib/perl/centreon/plugins/statefile.pm index f65747a2fb6..87a0713da50 100644 --- a/centreon/lib/perl/centreon/plugins/statefile.pm +++ b/centreon/lib/perl/centreon/plugins/statefile.pm @@ -20,6 +20,7 @@ sub new { $self->{output} = $options{output}; $self->{datas} = {}; $self->{memcached} = undef; + $self->{statefile_dir} = undef; return $self; @@ -29,7 +30,9 @@ sub check_options { my ($self, %options) = @_; if (defined($options{option_results}) && defined($options{option_results}->{memcached})) { - $self->{memcached} = $options{option_results}->{memcached}; + require Memcached::libmemcached; + $self->{memcached} = Memcached::libmemcached->new(); + Memcached::libmemcached::memcached_server_add($self->{memcached}, $options{option_results}->{memcached}); } $self->{statefile_dir} = $options{option_results}->{statefile_dir}; } @@ -39,9 +42,24 @@ sub read { $self->{statefile_dir} = defined($options{statefile_dir}) ? $options{statefile_dir} : $self->{statefile_dir}; $self->{statefile} = defined($options{statefile}) ? $options{statefile} : $self->{statefile}; + if (defined($self->{memcached})) { + # if "SUCCESS" or "NOT FOUND" is ok. Other with use the file + my $val = Memcached::libmemcached::memcached_get($self->{memcached}, $self->{statefile_dir} . "/" . $self->{statefile}); + if (defined($self->{memcached}->errstr) && $self->{memcached}->errstr =~ /^SUCCESS|NOT FOUND$/i) { + if (defined($val)) { + eval( $val ); + $self->{datas} = $datas; + $datas = {}; + return 1; + } + return 0; + } + $self->{memcached_ok} = 0; + } + if (! -e $self->{statefile_dir} . "/" . $self->{statefile}) { if (! -w $self->{statefile_dir}) { - $self->{output}->add_option_msg(short_msg => "Cannot write statefile '" . $self->{statefile_dir} . "/" . $self->{statefile} . "'. Need write permissions on directory."); + $self->{output}->add_option_msg(short_msg => "Cannot write statefile '" . $self->{statefile_dir} . "/" . $self->{statefile} . "'. Need write permissions on directory."); $self->{output}->option_exit(); } return 0; @@ -88,6 +106,13 @@ sub get { sub write { my ($self, %options) = @_; + if (defined($self->{memcached})) { + Memcached::libmemcached::memcached_set($self->{memcached}, $self->{statefile_dir} . "/" . $self->{statefile}, + Data::Dumper->Dump([$options{data}], ["datas"])); + if (defined($self->{memcached}->errstr) && $self->{memcached}->errstr =~ /^SUCCESS$/i) { + return ; + } + } open FILE, ">", $self->{statefile_dir} . "/" . $self->{statefile}; print FILE Data::Dumper->Dump([$options{data}], ["datas"]); close FILE; From 8bcb465a6075a730ee542aa56aad2f58c5793841 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 28 Oct 2013 10:46:40 +0100 Subject: [PATCH 115/458] + New command uptime --- .../plugins/plugin/{ => os}/linux/snmp.pm | 5 +- .../perl/plugins/plugin/os/windows/snmp.pm | 34 ++++++++ .../perl/plugins/snmp_standard/mode/uptime.pm | 87 +++++++++++++++++++ 3 files changed, 124 insertions(+), 2 deletions(-) rename centreon/lib/perl/plugins/plugin/{ => os}/linux/snmp.pm (86%) create mode 100644 centreon/lib/perl/plugins/plugin/os/windows/snmp.pm create mode 100644 centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm diff --git a/centreon/lib/perl/plugins/plugin/linux/snmp.pm b/centreon/lib/perl/plugins/plugin/os/linux/snmp.pm similarity index 86% rename from centreon/lib/perl/plugins/plugin/linux/snmp.pm rename to centreon/lib/perl/plugins/plugin/os/linux/snmp.pm index 1f19d769c81..eaf6056d86b 100644 --- a/centreon/lib/perl/plugins/plugin/linux/snmp.pm +++ b/centreon/lib/perl/plugins/plugin/os/linux/snmp.pm @@ -1,4 +1,4 @@ -package plugin::linux::snmp; +package plugin::os::linux::snmp; use strict; use warnings; @@ -17,6 +17,7 @@ sub new { 'processcount' => 'snmp_standard::mode::processcount', 'storage' => 'snmp_standard::mode::storage', 'traffic' => 'snmp_standard::mode::traffic', + 'uptime' => 'snmp_standard::mode::uptime', ); #$self->{default} = [{option_mode => 'traffic', option_name => 'warning', option_value => '-1'}]; @@ -29,6 +30,6 @@ __END__ =head1 PLUGIN DESCRIPTION -Check Linux Operating systems in SNMP. +Check Linux operating systems in SNMP. =cut diff --git a/centreon/lib/perl/plugins/plugin/os/windows/snmp.pm b/centreon/lib/perl/plugins/plugin/os/windows/snmp.pm new file mode 100644 index 00000000000..7f5b75e8ea7 --- /dev/null +++ b/centreon/lib/perl/plugins/plugin/os/windows/snmp.pm @@ -0,0 +1,34 @@ +package plugin::os::windows::snmp; + +use strict; +use warnings; +use base qw(centreon::plugins::script_snmp); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '0.1'; + %{$self->{modes}} = ( + 'cpu' => 'snmp_standard::mode::cpu', + 'load' => 'snmp_standard::mode::loadaverage', + 'processcount' => 'snmp_standard::mode::processcount', + 'storage' => 'snmp_standard::mode::storage', + 'traffic' => 'snmp_standard::mode::traffic', + 'uptime' => 'snmp_standard::mode::uptime', + ); + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check Windows operating systems in SNMP. + +=cut diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm b/centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm new file mode 100644 index 00000000000..ece22ec7acd --- /dev/null +++ b/centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm @@ -0,0 +1,87 @@ +package snmp_standard::mode::uptime; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use POSIX; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + "seconds" => { name => 'seconds', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_hrSystemUptime = '.1.3.6.1.2.1.25.1.1.0'; + my $result = $self->{snmp}->get_leef(oids => [ $oid_hrSystemUptime ]); + + my $exit_code = $self->{perfdata}->threshold_check(value => floor($result->{$oid_hrSystemUptime} / 100), + threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->perfdata_add(label => 'uptime', + value => floor($result->{$oid_hrSystemUptime} / 100), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("System uptime is: %s", + defined($self->{option_results}->{seconds}) ? floor($result->{$oid_hrSystemUptime} / 100) . " seconds" : floor($result->{$oid_hrSystemUptime} / 86400 / 100) . " days" )); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check system uptime. + +=over 8 + +=item B<--warning> + +Threshold warning in seconds. + +=item B<--critical> + +Threshold critical in seconds. + +=item B<--seconds> + +Display uptime in seconds. + +=back + +=cut From 11539fd8b48ff29615b5de70fe1f6001b0bc364f Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 28 Oct 2013 16:36:57 +0100 Subject: [PATCH 116/458] + Add beginning on sql works --- centreon/lib/perl/centreon/plugins/dbi.pm | 157 ++++++++++++++ centreon/lib/perl/centreon/plugins/misc.pm | 8 +- centreon/lib/perl/centreon/plugins/mode.pm | 10 +- .../lib/perl/centreon/plugins/script_snmp.pm | 2 +- .../lib/perl/centreon/plugins/script_sql.pm | 204 ++++++++++++++++++ .../database/mysql/mode/connectiontime.pm | 88 ++++++++ .../database/mysql/mode/databasessize.pm | 85 ++++++++ .../perl/plugins/database/mysql/mysqlcmd.pm | 193 +++++++++++++++++ .../lib/perl/plugins/database/mysql/plugin.pm | 60 ++++++ .../{plugin => }/example/mode/getvalue.pm | 0 .../{plugin => }/example/mode/launchcmd.pm | 0 .../command.pm => example/plugin_command.pm} | 4 +- .../snmp.pm => example/plugin_snmp.pm} | 4 +- .../os/linux/snmp.pm => os/linux/plugin.pm} | 4 +- .../windows/snmp.pm => os/windows/plugin.pm} | 2 +- 15 files changed, 809 insertions(+), 12 deletions(-) create mode 100644 centreon/lib/perl/centreon/plugins/dbi.pm create mode 100644 centreon/lib/perl/centreon/plugins/script_sql.pm create mode 100644 centreon/lib/perl/plugins/database/mysql/mode/connectiontime.pm create mode 100644 centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm create mode 100644 centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm create mode 100644 centreon/lib/perl/plugins/database/mysql/plugin.pm rename centreon/lib/perl/plugins/{plugin => }/example/mode/getvalue.pm (100%) rename centreon/lib/perl/plugins/{plugin => }/example/mode/launchcmd.pm (100%) rename centreon/lib/perl/plugins/{plugin/example/command.pm => example/plugin_command.pm} (80%) rename centreon/lib/perl/plugins/{plugin/example/snmp.pm => example/plugin_snmp.pm} (80%) rename centreon/lib/perl/plugins/{plugin/os/linux/snmp.pm => os/linux/plugin.pm} (86%) rename centreon/lib/perl/plugins/{plugin/os/windows/snmp.pm => os/windows/plugin.pm} (96%) diff --git a/centreon/lib/perl/centreon/plugins/dbi.pm b/centreon/lib/perl/centreon/plugins/dbi.pm new file mode 100644 index 00000000000..99a1ecd3a48 --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/dbi.pm @@ -0,0 +1,157 @@ + +package centreon::plugins::dbi; + +use strict; +use warnings; +use DBI; + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + # $options{options} = options object + # $options{output} = output object + # $options{exit_value} = integer + + if (!defined($options{output})) { + print "Class SNMP: Need to specify 'output' argument.\n"; + exit 3; + } + if (!defined($options{options})) { + $options{output}->add_option_msg(short_msg => "Class DBI: Need to specify 'options' argument."); + $options{output}->option_exit(); + } + $options{options}->add_options(arguments => + { "datasource:s" => { name => 'data_source' }, + "username:s" => { name => 'username' }, + "password:s" => { name => 'password' }, + "sql-errors-exit:s" => { name => 'sql-errors-exit', default => 'unknown' }, + }); + $options{options}->add_help(package => __PACKAGE__, sections => 'DBI OPTIONS'); + + $self->{output} = $options{output}; + $self->{mode} = $options{mode}; + $self->{instance} = undef; + $self->{statement_handle} = undef; + $self->{version} = undef; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + # options{default} = { 'mode_name' => { option_name => opt_value } } + + %{$self->{option_results}} = %{$options{option_results}}; + # Manage default value + return if (!defined($options{default})); + foreach (keys %{$options{default}}) { + if ($_ eq $self->{mode}) { + foreach my $value (keys %{$options{default}->{$_}}) { + if (!defined($self->{option_results}->{$value})) { + $self->{option_results}->{$value} = $options{default}->{$_}->{$value}; + } + } + } + } + + if (!defined($self->{option_results}->{data_source}) || $self->{option_results}->{data_source} eq '') { + $self->{output}->add_option_msg(short_msg => "Need to specify database arguments."); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + } +} + +sub quote { + my $self = shift; + + if (defined($self->{instance})) { + return $self->{instance}->quote($_[0]); + } + return undef; +} + +# Connection initializer +sub connect { + my ($self, %options) = @_; + my $dontquit = (defined($options{dontquit}) && $options{dontquit} == 1) ? 1 : 0; + + $self->{instance} = DBI->connect( + "DBI:". $self->{option_results}->{data_source}, + $self->{option_results}->{username}, + $self->{option_results}->{password}, + { "RaiseError" => 0, "PrintError" => 0, "AutoCommit" => 1 } + ); + + if (!defined($self->{instance})) { + if ($dontquit == 0) { + $self->{output}->add_option_msg(short_msg => "Cannot connect: " . $DBI::errstr); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + } + return (-1, "Cannot connect: " . $DBI::errstr); + } + + $self->{version} = $self->{instance}->get_info(18); # SQL_DBMS_VER + return 0; +} + +sub fetchall_arrayref { + my ($self, %options) = @_; + + return $self->{statement_handle}->fetchall_arrayref(); +} + +sub query { + my ($self, %options) = @_; + + $self->{statement_handle} = $self->{instance}->prepare($options{query}); + if (!defined($self->{statement_handle})) { + $self->{output}->add_option_msg(short_msg => "Cannot execute query: " . $self->{instance}->errstr); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + } + + my $rv = $self->{statement_handle}->execute; + if (!$rv) { + $self->{output}->add_option_msg(short_msg => "Cannot execute query: " . $self->{statement_handle}->errstr); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + } +} + +1; + +__END__ + +=head1 NAME + +DBI global + +=head1 SYNOPSIS + +dbi class + +=head1 DBI OPTIONS + +=over 8 + +=item B<--datasource> + +Hostname to query (required). + +=item B<--username> + +Database username. + +=item B<--password> + +Database password. + +=item B<--sql-errors-exit> + +Exit code for DB Errors (default: unknown) + +=back + +=head1 DESCRIPTION + +B. + +=cut diff --git a/centreon/lib/perl/centreon/plugins/misc.pm b/centreon/lib/perl/centreon/plugins/misc.pm index d8735f49133..973504e5060 100644 --- a/centreon/lib/perl/centreon/plugins/misc.pm +++ b/centreon/lib/perl/centreon/plugins/misc.pm @@ -9,6 +9,7 @@ sub backtick { arguments => [], timeout => 30, wait_exit => 0, + redirect_stderr => 0, @_, ); my @output; @@ -23,10 +24,11 @@ sub backtick { $sig_do = 'DEFAULT'; } local $SIG{CHLD} = $sig_do; + if (!defined($pid = open( KID, "-|" ))) { return (-1001, "Cant fork: $!", -1); } - + if ($pid) { eval { @@ -61,6 +63,10 @@ sub backtick { # kill -9 will kill it and all its descendents setpgrp( 0, 0 ); + if ($arg{redirect_stderr} == 1) { + open STDERR, ">&STDOUT"; + } + open STDERR, ">&STDOUT"; if (scalar(@{$arg{arguments}}) <= 0) { exec($arg{command}); } else { diff --git a/centreon/lib/perl/centreon/plugins/mode.pm b/centreon/lib/perl/centreon/plugins/mode.pm index ecb7dd371b8..7e5fe3be918 100644 --- a/centreon/lib/perl/centreon/plugins/mode.pm +++ b/centreon/lib/perl/centreon/plugins/mode.pm @@ -25,9 +25,13 @@ sub init { %{$self->{option_results}} = %{$options{option_results}}; # Manage default value return if (!defined($options{default})); - foreach (@{$options{default}}) { - if (defined($_->{option_mode}) && $_->{option_mode} eq $self->{mode} && !defined($self->{option_results}->{$_->{option_name}})) { - $self->{option_results}->{$_->{option_name}} = $_->{option_value}; + foreach (keys %{$options{default}}) { + if ($_ eq $self->{mode}) { + foreach my $value (keys %{$options{default}->{$_}}) { + if (!defined($self->{option_results}->{$value})) { + $self->{option_results}->{$value} = $options{default}->{$_}->{$value}; + } + } } } } diff --git a/centreon/lib/perl/centreon/plugins/script_snmp.pm b/centreon/lib/perl/centreon/plugins/script_snmp.pm index 553ae916469..2274f2fce51 100644 --- a/centreon/lib/perl/centreon/plugins/script_snmp.pm +++ b/centreon/lib/perl/centreon/plugins/script_snmp.pm @@ -108,7 +108,7 @@ sub is_mode { # $options->{mode} = mode if (!defined($self->{modes}{$options{mode}})) { - $self->{output}->add_option_msg(short_msg => "mode '" . $options{mode} . "' doesn't exist (use --list option to show available modes)."); + $self->{output}->add_option_msg(short_msg => "mode '" . $options{mode} . "' doesn't exist (use --list-mode option to show available modes)."); $self->{output}->option_exit(); } } diff --git a/centreon/lib/perl/centreon/plugins/script_sql.pm b/centreon/lib/perl/centreon/plugins/script_sql.pm new file mode 100644 index 00000000000..f349a39cbcf --- /dev/null +++ b/centreon/lib/perl/centreon/plugins/script_sql.pm @@ -0,0 +1,204 @@ +package centreon::plugins::script_sql; + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + # $options{package} = parent package caller + # $options{options} = options object + # $options{output} = output object + $self->{options} = $options{options}; + $self->{output} = $options{output}; + + $self->{options}->add_options( + arguments => { + 'mode:s' => { name => 'mode_name' }, + 'list-mode' => { name => 'list_mode' }, + 'sqlmode:s' => { name => 'sqlmode_name', default => 'dbi' }, + 'list-sqlmode' => { name => 'list_sqlmode' }, + } + ); + $self->{version} = '1.0'; + %{$self->{modes}} = (); + %{$self->{sql_modes}} = ('dbi' => 'centreon::plugins::dbi'); + $self->{default} = undef; + $self->{sqldefault} = {}; + + $self->{options}->parse_options(); + $self->{option_results} = $self->{options}->get_options(); + foreach (keys %{$self->{option_results}}) { + $self->{$_} = $self->{option_results}->{$_}; + } + $self->{options}->clean(); + + $self->{options}->add_help(package => $options{package}, sections => 'PLUGIN DESCRIPTION'); + $self->{options}->add_help(package => __PACKAGE__, sections => 'GLOBAL OPTIONS'); + + return $self; +} + +sub init { + my ($self, %options) = @_; + # $options{version} = string version + # $options{help} = string help + + if (defined($options{help}) && !defined($self->{mode_name})) { + $self->{options}->display_help(); + $self->{output}->option_exit(); + } + if (defined($options{version}) && !defined($self->{mode_name})) { + $self->version(); + } + if (defined($self->{list_mode})) { + $self->list_mode(); + } + if (defined($self->{list_sqlmode})) { + $self->list_sqlmode(); + } + + if (!defined($self->{mode_name}) || $self->{mode_name} eq '') { + $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' option."); + $self->{output}->option_exit(); + } + $self->is_mode(mode => $self->{mode_name}); + $self->is_sqlmode(sqlmode => $self->{sqlmode_name}); + + # Output HELP + $self->{options}->add_help(package => 'centreon::plugins::output', sections => 'OUTPUT OPTIONS'); + + # Load Sql-Mode + (my $file = $self->{sql_modes}{$self->{sqlmode_name}} . ".pm") =~ s{::}{/}g; + require $file; + $self->{sqlmode} = $self->{sql_modes}{$self->{sqlmode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{sqlmode_name}); + + # Load mode + ($file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; + require $file; + $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + + if (defined($options{help})) { + $self->{options}->add_help(package => $self->{modes}{$self->{mode_name}}, sections => 'MODE'); + $self->{options}->display_help(); + $self->{output}->option_exit(); + } + if (defined($options{version})) { + $self->{mode}->version(); + $self->{output}->option_exit(nolabel => 1); + } + + $self->{options}->parse_options(); + $self->{option_results} = $self->{options}->get_options(); + + $self->{sqlmode}->check_options(option_results => $self->{option_results}, default => $self->{sqldefault}); + $self->{mode}->check_options(option_results => $self->{option_results}, default => $self->{default}); +} + +sub run { + my $self = shift; + + if ($self->{output}->is_disco_format()) { + $self->{mode}->disco_format(); + $self->{output}->display_disco_format(); + $self->{output}->exit(exit_litteral => 'ok'); + } + + if ($self->{output}->is_disco_show()) { + $self->{mode}->disco_show(sql => $self->{sqlmode}); + $self->{output}->display_disco_show(); + $self->{output}->exit(exit_litteral => 'ok'); + } else { + $self->{mode}->run(sql => $self->{sqlmode}); + } +} + +sub is_mode { + my ($self, %options) = @_; + + # $options->{mode} = mode + if (!defined($self->{modes}{$options{mode}})) { + $self->{output}->add_option_msg(short_msg => "mode '" . $options{mode} . "' doesn't exist (use --list-mode option to show available modes)."); + $self->{output}->option_exit(); + } +} + +sub is_sqlmode { + my ($self, %options) = @_; + + # $options->{sqlmode} = mode + if (!defined($self->{sql_modes}{$options{sqlmode}})) { + $self->{output}->add_option_msg(short_msg => "mode '" . $options{sqlmode} . "' doesn't exist (use --list-sqlmode option to show available modes)."); + $self->{output}->option_exit(); + } +} + + +sub version { + my $self = shift; + $self->{output}->add_option_msg(short_msg => "Plugin Version: " . $self->{version}); + $self->{output}->option_exit(nolabel => 1); +} + +sub list_mode { + my $self = shift; + $self->{options}->display_help(); + + $self->{output}->add_option_msg(long_msg => "Modes Available:"); + foreach (keys %{$self->{modes}}) { + $self->{output}->add_option_msg(long_msg => " " . $_); + } + $self->{output}->option_exit(nolabel => 1); +} + +sub list_sqlmode { + my $self = shift; + $self->{options}->display_help(); + + $self->{output}->add_option_msg(long_msg => "SQL Modes Available:"); + foreach (keys %{$self->{sql_modes}}) { + $self->{output}->add_option_msg(long_msg => " " . $_); + } + $self->{output}->option_exit(nolabel => 1); +} + +1; + +__END__ + +=head1 NAME + +- + +=head1 SYNOPSIS + +- + +=head1 GLOBAL OPTIONS + +=over 8 + +=item B<--mode> + +Choose a mode (required). + +=item B<--list-mode> + +List available modes. + +=item B<--sqlmode> + +Choose a sql mode (Default: "dbi"). + +=item B<--list-sqlmode> + +List available sql modes. + +=back + +=head1 DESCRIPTION + +B<>. + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mode/connectiontime.pm b/centreon/lib/perl/plugins/database/mysql/mode/connectiontime.pm new file mode 100644 index 00000000000..2d1c0ebf872 --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mode/connectiontime.pm @@ -0,0 +1,88 @@ +package database::mysql::mode::connectiontime; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use Time::HiRes; +use POSIX; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + my $now = Time::HiRes::time(); + my ($exit, $msg_error) = $self->{sql}->connect(dontquit => 1); + my $now2 = Time::HiRes::time(); + + if ($exit == -1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => $msg_error); + } else { + my $milliseconds = $now2 - $now; + $milliseconds = floor($milliseconds * 1000); + my $exit_code = $self->{perfdata}->threshold_check(value => $milliseconds, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("Connection established in %.3fs.", $milliseconds / 1000)); + $self->{output}->perfdata_add(label => 'connection_time', unit => 'ms', + value => $milliseconds, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check MySQL connection time. + +=over 8 + +=item B<--warning> + +Threshold warning in milliseconds. + +=item B<--critical> + +Threshold critical in milliseconds. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm b/centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm new file mode 100644 index 00000000000..313ff17a2f5 --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm @@ -0,0 +1,85 @@ +package database::mysql::mode::databasessize; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + $self->{sql}->query(query => 'SELECT table_schema AS NAME, SUM(data_length+index_length) + FROM information_schema.tables + GROUP BY table_schema'); + my $result = $self->{sql}->fetchall_arrayref(); + use Data::Dumper; + print Data::Dumper::Dumper($result); + + + # my $exit_code = $self->{perfdata}->threshold_check(value => $milliseconds, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + # $self->{output}->output_add(severity => $exit_code, + # short_msg => sprintf("Connection established in %.3fs.", $milliseconds / 1000)); + # $self->{output}->perfdata_add(label => 'connection_time', unit => 'ms', + # value => $milliseconds, + # warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + # critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + # min => 0); + #} + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check MySQL databases size. + +=over 8 + +=item B<--warning> + +Threshold warning in bytes. + +=item B<--critical> + +Threshold critical in bytes. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm new file mode 100644 index 00000000000..4a5e2496198 --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm @@ -0,0 +1,193 @@ + +package database::mysql::mysqlcmd; + +use strict; +use warnings; +use centreon::plugins::misc; + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + # $options{options} = options object + # $options{output} = output object + # $options{exit_value} = integer + + if (!defined($options{output})) { + print "Class SNMP: Need to specify 'output' argument.\n"; + exit 3; + } + if (!defined($options{options})) { + $options{output}->add_option_msg(short_msg => "Class Mysqlcmd: Need to specify 'options' argument."); + $options{output}->option_exit(); + } + $options{options}->add_options(arguments => + { "mysql-cmd:s" => { name => 'mysql_cmd', default => '/usr/bin/mysql' }, + "host:s" => { name => 'host' }, + "port:s" => { name => 'port' }, + "username:s" => { name => 'username' }, + "password:s" => { name => 'password' }, + "sql-errors-exit:s" => { name => 'sql-errors-exit', default => 'unknown' }, + }); + $options{options}->add_help(package => __PACKAGE__, sections => 'MYSQLCMD OPTIONS'); + + $self->{output} = $options{output}; + $self->{mode} = $options{mode}; + $self->{args} = undef; + $self->{stdout} = undef; + $self->{version} = undef; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + # options{default} = { 'mode_name' => { option_name => opt_value } } + + %{$self->{option_results}} = %{$options{option_results}}; + # Manage default value + return if (!defined($options{default})); + foreach (keys %{$options{default}}) { + if ($_ eq $self->{mode}) { + foreach my $value (keys %{$options{default}->{$_}}) { + if (!defined($self->{option_results}->{$value})) { + $self->{option_results}->{$value} = $options{default}->{$_}->{$value}; + } + } + } + } + + if (!defined($self->{option_results}->{host}) || $self->{option_results}->{host} eq '') { + $self->{output}->add_option_msg(short_msg => "Need to specify host argument."); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + } + + $self->{args} = ['--batch', '--raw', '--skip-column-names', '--host', $self->{option_results}->{host}]; + if (defined($self->{option_results}->{port})) { + push @{$self->{args}}, "--port", $self->{option_results}->{port}; + } + if (defined($self->{option_results}->{username})) { + push @{$self->{args}}, "--user", $self->{option_results}->{username}; + } + if (defined($self->{option_results}->{password}) && $self->{option_results}->{password} ne '') { + push @{$self->{args}}, "-p" . $self->{option_results}->{password}; + } +} + +sub quote { + my $self = shift; + + return undef; +} + +sub command_execution { + my ($self, %options) = @_; + + my ($lerror, $stdout, $exit_code) = centreon::plugins::misc::backtick( + command => $self->{option_results}->{mysql_cmd}, + arguments => [@{$self->{args}}, '-e', $options{request}], + timeout => 30, + wait_exit => 1, + redirect_stderr => 1 + ); + if ($exit_code <= -1000) { + if ($exit_code == -1000) { + $self->{output}->output_add(severity => 'UNKNOWN', + short_msg => $stdout); + } + $self->{output}->display(); + $self->{output}->exit(); + } + + return ($exit_code, $stdout); +} + +# Connection initializer +sub connect { + my ($self, %options) = @_; + my $dontquit = (defined($options{dontquit}) && $options{dontquit} == 1) ? 1 : 0; + + my ($exit_code, $stdout) = $self->command_execution(request => "SHOW VARIABLES LIKE 'version'"); + if ($exit_code != 0) { + if ($dontquit == 0) { + $self->{output}->add_option_msg(short_msg => "Cannot connect: " . $stdout); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + } + return (-1, "Cannot connect: " . $stdout); + } + + (my $name, $self->{version}) = split(/\t/, $stdout); + + return 0; +} + +sub fetchall_arrayref { + my ($self, %options) = @_; + my $array_ref = []; + + foreach (split /\n/, $self->{stdout}) { + push @$array_ref, [map({ s/\\n/\x{0a}/g; s/\\t/\x{09}/g; s/\\/\x{5c}/g; $_; } split(/\t/, $_))]; + } + + return $array_ref; +} + +sub query { + my ($self, %options) = @_; + + (my $exit_code, $self->{stdout}) = $self->command_execution(request => $options{query}); + + if ($exit_code != 0) { + $self->{output}->add_option_msg(short_msg => "Cannot execute query: " . $self->{stdout}); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + } + +} + +1; + +__END__ + +=head1 NAME + +mysqlcmd global + +=head1 SYNOPSIS + +mysqlcmd class + +=head1 MYSQLCMD OPTIONS + +=over 8 + +=item B<--mysql-cmd> + +mysql command (Default: '/usr/bin/mysql'). + +=item B<--host> + +Database hostname. + +=item B<--port> + +Database port. + +=item B<--username> + +Database username. + +=item B<--password> + +Database password. + +=item B<--sql-errors-exit> + +Exit code for DB Errors (default: unknown) + +=back + +=head1 DESCRIPTION + +B. + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/plugin.pm b/centreon/lib/perl/plugins/database/mysql/plugin.pm new file mode 100644 index 00000000000..d5403078070 --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/plugin.pm @@ -0,0 +1,60 @@ +package database::mysql::plugin; + +use strict; +use warnings; +use base qw(centreon::plugins::script_sql); + +sub new { + my ($class, %options) = @_; + $options{options}->add_options( + arguments => { + 'host:s' => { name => 'db_host' }, + 'port:s' => { name => 'db_port' }, + } + ); + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '0.1'; + %{$self->{modes}} = ( + 'connection-time' => 'database::mysql::mode::connectiontime', + 'databases-size' => 'database::mysql::mode::databasessize', + ); + $self->{sql_modes}{mysqlcmd} = 'database::mysql::mysqlcmd'; + + if (defined($self->{db_host}) && $self->{db_host} ne '') { + $self->{sqldefault}->{dbi} = { data_source => 'mysql:host=' . $self->{db_host} }; + $self->{sqldefault}->{mysqlcmd} = { host => $self->{db_host} }; + if (defined($self->{db_port}) && $self->{db_port} ne '') { + $self->{sqldefault}->{dbi}->{data_source} .= ';port=' . $self->{db_port}; + $self->{sqldefault}->{mysqlcmd}->{port} = $self->{db_port}; + } + } + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check MySQL Server. + +=over 8 + +You can use following options or options from 'sqlmode' directly. + +=item B<--host> + +Hostname to query. + +=item B<--port> + +Database Server Port. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/plugin/example/mode/getvalue.pm b/centreon/lib/perl/plugins/example/mode/getvalue.pm similarity index 100% rename from centreon/lib/perl/plugins/plugin/example/mode/getvalue.pm rename to centreon/lib/perl/plugins/example/mode/getvalue.pm diff --git a/centreon/lib/perl/plugins/plugin/example/mode/launchcmd.pm b/centreon/lib/perl/plugins/example/mode/launchcmd.pm similarity index 100% rename from centreon/lib/perl/plugins/plugin/example/mode/launchcmd.pm rename to centreon/lib/perl/plugins/example/mode/launchcmd.pm diff --git a/centreon/lib/perl/plugins/plugin/example/command.pm b/centreon/lib/perl/plugins/example/plugin_command.pm similarity index 80% rename from centreon/lib/perl/plugins/plugin/example/command.pm rename to centreon/lib/perl/plugins/example/plugin_command.pm index 21bb597c5f5..79b5e0668d8 100644 --- a/centreon/lib/perl/plugins/plugin/example/command.pm +++ b/centreon/lib/perl/plugins/example/plugin_command.pm @@ -1,4 +1,4 @@ -package plugin::example::command; +package example::plugin_command; use strict; use warnings; @@ -12,7 +12,7 @@ sub new { $self->{version} = '0.1'; %{$self->{modes}} = ( - 'launchcmd' => 'plugin::example::mode::launchcmd' + 'launchcmd' => 'example::mode::launchcmd' ); return $self; diff --git a/centreon/lib/perl/plugins/plugin/example/snmp.pm b/centreon/lib/perl/plugins/example/plugin_snmp.pm similarity index 80% rename from centreon/lib/perl/plugins/plugin/example/snmp.pm rename to centreon/lib/perl/plugins/example/plugin_snmp.pm index 71273d38f41..ff689ab8233 100644 --- a/centreon/lib/perl/plugins/plugin/example/snmp.pm +++ b/centreon/lib/perl/plugins/example/plugin_snmp.pm @@ -1,4 +1,4 @@ -package plugin::example::snmp; +package example::plugin_snmp; use strict; use warnings; @@ -12,7 +12,7 @@ sub new { $self->{version} = '0.1'; %{$self->{modes}} = ( - 'getvalue' => 'plugin::example::mode::getvalue' + 'getvalue' => 'example::mode::getvalue' ); return $self; diff --git a/centreon/lib/perl/plugins/plugin/os/linux/snmp.pm b/centreon/lib/perl/plugins/os/linux/plugin.pm similarity index 86% rename from centreon/lib/perl/plugins/plugin/os/linux/snmp.pm rename to centreon/lib/perl/plugins/os/linux/plugin.pm index eaf6056d86b..4d22cbf79da 100644 --- a/centreon/lib/perl/plugins/plugin/os/linux/snmp.pm +++ b/centreon/lib/perl/plugins/os/linux/plugin.pm @@ -1,4 +1,4 @@ -package plugin::os::linux::snmp; +package os::linux::plugin; use strict; use warnings; @@ -19,7 +19,7 @@ sub new { 'traffic' => 'snmp_standard::mode::traffic', 'uptime' => 'snmp_standard::mode::uptime', ); - #$self->{default} = [{option_mode => 'traffic', option_name => 'warning', option_value => '-1'}]; + #$self->{default} = { traffic => { warning => '-1'} }; return $self; } diff --git a/centreon/lib/perl/plugins/plugin/os/windows/snmp.pm b/centreon/lib/perl/plugins/os/windows/plugin.pm similarity index 96% rename from centreon/lib/perl/plugins/plugin/os/windows/snmp.pm rename to centreon/lib/perl/plugins/os/windows/plugin.pm index 7f5b75e8ea7..0a28371425e 100644 --- a/centreon/lib/perl/plugins/plugin/os/windows/snmp.pm +++ b/centreon/lib/perl/plugins/os/windows/plugin.pm @@ -1,4 +1,4 @@ -package plugin::os::windows::snmp; +package os::windows::plugin; use strict; use warnings; From 993ae87552936ee52a7b75283dba641b6f40a265 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Mon, 28 Oct 2013 23:38:13 +0100 Subject: [PATCH 117/458] + Add MySQL modes --- centreon/lib/perl/centreon/plugins/dbi.pm | 32 ++++- .../database/mysql/mode/databasessize.pm | 40 ++++-- .../mysql/mode/innodbbufferpoolhitrate.pm | 132 ++++++++++++++++++ .../mode/innodbbufferpoolhitrate_plop.pm | 121 ++++++++++++++++ .../mysql/mode/myisamkeycachehitrate.pm | 132 ++++++++++++++++++ .../plugins/database/mysql/mode/openfiles.pm | 99 +++++++++++++ .../plugins/database/mysql/mode/queries.pm | 122 ++++++++++++++++ .../database/mysql/mode/slowqueries.pm | 118 ++++++++++++++++ .../database/mysql/mode/threadsconnected.pm | 94 +++++++++++++ .../plugins/database/mysql/mode/uptime.pm | 103 ++++++++++++++ .../perl/plugins/database/mysql/mysqlcmd.pm | 40 ++++++ .../lib/perl/plugins/database/mysql/plugin.pm | 7 + 12 files changed, 1028 insertions(+), 12 deletions(-) create mode 100644 centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate.pm create mode 100644 centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate_plop.pm create mode 100644 centreon/lib/perl/plugins/database/mysql/mode/myisamkeycachehitrate.pm create mode 100644 centreon/lib/perl/plugins/database/mysql/mode/openfiles.pm create mode 100644 centreon/lib/perl/plugins/database/mysql/mode/queries.pm create mode 100644 centreon/lib/perl/plugins/database/mysql/mode/slowqueries.pm create mode 100644 centreon/lib/perl/plugins/database/mysql/mode/threadsconnected.pm create mode 100644 centreon/lib/perl/plugins/database/mysql/mode/uptime.pm diff --git a/centreon/lib/perl/centreon/plugins/dbi.pm b/centreon/lib/perl/centreon/plugins/dbi.pm index 99a1ecd3a48..9ce351d80d7 100644 --- a/centreon/lib/perl/centreon/plugins/dbi.pm +++ b/centreon/lib/perl/centreon/plugins/dbi.pm @@ -4,6 +4,7 @@ package centreon::plugins::dbi; use strict; use warnings; use DBI; +use Digest::MD5 qw(md5_hex); sub new { my ($class, %options) = @_; @@ -70,7 +71,24 @@ sub quote { return undef; } -# Connection initializer +sub is_version_minimum { + my ($self, %options) = @_; + # $options{version} = string version to check + + my @version_src = split /\./, $self->{version}; + my @versions = split /\./, $options{version}; + for (my $i = 0; $i < scalar(@versions); $i++) { + return 1 if ($versions[$i] eq 'x'); + return 1 if (!defined($version_src[$i])); + $version_src[$i] =~ /^([0-9]*)/; + next if ($versions[$i] == int($1)); + return 0 if ($versions[$i] > int($1)); + return 1 if ($versions[$i] < int($1)); + } + + return 1; +} + sub connect { my ($self, %options) = @_; my $dontquit = (defined($options{dontquit}) && $options{dontquit} == 1) ? 1 : 0; @@ -94,12 +112,24 @@ sub connect { return 0; } +sub get_unique_id4save { + my ($self, %options) = @_; + + return md5_hex($self->{option_results}->{data_source}); +} + sub fetchall_arrayref { my ($self, %options) = @_; return $self->{statement_handle}->fetchall_arrayref(); } +sub fetchrow_array { + my ($self, %options) = @_; + + return $self->{statement_handle}->fetchrow_array(); +} + sub query { my ($self, %options) = @_; diff --git a/centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm b/centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm index 313ff17a2f5..cb064bceee5 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm @@ -15,6 +15,7 @@ sub new { { "warning:s" => { name => 'warning', }, "critical:s" => { name => 'critical', }, + "filter:s" => { name => 'filter', }, }); return $self; @@ -44,19 +45,32 @@ sub run { FROM information_schema.tables GROUP BY table_schema'); my $result = $self->{sql}->fetchall_arrayref(); - use Data::Dumper; - print Data::Dumper::Dumper($result); + if (!($self->{sql}->is_version_minimum(version => '5'))) { + $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported."); + $self->{output}->option_exit(); + } - # my $exit_code = $self->{perfdata}->threshold_check(value => $milliseconds, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); - # $self->{output}->output_add(severity => $exit_code, - # short_msg => sprintf("Connection established in %.3fs.", $milliseconds / 1000)); - # $self->{output}->perfdata_add(label => 'connection_time', unit => 'ms', - # value => $milliseconds, - # warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), - # critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), - # min => 0); - #} + $self->{output}->output_add(severity => 'OK', + short_msg => "All databases are ok."); + foreach my $row (@$result) { + next if (defined($self->{option_results}->{filter}) && + $$row[0] !~ /$self->{option_results}->{filter}/); + + my $exit_code = $self->{perfdata}->threshold_check(value => $$row[1], threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + + my ($value, $value_unit) = $self->{perfdata}->change_bytes(value => $$row[1]); + $self->{output}->output_add(long_msg => sprintf("DB '" . $$row[0] . "' size: %.3f%s", $value, $value_unit)); + if (!$self->{output}->is_status(value => $exit_code, compare => 'ok', litteral => 1)) { + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("DB '" . $$row[0] . "' size: %.3f%s", $value, $value_unit)); + } + $self->{output}->perfdata_add(label => $$row[0] . '_size', + value => $$row[1], + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + } $self->{output}->display(); $self->{output}->exit(); @@ -80,6 +94,10 @@ Threshold warning in bytes. Threshold critical in bytes. +=item B<--filter> + +Filter database to checks. + =back =cut diff --git a/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate.pm b/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate.pm new file mode 100644 index 00000000000..8606c43376a --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate.pm @@ -0,0 +1,132 @@ +package database::mysql::mode::innodbbufferpoolhitrate; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + "lookback" => { name => 'lookback', }, + }); + $self->{statefile_cache} = centreon::plugins::statefile->new(%options); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } + + $self->{statefile_cache}->check_options(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + if (!($self->{sql}->is_version_minimum(version => '5'))) { + $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported (need version >= '5.x')."); + $self->{output}->option_exit(); + } + + $self->{sql}->query(query => q{SHOW /*!50000 global */ STATUS WHERE Variable_name IN ('Innodb_buffer_pool_read_requests', 'Innodb_buffer_pool_reads')}); + my $new_datas = {Innodb_buffer_pool_read_requests => undef, Innodb_buffer_pool_reads => undef}; + my $result = $self->{sql}->fetchall_arrayref(); + foreach my $row (@{$result}) { + $new_datas->{$$row[0]} = $$row[1]; + } + foreach (keys %$new_datas) { + if (!defined($new_datas->{$_})) { + $self->{output}->add_option_msg(short_msg => "Cannot get '$_' variable."); + $self->{output}->option_exit(); + } + } + + $self->{statefile_cache}->read(statefile => 'mysql_' . $self->{mode} . '_' . $self->{sql}->get_unique_id4save()); + my $old_timestamp = $self->{statefile_cache}->get(name => 'last_timestamp'); + $new_datas->{last_timestamp} = time(); + + my $old_read_request = $self->{statefile_cache}->get(name => 'Innodb_buffer_pool_read_requests'); + my $old_read = $self->{statefile_cache}->get(name => 'Innodb_buffer_pool_reads'); + if (defined($old_read_request) && defined($old_read) && + $new_datas->{Innodb_buffer_pool_read_requests} >= $old_read_request && + $new_datas->{Innodb_buffer_pool_reads} >= $old_read) { + + + my %prcts = (); + my $total_read_requests = $new_datas->{Innodb_buffer_pool_read_requests} - $old_read_request; + my $total_read_disk = $new_datas->{Innodb_buffer_pool_reads} - $old_read; + $prcts{bufferpool_hitrate_now} = ($total_read_requests == 0) ? 100 : ($total_read_requests - $total_read_disk) * 100 / $total_read_requests; + $prcts{bufferpool_hitrate} = ($new_datas->{Innodb_buffer_pool_read_requests} == 0) ? 100 : ($new_datas->{Innodb_buffer_pool_read_requests} - $new_datas->{Innodb_buffer_pool_reads}) * 100 / $new_datas->{Innodb_buffer_pool_read_requests}; + + my $exit_code = $self->{perfdata}->threshold_check(value => $prcts{'bufferpool_hitrate' . ((defined($self->{option_results}->{lookback})) ? '_now' : '' )}, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("innodb buffer pool hitrate at %.2f%%", $prcts{'bufferpool_hitrate' . ((defined($self->{option_results}->{lookback})) ? '' : '_now')}) + ); + $self->{output}->perfdata_add(label => 'bufferpool_hitrate' . ((defined($self->{option_results}->{lookback})) ? '' : '_now'), unit => '%', + value => sprintf("%.2f", $prcts{'bufferpool_hitrate' . ((defined($self->{option_results}->{lookback})) ? '_now' : '')}), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + $self->{output}->perfdata_add(label => 'bufferpool_hitrate' . ((defined($self->{option_results}->{lookback})) ? '_now' : ''), unit => '%', + value => sprintf("%.2f", $prcts{'bufferpool_hitrate' . ((defined($self->{option_results}->{lookback})) ? '_now' : '')}), + min => 0); + } + + $self->{statefile_cache}->write(data => $new_datas); + if (!defined($old_timestamp)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check hitrate in the InnoDB Buffer Pool. + +=over 8 + +=item B<--warning> + +Threshold warning. + +=item B<--critical> + +Threshold critical. + +=item B<--lookback> + +Threshold isn't on the percent calculated from the difference ('bufferpool_hitrate_now'). + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate_plop.pm b/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate_plop.pm new file mode 100644 index 00000000000..55295e998d4 --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate_plop.pm @@ -0,0 +1,121 @@ +package database::mysql::mode::innodbbufferpoolhitrate; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + $self->{statefile_cache} = centreon::plugins::statefile->new(%options); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } + + $self->{statefile_cache}->check_options(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + if (!($self->{sql}->is_version_minimum(version => '5'))) { + $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported (need version >= '5.x')."); + $self->{output}->option_exit(); + } + + $self->{sql}->query(query => q{SHOW /*!50000 global */ STATUS WHERE Variable_name IN ('Innodb_buffer_pool_read_requests', 'Innodb_buffer_pool_reads')}); + my $new_datas = {Innodb_buffer_pool_read_requests => undef, Innodb_buffer_pool_reads => undef}; + my $result = $self->{sql}->fetchall_arrayref(); + foreach my $row (@{$result}) { + $new_datas->{$$row[0]} = $$row[1]; + } + foreach (keys %$new_datas) { + if (!defined($new_datas->{$_})) { + $self->{output}->add_option_msg(short_msg => "Cannot get '$_' variable."); + $self->{output}->option_exit(); + } + } + + $self->{statefile_cache}->read(statefile => 'mysql_' . $self->{mode} . '_' . $self->{sql}->get_unique_id4save()); + my $old_timestamp = $self->{statefile_cache}->get(name => 'last_timestamp'); + $new_datas->{last_timestamp} = time(); + + my $old_read_request = $self->{statefile_cache}->get(name => 'Innodb_buffer_pool_read_requests'); + my $old_read = $self->{statefile_cache}->get(name => 'Innodb_buffer_pool_reads'); + if (defined($old_read_request) && defined($old_read) && + $new_datas->{Innodb_buffer_pool_read_requests} >= $old_read_request && + $new_datas->{Innodb_buffer_pool_reads} >= $old_read) { + + my $total_read_requests = $new_datas->{Innodb_buffer_pool_read_requests} - $old_read_request; + my $total_read_disk = $new_datas->{Innodb_buffer_pool_reads} - $old_read; + my $prct_hitrate = ($total_read_requests == 0) ? 100 : ($total_read_requests - $total_read_disk) * 100 / $total_read_requests; + + my $exit_code = $self->{perfdata}->threshold_check(value => $prct_hitrate, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("innodb buffer pool hitrate at %.2f%%", $prct_hitrate) + ); + $self->{output}->perfdata_add(label => 'bufferpool_hitrate', unit => '%', + value => sprintf("%.2f", $prct_hitrate), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + } + + $self->{statefile_cache}->write(data => $new_datas); + if (!defined($old_timestamp)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check hitrate in the InnoDB Buffer Pool. + +=over 8 + +=item B<--warning> + +Threshold warning. + +=item B<--critical> + +Threshold critical. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mode/myisamkeycachehitrate.pm b/centreon/lib/perl/plugins/database/mysql/mode/myisamkeycachehitrate.pm new file mode 100644 index 00000000000..1fd0c262055 --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mode/myisamkeycachehitrate.pm @@ -0,0 +1,132 @@ +package database::mysql::mode::myisamkeycachehitrate; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + "lookback" => { name => 'lookback', }, + }); + $self->{statefile_cache} = centreon::plugins::statefile->new(%options); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } + + $self->{statefile_cache}->check_options(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + if (!($self->{sql}->is_version_minimum(version => '5'))) { + $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported (need version >= '5.x')."); + $self->{output}->option_exit(); + } + + $self->{sql}->query(query => q{SHOW /*!50000 global */ STATUS WHERE Variable_name IN ('Key_read_requests', 'Key_reads')}); + my $new_datas = {Key_read_requests => undef, Key_reads => undef}; + my $result = $self->{sql}->fetchall_arrayref(); + foreach my $row (@{$result}) { + $new_datas->{$$row[0]} = $$row[1]; + } + foreach (keys %$new_datas) { + if (!defined($new_datas->{$_})) { + $self->{output}->add_option_msg(short_msg => "Cannot get '$_' variable."); + $self->{output}->option_exit(); + } + } + + $self->{statefile_cache}->read(statefile => 'mysql_' . $self->{mode} . '_' . $self->{sql}->get_unique_id4save()); + my $old_timestamp = $self->{statefile_cache}->get(name => 'last_timestamp'); + $new_datas->{last_timestamp} = time(); + + my $old_read_request = $self->{statefile_cache}->get(name => 'Key_read_requests'); + my $old_read = $self->{statefile_cache}->get(name => 'Key_reads'); + if (defined($old_read_request) && defined($old_read) && + $new_datas->{Key_read_requests} >= $old_read_request && + $new_datas->{Key_reads} >= $old_read) { + + + my %prcts = (); + my $total_read_requests = $new_datas->{Key_read_requests} - $old_read_request; + my $total_read_disk = $new_datas->{Key_reads} - $old_read; + $prcts{keycache_hitrate_now} = ($total_read_requests == 0) ? 100 : ($total_read_requests - $total_read_disk) * 100 / $total_read_requests; + $prcts{keycache_hitrate} = ($new_datas->{Key_read_requests} == 0) ? 100 : ($new_datas->{Key_read_requests} - $new_datas->{Key_reads}) * 100 / $new_datas->{Key_read_requests}; + + my $exit_code = $self->{perfdata}->threshold_check(value => $prcts{'keycache_hitrate' . ((defined($self->{option_results}->{lookback})) ? '_now' : '' )}, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("myisam keycache hitrate at %.2f%%", $prcts{'keycache_hitrate' . ((defined($self->{option_results}->{lookback})) ? '' : '_now')}) + ); + $self->{output}->perfdata_add(label => 'keycache_hitrate' . ((defined($self->{option_results}->{lookback})) ? '' : '_now'), unit => '%', + value => sprintf("%.2f", $prcts{'keycache_hitrate' . ((defined($self->{option_results}->{lookback})) ? '_now' : '')}), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + $self->{output}->perfdata_add(label => 'keycache_hitrate' . ((defined($self->{option_results}->{lookback})) ? '_now' : ''), unit => '%', + value => sprintf("%.2f", $prcts{'keycache_hitrate' . ((defined($self->{option_results}->{lookback})) ? '_now' : '')}), + min => 0); + } + + $self->{statefile_cache}->write(data => $new_datas); + if (!defined($old_timestamp)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check hitrate in the Myisam Key Cache. + +=over 8 + +=item B<--warning> + +Threshold warning. + +=item B<--critical> + +Threshold critical. + +=item B<--lookback> + +Threshold isn't on the percent calculated from the difference ('keycache_hitrate_now'). + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mode/openfiles.pm b/centreon/lib/perl/plugins/database/mysql/mode/openfiles.pm new file mode 100644 index 00000000000..e42d6f0da5a --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mode/openfiles.pm @@ -0,0 +1,99 @@ +package database::mysql::mode::openfiles; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } + +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + if (!($self->{sql}->is_version_minimum(version => '5'))) { + $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported (need version >= '5.x')."); + $self->{output}->option_exit(); + } + + $self->{sql}->query(query => q{SHOW VARIABLES LIKE 'open_files_limit'}); + my ($dummy, $open_files_limit) = $self->{sql}->fetchrow_array(); + if (!defined($open_files_limit)) { + $self->{output}->add_option_msg(short_msg => "Cannot get ope files limit."); + $self->{output}->option_exit(); + } + $self->{sql}->query(query => q{SHOW /*!50000 global */ STATUS LIKE 'Open_files'}); + ($dummy, my $open_files) = $self->{sql}->fetchrow_array(); + if (!defined($open_files)) { + $self->{output}->add_option_msg(short_msg => "Cannot get open files."); + $self->{output}->option_exit(); + } + + my $prct_open = int(100 * $open_files / $open_files_limit); + my $exit_code = $self->{perfdata}->threshold_check(value => $prct_open, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("%.2f%% of the open files limit reached (%d of max. %d)", + $prct_open, $open_files, $open_files_limit)); + $self->{output}->perfdata_add(label => 'open_files', + value => $open_files, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $open_files_limit, cast_int => 1), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $open_files_limit, cast_int => 1), + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check number of open files. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mode/queries.pm b/centreon/lib/perl/plugins/database/mysql/mode/queries.pm new file mode 100644 index 00000000000..fb409cbb766 --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mode/queries.pm @@ -0,0 +1,122 @@ +package database::mysql::mode::queries; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + $self->{statefile_cache} = centreon::plugins::statefile->new(%options); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } + + $self->{statefile_cache}->check_options(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + $self->{sql}->query(query => q{ + SHOW /*!50000 global */ STATUS WHERE Variable_name IN ('Queries', 'Com_update', 'Com_delete', 'Com_insert', 'Com_truncate', 'Com_select') + }); + my $result = $self->{sql}->fetchall_arrayref(); + + if (!($self->{sql}->is_version_minimum(version => '5.0.76'))) { + $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported (need version >= '5.0.76')."); + $self->{output}->option_exit(); + } + + my $new_datas = {}; + $self->{statefile_cache}->read(statefile => 'mysql_' . $self->{mode} . '_' . $self->{sql}->get_unique_id4save()); + my $old_timestamp = $self->{statefile_cache}->get(name => 'last_timestamp'); + $new_datas->{last_timestamp} = time(); + + if (defined($old_timestamp) && $new_datas->{last_timestamp} - $old_timestamp == 0) { + $self->{output}->add_option_msg(short_msg => "Need at least one second between two checks."); + $self->{output}->option_exit(); + } + + foreach my $row (@{$result}) { + next if ($$row[0] !~ /^(Queries|Com_update|Com_delete|Com_insert|Com_truncate|Com_select)/i); + + $new_datas->{$$row[0]} = $$row[1]; + my $old_val = $self->{statefile_cache}->get(name => $$row[0]); + next if (!defined($old_val) || $$row[1] < $old_val); + + my $value = int(($$row[1] - $old_val) / ($new_datas->{last_timestamp} - $old_timestamp)); + if ($$row[0] ne 'Queries') { + $self->{output}->perfdata_add(label => $$row[0] . '_requests', + value => $value, + min => 0); + next; + } + + my $exit_code = $self->{perfdata}->threshold_check(value => $value, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("Total requests = %d.", $value)); + $self->{output}->perfdata_add(label => 'total_requests', + value => $value, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + } + + $self->{statefile_cache}->write(data => $new_datas); + if (!defined($old_timestamp)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check average number of queries executed. + +=over 8 + +=item B<--warning> + +Threshold warning in bytes. + +=item B<--critical> + +Threshold critical in bytes. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mode/slowqueries.pm b/centreon/lib/perl/plugins/database/mysql/mode/slowqueries.pm new file mode 100644 index 00000000000..51e77e0e6a5 --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mode/slowqueries.pm @@ -0,0 +1,118 @@ +package database::mysql::mode::slowqueries; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + $self->{statefile_cache} = centreon::plugins::statefile->new(%options); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } + + $self->{statefile_cache}->check_options(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + if (!($self->{sql}->is_version_minimum(version => '5'))) { + $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported (need version >= '5.x')."); + $self->{output}->option_exit(); + } + + $self->{sql}->query(query => q{SHOW /*!50000 global */ STATUS LIKE 'Slow_queries'}); + my ($name, $result) = $self->{sql}->fetchrow_array(); + if (!defined($result)) { + $self->{output}->add_option_msg(short_msg => "Cannot get slow queries."); + $self->{output}->option_exit(); + } + + + my $new_datas = {}; + $self->{statefile_cache}->read(statefile => 'mysql_' . $self->{mode} . '_' . $self->{sql}->get_unique_id4save()); + my $old_timestamp = $self->{statefile_cache}->get(name => 'last_timestamp'); + $new_datas->{last_timestamp} = time(); + + if (defined($old_timestamp) && $new_datas->{last_timestamp} - $old_timestamp == 0) { + $self->{output}->add_option_msg(short_msg => "Need at least one second between two checks."); + $self->{output}->option_exit(); + } + + $new_datas->{$name} = $result; + my $old_val = $self->{statefile_cache}->get(name => $name); + if (defined($old_val) && $result >= $old_val) { + my $value = sprintf("%.2f", ($result - $old_val) / ($new_datas->{last_timestamp} - $old_timestamp)); + + my $exit_code = $self->{perfdata}->threshold_check(value => $value, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("%d slow queries in %d seconds (%.2f/sec)", + ($result - $old_val), ($new_datas->{last_timestamp} - $old_timestamp), $value) + ); + $self->{output}->perfdata_add(label => 'slow_queries_rate', + value => $value, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + } + + $self->{statefile_cache}->write(data => $new_datas); + if (!defined($old_timestamp)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check average number of queries detected as "slow" (per seconds). + +=over 8 + +=item B<--warning> + +Threshold warning in queries per seconds. + +=item B<--critical> + +Threshold critical in queries per seconds. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mode/threadsconnected.pm b/centreon/lib/perl/plugins/database/mysql/mode/threadsconnected.pm new file mode 100644 index 00000000000..982ddb9f137 --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mode/threadsconnected.pm @@ -0,0 +1,94 @@ +package database::mysql::mode::threadsconnected; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } + +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + if (!($self->{sql}->is_version_minimum(version => '5'))) { + $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported (need version >= '5.x')."); + $self->{output}->option_exit(); + } + + $self->{sql}->query(query => q{SHOW /*!50000 global */ STATUS LIKE 'Threads_connected'}); + my ($dummy, $result) = $self->{sql}->fetchrow_array(); + if (!defined($result)) { + $self->{output}->add_option_msg(short_msg => "Cannot get number of open connections."); + $self->{output}->option_exit(); + } + + + my $value = $result; + + my $exit_code = $self->{perfdata}->threshold_check(value => $value, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("%d client connection threads", $value) + ); + $self->{output}->perfdata_add(label => 'threads_connected', + value => $value, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check number of open connections. + +=over 8 + +=item B<--warning> + +Threshold warning. + +=item B<--critical> + +Threshold critical. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mode/uptime.pm b/centreon/lib/perl/plugins/database/mysql/mode/uptime.pm new file mode 100644 index 00000000000..bddc762c136 --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mode/uptime.pm @@ -0,0 +1,103 @@ +package database::mysql::mode::uptime; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use POSIX; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + "seconds" => { name => 'seconds', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } + +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + if (!($self->{sql}->is_version_minimum(version => '5'))) { + $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported (need version >= '5.x')."); + $self->{output}->option_exit(); + } + + $self->{sql}->query(query => q{SHOW /*!50000 global */ STATUS LIKE 'Uptime'}); + my ($dummy, $result) = $self->{sql}->fetchrow_array(); + if (!defined($result)) { + $self->{output}->add_option_msg(short_msg => "Cannot get uptime."); + $self->{output}->option_exit(); + } + + my $value = $result; + + my $exit_code = $self->{perfdata}->threshold_check(value => $value, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my $msg = sprintf("database is up since %d days", floor($value / 86400)); + if (defined($self->{option_results}->{seconds})) { + $msg = sprintf("database is up since %d seconds", $value); + } + + $self->{output}->output_add(severity => $exit_code, + short_msg => $msg); + $self->{output}->perfdata_add(label => 'uptime', unit => 's', + value => $value, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check MySQL uptime. + +=over 8 + +=item B<--warning> + +Threshold warning. + +=item B<--critical> + +Threshold critical. + +=item B<--seconds> + +Display uptime in seconds. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm index 4a5e2496198..a3a5b39ca5f 100644 --- a/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm +++ b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm @@ -4,6 +4,7 @@ package database::mysql::mysqlcmd; use strict; use warnings; use centreon::plugins::misc; +use Digest::MD5 qw(md5_hex); sub new { my ($class, %options) = @_; @@ -74,6 +75,34 @@ sub check_options { } } +sub is_version_minimum { + my ($self, %options) = @_; + # $options{version} = string version to check + + my @version_src = split /\./, $self->{version}; + my @versions = split /\./, $options{version}; + for (my $i = 0; $i < scalar(@versions); $i++) { + return 1 if ($versions[$i] eq 'x'); + return 1 if (!defined($version_src[$i])); + $version_src[$i] =~ /^([0-9]*)/; + next if ($versions[$i] == int($1)); + return 0 if ($versions[$i] > int($1)); + return 1 if ($versions[$i] < int($1)); + } + + return 1; +} + +sub get_unique_id4save { + my ($self, %options) = @_; + + my $msg = $self->{option_results}->{host}; + if (defined($self->{option_results}->{port})) { + $msg .= ":" . $self->{option_results}->{port}; + } + return md5_hex($msg); +} + sub quote { my $self = shift; @@ -132,6 +161,17 @@ sub fetchall_arrayref { return $array_ref; } +sub fetchrow_array { + my ($self, %options) = @_; + my @array_result = (); + + if (($self->{stdout} =~ s/^(.*?)(\n|$)//)) { + push @array_result, map({ s/\\n/\x{0a}/g; s/\\t/\x{09}/g; s/\\/\x{5c}/g; $_; } split(/\t/, $1)); + } + + return @array_result; +} + sub query { my ($self, %options) = @_; diff --git a/centreon/lib/perl/plugins/database/mysql/plugin.pm b/centreon/lib/perl/plugins/database/mysql/plugin.pm index d5403078070..3502d65d9b1 100644 --- a/centreon/lib/perl/plugins/database/mysql/plugin.pm +++ b/centreon/lib/perl/plugins/database/mysql/plugin.pm @@ -20,6 +20,13 @@ sub new { %{$self->{modes}} = ( 'connection-time' => 'database::mysql::mode::connectiontime', 'databases-size' => 'database::mysql::mode::databasessize', + 'queries' => 'database::mysql::mode::queries', + 'slow-queries' => 'database::mysql::mode::slowqueries', + 'threads-connected' => 'database::mysql::mode::threadsconnected', + 'uptime' => 'database::mysql::mode::uptime', + 'open-files' => 'database::mysql::mode::openfiles', + 'innodb-bufferpool-hitrate' => 'database::mysql::mode::innodbbufferpoolhitrate', + 'myisam-keycache-hitrate' => 'database::mysql::mode::myisamkeycachehitrate', ); $self->{sql_modes}{mysqlcmd} = 'database::mysql::mysqlcmd'; From c3c339d8042898047fc97739cec20f8ddc5c273c Mon Sep 17 00:00:00 2001 From: qgarnier Date: Mon, 28 Oct 2013 23:41:11 +0100 Subject: [PATCH 118/458] + Delete wrong file --- .../mode/innodbbufferpoolhitrate_plop.pm | 121 ------------------ 1 file changed, 121 deletions(-) delete mode 100644 centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate_plop.pm diff --git a/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate_plop.pm b/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate_plop.pm deleted file mode 100644 index 55295e998d4..00000000000 --- a/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate_plop.pm +++ /dev/null @@ -1,121 +0,0 @@ -package database::mysql::mode::innodbbufferpoolhitrate; - -use base qw(centreon::plugins::mode); - -use strict; -use warnings; -use centreon::plugins::statefile; - -sub new { - my ($class, %options) = @_; - my $self = $class->SUPER::new(package => __PACKAGE__, %options); - bless $self, $class; - - $self->{version} = '1.0'; - $options{options}->add_options(arguments => - { - "warning:s" => { name => 'warning', }, - "critical:s" => { name => 'critical', }, - }); - $self->{statefile_cache} = centreon::plugins::statefile->new(%options); - - return $self; -} - -sub check_options { - my ($self, %options) = @_; - $self->SUPER::init(%options); - - if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { - $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); - $self->{output}->option_exit(); - } - if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { - $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); - $self->{output}->option_exit(); - } - - $self->{statefile_cache}->check_options(%options); -} - -sub run { - my ($self, %options) = @_; - # $options{sql} = sqlmode object - $self->{sql} = $options{sql}; - - $self->{sql}->connect(); - - if (!($self->{sql}->is_version_minimum(version => '5'))) { - $self->{output}->add_option_msg(short_msg => "MySQL version '" . $self->{sql}->{version} . "' is not supported (need version >= '5.x')."); - $self->{output}->option_exit(); - } - - $self->{sql}->query(query => q{SHOW /*!50000 global */ STATUS WHERE Variable_name IN ('Innodb_buffer_pool_read_requests', 'Innodb_buffer_pool_reads')}); - my $new_datas = {Innodb_buffer_pool_read_requests => undef, Innodb_buffer_pool_reads => undef}; - my $result = $self->{sql}->fetchall_arrayref(); - foreach my $row (@{$result}) { - $new_datas->{$$row[0]} = $$row[1]; - } - foreach (keys %$new_datas) { - if (!defined($new_datas->{$_})) { - $self->{output}->add_option_msg(short_msg => "Cannot get '$_' variable."); - $self->{output}->option_exit(); - } - } - - $self->{statefile_cache}->read(statefile => 'mysql_' . $self->{mode} . '_' . $self->{sql}->get_unique_id4save()); - my $old_timestamp = $self->{statefile_cache}->get(name => 'last_timestamp'); - $new_datas->{last_timestamp} = time(); - - my $old_read_request = $self->{statefile_cache}->get(name => 'Innodb_buffer_pool_read_requests'); - my $old_read = $self->{statefile_cache}->get(name => 'Innodb_buffer_pool_reads'); - if (defined($old_read_request) && defined($old_read) && - $new_datas->{Innodb_buffer_pool_read_requests} >= $old_read_request && - $new_datas->{Innodb_buffer_pool_reads} >= $old_read) { - - my $total_read_requests = $new_datas->{Innodb_buffer_pool_read_requests} - $old_read_request; - my $total_read_disk = $new_datas->{Innodb_buffer_pool_reads} - $old_read; - my $prct_hitrate = ($total_read_requests == 0) ? 100 : ($total_read_requests - $total_read_disk) * 100 / $total_read_requests; - - my $exit_code = $self->{perfdata}->threshold_check(value => $prct_hitrate, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); - $self->{output}->output_add(severity => $exit_code, - short_msg => sprintf("innodb buffer pool hitrate at %.2f%%", $prct_hitrate) - ); - $self->{output}->perfdata_add(label => 'bufferpool_hitrate', unit => '%', - value => sprintf("%.2f", $prct_hitrate), - warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), - critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), - min => 0); - } - - $self->{statefile_cache}->write(data => $new_datas); - if (!defined($old_timestamp)) { - $self->{output}->output_add(severity => 'OK', - short_msg => "Buffer creation..."); - } - - $self->{output}->display(); - $self->{output}->exit(); -} - -1; - -__END__ - -=head1 MODE - -Check hitrate in the InnoDB Buffer Pool. - -=over 8 - -=item B<--warning> - -Threshold warning. - -=item B<--critical> - -Threshold critical. - -=back - -=cut From d7b0d9936b6b87dcc7e6e6cf5a9978c3f2fdbbce Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 29 Oct 2013 14:55:37 +0100 Subject: [PATCH 119/458] + Manage multiples connections --- centreon/lib/perl/centreon/plugins/dbi.pm | 83 +++++++++++----- .../lib/perl/centreon/plugins/script_sql.pm | 40 ++++++-- .../perl/plugins/database/mysql/mysqlcmd.pm | 99 +++++++++++++------ .../lib/perl/plugins/database/mysql/plugin.pm | 41 +++++--- 4 files changed, 185 insertions(+), 78 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/dbi.pm b/centreon/lib/perl/centreon/plugins/dbi.pm index 9ce351d80d7..84bbbbce7bb 100644 --- a/centreon/lib/perl/centreon/plugins/dbi.pm +++ b/centreon/lib/perl/centreon/plugins/dbi.pm @@ -13,22 +13,26 @@ sub new { # $options{options} = options object # $options{output} = output object # $options{exit_value} = integer - + # $options{noptions} = integer + if (!defined($options{output})) { - print "Class SNMP: Need to specify 'output' argument.\n"; + print "Class DBI: Need to specify 'output' argument.\n"; exit 3; } if (!defined($options{options})) { $options{output}->add_option_msg(short_msg => "Class DBI: Need to specify 'options' argument."); $options{output}->option_exit(); } - $options{options}->add_options(arguments => - { "datasource:s" => { name => 'data_source' }, - "username:s" => { name => 'username' }, - "password:s" => { name => 'password' }, - "sql-errors-exit:s" => { name => 'sql-errors-exit', default => 'unknown' }, - }); - $options{options}->add_help(package => __PACKAGE__, sections => 'DBI OPTIONS'); + + if (!defined($options{noptions})) { + $options{options}->add_options(arguments => + { "datasource:s@" => { name => 'data_source' }, + "username:s@" => { name => 'username' }, + "password:s@" => { name => 'password' }, + "sql-errors-exit:s" => { name => 'sql_errors_exit', default => 'unknown' }, + }); + } + $options{options}->add_help(package => __PACKAGE__, sections => 'DBI OPTIONS', once => 1); $self->{output} = $options{output}; $self->{mode} = $options{mode}; @@ -36,30 +40,59 @@ sub new { $self->{statement_handle} = undef; $self->{version} = undef; + $self->{data_source} = undef; + $self->{username} = undef; + $self->{password} = undef; + return $self; } -sub check_options { +# Method to manage multiples +sub set_options { my ($self, %options) = @_; - # options{default} = { 'mode_name' => { option_name => opt_value } } + # options{options_result} + + $self->{option_results} = $options{option_results}; +} - %{$self->{option_results}} = %{$options{option_results}}; +# Method to manage multiples +sub set_defaults { + my ($self, %options) = @_; + # options{default} + # Manage default value - return if (!defined($options{default})); foreach (keys %{$options{default}}) { if ($_ eq $self->{mode}) { - foreach my $value (keys %{$options{default}->{$_}}) { - if (!defined($self->{option_results}->{$value})) { - $self->{option_results}->{$value} = $options{default}->{$_}->{$value}; + for (my $i = 0; $i < scalar(@{$options{default}->{$_}}); $i++) { + foreach my $opt (keys %{$options{default}->{$_}[$i]}) { + if (!defined($self->{option_results}->{$opt}[$i])) { + $self->{option_results}->{$opt}[$i] = $options{default}->{$_}[$i]->{$opt}; + } } } } } +} - if (!defined($self->{option_results}->{data_source}) || $self->{option_results}->{data_source} eq '') { +sub check_options { + my ($self, %options) = @_; + # return 1 = ok still data_source + # return 0 = no data_source left + + $self->{data_source} = (defined($self->{option_results}->{data_source})) ? shift(@{$self->{option_results}->{data_source}}) : undef; + $self->{username} = (defined($self->{option_results}->{username})) ? shift(@{$self->{option_results}->{username}}) : undef; + $self->{password} = (defined($self->{option_results}->{password})) ? shift(@{$self->{option_results}->{password}}) : undef; + $self->{sql_errors_exit} = $self->{option_results}->{sql_errors_exit}; + + if (!defined($self->{data_source}) || $self->{data_source} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify database arguments."); - $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); + } + + if (scalar(@{$self->{option_results}->{data_source}}) == 0) { + return 0; } + return 1; } sub quote { @@ -94,16 +127,16 @@ sub connect { my $dontquit = (defined($options{dontquit}) && $options{dontquit} == 1) ? 1 : 0; $self->{instance} = DBI->connect( - "DBI:". $self->{option_results}->{data_source}, - $self->{option_results}->{username}, - $self->{option_results}->{password}, + "DBI:". $self->{data_source}, + $self->{username}, + $self->{password}, { "RaiseError" => 0, "PrintError" => 0, "AutoCommit" => 1 } ); if (!defined($self->{instance})) { if ($dontquit == 0) { $self->{output}->add_option_msg(short_msg => "Cannot connect: " . $DBI::errstr); - $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); } return (-1, "Cannot connect: " . $DBI::errstr); } @@ -115,7 +148,7 @@ sub connect { sub get_unique_id4save { my ($self, %options) = @_; - return md5_hex($self->{option_results}->{data_source}); + return md5_hex($self->{data_source}); } sub fetchall_arrayref { @@ -136,13 +169,13 @@ sub query { $self->{statement_handle} = $self->{instance}->prepare($options{query}); if (!defined($self->{statement_handle})) { $self->{output}->add_option_msg(short_msg => "Cannot execute query: " . $self->{instance}->errstr); - $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); } my $rv = $self->{statement_handle}->execute; if (!$rv) { $self->{output}->add_option_msg(short_msg => "Cannot execute query: " . $self->{statement_handle}->errstr); - $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); } } diff --git a/centreon/lib/perl/centreon/plugins/script_sql.pm b/centreon/lib/perl/centreon/plugins/script_sql.pm index f349a39cbcf..8e4137f0ac2 100644 --- a/centreon/lib/perl/centreon/plugins/script_sql.pm +++ b/centreon/lib/perl/centreon/plugins/script_sql.pm @@ -15,10 +15,11 @@ sub new { $self->{options}->add_options( arguments => { - 'mode:s' => { name => 'mode_name' }, - 'list-mode' => { name => 'list_mode' }, - 'sqlmode:s' => { name => 'sqlmode_name', default => 'dbi' }, + 'mode:s' => { name => 'mode_name' }, + 'list-mode' => { name => 'list_mode' }, + 'sqlmode:s' => { name => 'sqlmode_name', default => 'dbi' }, 'list-sqlmode' => { name => 'list_sqlmode' }, + 'multiple' => { name => 'multiple' }, } ); $self->{version} = '1.0'; @@ -26,11 +27,13 @@ sub new { %{$self->{sql_modes}} = ('dbi' => 'centreon::plugins::dbi'); $self->{default} = undef; $self->{sqldefault} = {}; + $self->{sqlmode_current} = undef; + $self->{sqlmode_stored} = []; $self->{options}->parse_options(); $self->{option_results} = $self->{options}->get_options(); foreach (keys %{$self->{option_results}}) { - $self->{$_} = $self->{option_results}->{$_}; + $self->{$_} = $self->{option_results}->{$_}; } $self->{options}->clean(); @@ -72,7 +75,8 @@ sub init { # Load Sql-Mode (my $file = $self->{sql_modes}{$self->{sqlmode_name}} . ".pm") =~ s{::}{/}g; require $file; - $self->{sqlmode} = $self->{sql_modes}{$self->{sqlmode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{sqlmode_name}); + + $self->{sqlmode_current} = $self->{sql_modes}{$self->{sqlmode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{sqlmode_name}); # Load mode ($file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; @@ -92,7 +96,15 @@ sub init { $self->{options}->parse_options(); $self->{option_results} = $self->{options}->get_options(); - $self->{sqlmode}->check_options(option_results => $self->{option_results}, default => $self->{sqldefault}); + push @{$self->{sqlmode_stored}}, $self->{sqlmode_current}; + $self->{sqlmode_current}->set_options(option_results => $self->{option_results}); + $self->{sqlmode_current}->set_defaults(default => $self->{sqldefault}); + + while ($self->{sqlmode_current}->check_options()) { + $self->{sqlmode_current} = $self->{sql_modes}{$self->{sqlmode_name}}->new(noptions => 1, options => $self->{options}, output => $self->{output}, mode => $self->{sqlmode_name}); + $self->{sqlmode_current}->set_options(option_results => $self->{option_results}); + push @{$self->{sqlmode_stored}}, $self->{sqlmode_current}; + } $self->{mode}->check_options(option_results => $self->{option_results}, default => $self->{default}); } @@ -106,11 +118,19 @@ sub run { } if ($self->{output}->is_disco_show()) { - $self->{mode}->disco_show(sql => $self->{sqlmode}); + if (defined($self->{multiple})) { + $self->{mode}->disco_show(sql => $self->{sqlmode}); + } else { + $self->{mode}->disco_show(sql => $self->{sqlmode_stored}[0]); + } $self->{output}->display_disco_show(); $self->{output}->exit(exit_litteral => 'ok'); } else { - $self->{mode}->run(sql => $self->{sqlmode}); + if (defined($self->{multiple})) { + $self->{mode}->run(sql => $self->{sqlmode_stored}); + } else { + $self->{mode}->run(sql => $self->{sqlmode_stored}[0]); + } } } @@ -195,6 +215,10 @@ Choose a sql mode (Default: "dbi"). List available sql modes. +=item B<--multiple> + +Multiple database connections (some mode needs it). + =back =head1 DESCRIPTION diff --git a/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm index a3a5b39ca5f..963d60b068a 100644 --- a/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm +++ b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm @@ -13,24 +13,27 @@ sub new { # $options{options} = options object # $options{output} = output object # $options{exit_value} = integer + # $options{noptions} = integer if (!defined($options{output})) { - print "Class SNMP: Need to specify 'output' argument.\n"; + print "Class mysqlcmd: Need to specify 'output' argument.\n"; exit 3; } if (!defined($options{options})) { $options{output}->add_option_msg(short_msg => "Class Mysqlcmd: Need to specify 'options' argument."); $options{output}->option_exit(); } - $options{options}->add_options(arguments => - { "mysql-cmd:s" => { name => 'mysql_cmd', default => '/usr/bin/mysql' }, - "host:s" => { name => 'host' }, - "port:s" => { name => 'port' }, - "username:s" => { name => 'username' }, - "password:s" => { name => 'password' }, - "sql-errors-exit:s" => { name => 'sql-errors-exit', default => 'unknown' }, - }); - $options{options}->add_help(package => __PACKAGE__, sections => 'MYSQLCMD OPTIONS'); + if (!defined($options{noptions})) { + $options{options}->add_options(arguments => + { "mysql-cmd:s" => { name => 'mysql_cmd', default => '/usr/bin/mysql' }, + "host:s@" => { name => 'host' }, + "port:s@" => { name => 'port' }, + "username:s@" => { name => 'username' }, + "password:s@" => { name => 'password' }, + "sql-errors-exit:s" => { name => 'sql_errors_exit', default => 'unknown' }, + }); + } + $options{options}->add_help(package => __PACKAGE__, sections => 'MYSQLCMD OPTIONS', once => 1); $self->{output} = $options{output}; $self->{mode} = $options{mode}; @@ -38,41 +41,73 @@ sub new { $self->{stdout} = undef; $self->{version} = undef; + $self->{host} = undef; + $self->{port} = undef; + $self->{username} = undef; + $self->{password} = undef; + return $self; } -sub check_options { +# Method to manage multiples +sub set_options { my ($self, %options) = @_; - # options{default} = { 'mode_name' => { option_name => opt_value } } + # options{options_result} - %{$self->{option_results}} = %{$options{option_results}}; + $self->{option_results} = $options{option_results}; +} + +# Method to manage multiples +sub set_defaults { + my ($self, %options) = @_; + # options{default} + # Manage default value - return if (!defined($options{default})); foreach (keys %{$options{default}}) { if ($_ eq $self->{mode}) { - foreach my $value (keys %{$options{default}->{$_}}) { - if (!defined($self->{option_results}->{$value})) { - $self->{option_results}->{$value} = $options{default}->{$_}->{$value}; + for (my $i = 0; $i < scalar(@{$options{default}->{$_}}); $i++) { + foreach my $opt (keys %{$options{default}->{$_}[$i]}) { + if (!defined($self->{option_results}->{$opt}[$i])) { + $self->{option_results}->{$opt}[$i] = $options{default}->{$_}[$i]->{$opt}; + } } } } } +} - if (!defined($self->{option_results}->{host}) || $self->{option_results}->{host} eq '') { +sub check_options { + my ($self, %options) = @_; + # return 1 = ok still data_source + # return 0 = no data_source left + + $self->{host} = (defined($self->{option_results}->{host})) ? shift(@{$self->{option_results}->{host}}) : undef; + $self->{port} = (defined($self->{option_results}->{port})) ? shift(@{$self->{option_results}->{port}}) : undef; + $self->{username} = (defined($self->{option_results}->{username})) ? shift(@{$self->{option_results}->{username}}) : undef; + $self->{password} = (defined($self->{option_results}->{password})) ? shift(@{$self->{option_results}->{password}}) : undef; + $self->{sql_errors_exit} = $self->{option_results}->{sql_errors_exit}; + $self->{mysql_cmd} = $self->{option_results}->{mysql_cmd}; + + if (!defined($self->{host}) || $self->{host} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify host argument."); - $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); } - $self->{args} = ['--batch', '--raw', '--skip-column-names', '--host', $self->{option_results}->{host}]; - if (defined($self->{option_results}->{port})) { - push @{$self->{args}}, "--port", $self->{option_results}->{port}; + $self->{args} = ['--batch', '--raw', '--skip-column-names', '--host', $self->{host}]; + if (defined($self->{port})) { + push @{$self->{args}}, "--port", $self->{port}; } - if (defined($self->{option_results}->{username})) { - push @{$self->{args}}, "--user", $self->{option_results}->{username}; + if (defined($self->{username})) { + push @{$self->{args}}, "--user", $self->{username}; } - if (defined($self->{option_results}->{password}) && $self->{option_results}->{password} ne '') { - push @{$self->{args}}, "-p" . $self->{option_results}->{password}; + if (defined($self->{password}) && $self->{password} ne '') { + push @{$self->{args}}, "-p" . $self->{password}; } + + if (scalar(@{$self->{option_results}->{host}}) == 0) { + return 0; + } + return 1; } sub is_version_minimum { @@ -96,9 +131,9 @@ sub is_version_minimum { sub get_unique_id4save { my ($self, %options) = @_; - my $msg = $self->{option_results}->{host}; - if (defined($self->{option_results}->{port})) { - $msg .= ":" . $self->{option_results}->{port}; + my $msg = $self->{host}; + if (defined($self->{port})) { + $msg .= ":" . $self->{port}; } return md5_hex($msg); } @@ -113,7 +148,7 @@ sub command_execution { my ($self, %options) = @_; my ($lerror, $stdout, $exit_code) = centreon::plugins::misc::backtick( - command => $self->{option_results}->{mysql_cmd}, + command => $self->{mysql_cmd}, arguments => [@{$self->{args}}, '-e', $options{request}], timeout => 30, wait_exit => 1, @@ -140,7 +175,7 @@ sub connect { if ($exit_code != 0) { if ($dontquit == 0) { $self->{output}->add_option_msg(short_msg => "Cannot connect: " . $stdout); - $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); } return (-1, "Cannot connect: " . $stdout); } @@ -179,7 +214,7 @@ sub query { if ($exit_code != 0) { $self->{output}->add_option_msg(short_msg => "Cannot execute query: " . $self->{stdout}); - $self->{output}->option_exit(exit_litteral => $self->{option_results}->{sql_errors_exit}); + $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); } } diff --git a/centreon/lib/perl/plugins/database/mysql/plugin.pm b/centreon/lib/perl/plugins/database/mysql/plugin.pm index 3502d65d9b1..7906063ccaf 100644 --- a/centreon/lib/perl/plugins/database/mysql/plugin.pm +++ b/centreon/lib/perl/plugins/database/mysql/plugin.pm @@ -6,12 +6,7 @@ use base qw(centreon::plugins::script_sql); sub new { my ($class, %options) = @_; - $options{options}->add_options( - arguments => { - 'host:s' => { name => 'db_host' }, - 'port:s' => { name => 'db_port' }, - } - ); + my $self = $class->SUPER::new(package => __PACKAGE__, %options); bless $self, $class; # $options->{options} = options object @@ -30,16 +25,36 @@ sub new { ); $self->{sql_modes}{mysqlcmd} = 'database::mysql::mysqlcmd'; - if (defined($self->{db_host}) && $self->{db_host} ne '') { - $self->{sqldefault}->{dbi} = { data_source => 'mysql:host=' . $self->{db_host} }; - $self->{sqldefault}->{mysqlcmd} = { host => $self->{db_host} }; - if (defined($self->{db_port}) && $self->{db_port} ne '') { - $self->{sqldefault}->{dbi}->{data_source} .= ';port=' . $self->{db_port}; - $self->{sqldefault}->{mysqlcmd}->{port} = $self->{db_port}; + return $self; +} + +sub init { + my ($self, %options) = @_; + + $self->{options}->add_options( + arguments => { + 'host:s@' => { name => 'db_host' }, + 'port:s@' => { name => 'db_port' }, + } + ); + $self->{options}->parse_options(); + my $options_result = $self->{options}->get_options(); + $self->{options}->clean(); + + if (defined($options_result->{db_host})) { + @{$self->{sqldefault}->{dbi}} = (); + @{$self->{sqldefault}->{mysqlcmd}} = (); + for (my $i = 0; $i < scalar(@{$options_result->{db_host}}); $i++) { + $self->{sqldefault}->{dbi}[$i] = { data_source => 'mysql:host=' . $options_result->{db_host}[$i] }; + $self->{sqldefault}->{mysqlcmd}[$i] = { host => $options_result->{db_host}[$i] }; + if (defined($options_result->{db_port}[$i])) { + $self->{sqldefault}->{dbi}[$i]->{data_source} .= ';port=' . $options_result->{db_port}[$i]; + $self->{sqldefault}->{mysqlcmd}[$i]->{port} = $options_result->{db_port}[$i]; + } } } - return $self; + $self->SUPER::init(%options); } 1; From d9e4d125e30a450d057b45ebb873b7bc1ea71517 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 29 Oct 2013 17:21:40 +0100 Subject: [PATCH 120/458] + Add MySQL mode replication check --- centreon/lib/perl/centreon/plugins/dbi.pm | 12 + .../mysql/mode/replicationmasterslave.pm | 312 ++++++++++++++++++ .../perl/plugins/database/mysql/mysqlcmd.pm | 45 ++- .../lib/perl/plugins/database/mysql/plugin.pm | 1 + 4 files changed, 369 insertions(+), 1 deletion(-) create mode 100644 centreon/lib/perl/plugins/database/mysql/mode/replicationmasterslave.pm diff --git a/centreon/lib/perl/centreon/plugins/dbi.pm b/centreon/lib/perl/centreon/plugins/dbi.pm index 84bbbbce7bb..3b98c260208 100644 --- a/centreon/lib/perl/centreon/plugins/dbi.pm +++ b/centreon/lib/perl/centreon/plugins/dbi.pm @@ -145,6 +145,12 @@ sub connect { return 0; } +sub get_id { + my ($self, %options) = @_; + + return $self->{data_source}; +} + sub get_unique_id4save { my ($self, %options) = @_; @@ -163,6 +169,12 @@ sub fetchrow_array { return $self->{statement_handle}->fetchrow_array(); } +sub fetchrow_hashref { + my ($self, %options) = @_; + + return $self->{statement_handle}->fetchrow_hashref(); +} + sub query { my ($self, %options) = @_; diff --git a/centreon/lib/perl/plugins/database/mysql/mode/replicationmasterslave.pm b/centreon/lib/perl/plugins/database/mysql/mode/replicationmasterslave.pm new file mode 100644 index 00000000000..e863798e076 --- /dev/null +++ b/centreon/lib/perl/plugins/database/mysql/mode/replicationmasterslave.pm @@ -0,0 +1,312 @@ +package database::mysql::mode::replicationmasterslave; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + + if (ref($options{sql}) ne 'ARRAY') { + $self->{output}->add_option_msg(short_msg => "Need to use --multiple options."); + $self->{output}->option_exit(); + } + if (scalar(@{$options{sql}}) < 2) { + $self->{output}->add_option_msg(short_msg => "Need to specify two MySQL Server."); + $self->{output}->option_exit(); + } + + my ($sql_one, $sql_two) = @{$options{sql}}; + my ($slave_status, $slave_status_error) = (0, ""); + my ($position_status, $position_status_error) = (0, ""); + my ($connection_status_name_srv1, $connection_status_name_srv2) = ($sql_one->get_id(), $sql_two->get_id()); + my ($master_save, $slave_save); + + my ($exit1, $msg_error1) = $sql_one->connect(dontquit => 1); + my ($exit2, $msg_error2) = $sql_two->connect(dontquit => 1); + $self->{output}->output_add(severity => 'OK', + short_msg => "No problems. Replication is ok."); + if ($exit1 == -1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Connection Status '" . $sql_one->get_id() . "': " . $msg_error1); + } else { + $self->{output}->output_add(long_msg => "Connection Status '" . $sql_one->get_id() . "' [OK]"); + } + if ($exit2 == -1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Connection Status '" . $sql_two->get_id() . "': " . $msg_error2); + } else { + $self->{output}->output_add(long_msg => "Connection Status '" . $sql_two->get_id() . "' [OK]"); + } + + ##### + # Find SLAVE + ##### + my ($total_srv1, $total_srv2); + my ($last_error1, $last_error2); + + my ($io_thread_status_srv1, $sql_thread_status_srv1); + if ($exit1 != -1) { + $sql_one->query(query => q{ + SHOW SLAVE STATUS + }); + my $result = $sql_one->fetchrow_hashref(); + my $slave_io_running = $result->{Slave_IO_Running}; + my $slave_sql_running = $result->{Slave_SQL_Running}; + $last_error1 = $result->{Last_Error}; + + if (defined($slave_io_running) && $slave_io_running =~ /^yes$/i) { + $io_thread_status_srv1 = 0; + } else { + $io_thread_status_srv1 = 1; + } + if (defined($slave_sql_running) && $slave_sql_running =~ /^yes$/i) { + $sql_thread_status_srv1 = 0; + } else { + $sql_thread_status_srv1 = 1; + } + } else { + $io_thread_status_srv1 = 100; + $sql_thread_status_srv1 = 100; + } + + my ($io_thread_status_srv2, $sql_thread_status_srv2); + if ($exit2 != -1) { + $sql_two->query(query => q{ + SHOW SLAVE STATUS + }); + my $result = $sql_two->fetchrow_hashref(); + my $slave_io_running = $result->{Slave_IO_Running}; + my $slave_sql_running = $result->{Slave_SQL_Running}; + $last_error2 = $result->{Last_Error}; + + if (defined($slave_io_running) && $slave_io_running =~ /^yes$/i) { + $io_thread_status_srv2 = 0; + } else { + $io_thread_status_srv2 = 1; + } + if (defined($slave_sql_running) && $slave_sql_running =~ /^yes$/i) { + $sql_thread_status_srv2 = 0; + } else { + $sql_thread_status_srv2 = 1; + } + } else { + $io_thread_status_srv2 = 100; + $sql_thread_status_srv2 = 100; + } + + $total_srv1 = $io_thread_status_srv1 + $sql_thread_status_srv1; + $total_srv2 = $io_thread_status_srv2 + $sql_thread_status_srv2; + + # Check If there is two slave + if ($total_srv1 < 2 && $total_srv2 < 2) { + $slave_status = 1; + $slave_status_error = "Two slave. Need to have only one."; + } else { + # Check if a thread is down + if ($total_srv1 == 1) { + $slave_status = -1; + $slave_status_error = "A Replication thread is down on '" . $sql_one->get_id() . "'."; + if ($sql_thread_status_srv1 != 0) { + if (defined($last_error1) && $last_error1 ne "") { + $slave_status = 1; + $slave_status_error .= " SQL Thread is stopped because of an error (error='" . $last_error1 . "')."; + } + } + } + if ($total_srv2 == 1) { + $slave_status = -1; + $slave_status_error = "A Replication thread is down on '" . $sql_two->get_id() . "'."; + if ($sql_thread_status_srv2 != 0) { + if (defined($last_error2) && $last_error2 ne "") { + $slave_status = 1; + $slave_status_error .= " SQL Thread is stopped because of an error (error='" . $last_error2 . "')."; + } + } + } + + # Check if we need to SKIP + if ($io_thread_status_srv1 == 100) { + $slave_status = -1; + $slave_status_error .= " Skip check on '" . $sql_one->get_id() . "'."; + } + if ($io_thread_status_srv2 == 100) { + $slave_status = -1; + $slave_status_error .= " Skip check on '" . $sql_two->get_id() . "'."; + } + + # Save Slave + if ($total_srv1 < 2) { + $slave_save = $sql_one; + $master_save = $sql_two; + } + if ($total_srv2 < 2) { + $slave_save = $sql_two; + $master_save = $sql_one; + } + + if ($total_srv2 > 1 && $total_srv1 > 1) { + $slave_status = 1; + $slave_status_error .= " No slave (maybe because we cannot check a server)."; + } + } + + #### + # Check Slave position + #### + if (!defined($slave_save)) { + $position_status = -2; + $position_status_error = "Skip because we can't identify a unique slave."; + } else { + if ($master_save->get_id() eq $connection_status_name_srv1 && $exit1 == -1) { + $position_status = -1; + $position_status_error = "Can't get master position on '" . $master_save->get_id() . "'."; + } elsif ($master_save->get_id() eq $connection_status_name_srv2 && $exit2 == -1) { + $position_status = -1; + $position_status_error = "Can't get master position on '" . $master_save->get_id() . "'."; + } else { + # Get Master Position + $master_save->query(query => q{ + SHOW MASTER STATUS + }); + my $result = $master_save->fetchrow_hashref(); + my $master_file = $result->{File}; + my $master_position = $result->{Position}; + + $slave_save->query(query => q{ + SHOW SLAVE STATUS + }); + my $result2 = $slave_save->fetchrow_hashref(); + my $slave_file = $result2->{Master_Log_File}; # 'Master_Log_File' + my $slave_position = $result2->{Read_Master_Log_Pos}; # 'Read_Master_Log_Pos' + my $num_sec_lates = $result2->{Seconds_Behind_Master}; + + my $exit_code_sec = $self->{perfdata}->threshold_check(value => $num_sec_lates, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + if (!$self->{output}->is_status(value => $exit_code_sec, compare => 'ok', litteral => 1)) { + $self->{output}->output_add(severity => $exit_code_sec, + short_msg => sprintf("Slave has %d seconds latency behind master", $num_sec_lates)); + } + $self->{output}->perfdata_add(label => 'slave_latency', unit => 's', + value => $num_sec_lates, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + + my $slave_sql_thread_ko = 1; + my $slave_sql_thread_warning = 1; + my $slave_sql_thread_ok = 1; + + $slave_save->query(query => q{ + SHOW FULL PROCESSLIST + }); + while ((my $row = $slave_save->fetchrow_hashref())) { + my $state = $row->{State}; + $slave_sql_thread_ko = 0 if (defined($state) && $state =~ /^(Waiting to reconnect after a failed binlog dump request|Connecting to master|Reconnecting after a failed binlog dump request|Waiting to reconnect after a failed master event read|Waiting for the slave SQL thread to free enough relay log space)$/i); + $slave_sql_thread_warning = 0 if (defined($state) && $state =~ /^Waiting for the next event in relay log|Reading event from the relay log$/i); + $slave_sql_thread_ok = 0 if (defined($state) && $state =~ /^Has read all relay log; waiting for the slave I\/O thread to update it$/i); + } + + if ($slave_sql_thread_ko == 0) { + $position_status = 1; + $position_status_error .= " Slave replication has connection issue with the master."; + } elsif (($master_file ne $slave_file || $master_position != $slave_position) && $slave_sql_thread_warning == 0) { + $position_status = -1; + $position_status_error .= " Slave replication is late but it's progressing.."; + } elsif (($master_file ne $slave_file || $master_position != $slave_position) && $slave_sql_thread_ok == 0) { + $position_status = -1; + $position_status_error .= " Slave replication is late but it's progressing.."; + } + } + } + + + + $self->replication_add($slave_status, "Slave Thread Status", $slave_status_error); + $self->replication_add($position_status, "Position Status", $position_status_error); + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub replication_add { + my ($self, $lstate, $str_display, $lerr) = @_; + my $status; + my $status_msg; + + if ($lstate == 0) { + $status = 'OK'; + } elsif ($lstate == -1) { + $status = 'WARNING'; + } elsif ($lstate == -2) { + $status = 'CRITICAL'; + $status_msg = 'SKIP'; + } else { + $status = 'CRITICAL'; + } + + my $output; + if (defined($lerr) && $lerr ne "") { + $output = $str_display . " [" . (defined($status_msg) ? $status_msg : $status) . "] [" . $lerr . "]"; + } else { + $output = $str_display . " [" . (defined($status_msg) ? $status_msg : $status) . "]"; + } + if (!$self->{output}->is_status(value => $status, compare => 'ok', litteral => 1)) { + $self->{output}->output_add(severity => $status, + short_msg => $output); + } + + $self->{output}->output_add(long_msg => $output); +} + +1; + +__END__ + +=head1 MODE + +Check MySQL replication master/slave (need to use --multiple). + +=over 8 + +=item B<--warning> + +Threshold warning in seconds (slave latency). + +=item B<--critical> + +Threshold critical in seconds (slave latency). + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm index 963d60b068a..313fd1792e1 100644 --- a/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm +++ b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm @@ -93,7 +93,7 @@ sub check_options { $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); } - $self->{args} = ['--batch', '--raw', '--skip-column-names', '--host', $self->{host}]; + $self->{args} = ['--batch', '--raw', '--host', $self->{host}]; if (defined($self->{port})) { push @{$self->{args}}, "--port", $self->{port}; } @@ -128,6 +128,17 @@ sub is_version_minimum { return 1; } +sub get_id { + my ($self, %options) = @_; + + my $msg = $self->{host}; + if (defined($self->{port})) { + $msg .= ":" . $self->{port}; + } + return $msg; +} + + sub get_unique_id4save { my ($self, %options) = @_; @@ -189,6 +200,10 @@ sub fetchall_arrayref { my ($self, %options) = @_; my $array_ref = []; + if (!defined($self->{columns})) { + $self->{stdout} =~ s/^(.*?)(\n|$)//; + @{$self->{columns}} = split(/\t/, $1); + } foreach (split /\n/, $self->{stdout}) { push @$array_ref, [map({ s/\\n/\x{0a}/g; s/\\t/\x{09}/g; s/\\/\x{5c}/g; $_; } split(/\t/, $_))]; } @@ -200,6 +215,10 @@ sub fetchrow_array { my ($self, %options) = @_; my @array_result = (); + if (!defined($self->{columns})) { + $self->{stdout} =~ s/^(.*?)(\n|$)//; + @{$self->{columns}} = split(/\t/, $1); + } if (($self->{stdout} =~ s/^(.*?)(\n|$)//)) { push @array_result, map({ s/\\n/\x{0a}/g; s/\\t/\x{09}/g; s/\\/\x{5c}/g; $_; } split(/\t/, $1)); } @@ -207,9 +226,33 @@ sub fetchrow_array { return @array_result; } +sub fetchrow_hashref { + my ($self, %options) = @_; + my $array_result = undef; + + if (!defined($self->{columns})) { + $self->{stdout} =~ s/^(.*?)(\n|$)//; + @{$self->{columns}} = split(/\t/, $1); + } + if ($self->{stdout} ne '' && $self->{stdout} =~ s/^(.*?)(\n|$)//) { + $array_result = {}; + my @values = split(/\t/, $1); + for (my $i = 0; $i < scalar(@values); $i++) { + my $value = $values[$i]; + $value =~ s/\\n/\x{0a}/g; + $value =~ s/\\t/\x{09}/g; + $value =~ s/\\/\x{5c}/g; + $array_result->{$self->{columns}[$i]} = $value; + } + } + + return $array_result; +} + sub query { my ($self, %options) = @_; + $self->{columns} = undef; (my $exit_code, $self->{stdout}) = $self->command_execution(request => $options{query}); if ($exit_code != 0) { diff --git a/centreon/lib/perl/plugins/database/mysql/plugin.pm b/centreon/lib/perl/plugins/database/mysql/plugin.pm index 7906063ccaf..5b9903a0aa3 100644 --- a/centreon/lib/perl/plugins/database/mysql/plugin.pm +++ b/centreon/lib/perl/plugins/database/mysql/plugin.pm @@ -22,6 +22,7 @@ sub new { 'open-files' => 'database::mysql::mode::openfiles', 'innodb-bufferpool-hitrate' => 'database::mysql::mode::innodbbufferpoolhitrate', 'myisam-keycache-hitrate' => 'database::mysql::mode::myisamkeycachehitrate', + 'replication-master-slave' => 'database::mysql::mode::replicationmasterslave', ); $self->{sql_modes}{mysqlcmd} = 'database::mysql::mysqlcmd'; From f3ebccc105598728ced5f73bdf59b78ddf62d4b2 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Thu, 31 Oct 2013 13:10:45 +0100 Subject: [PATCH 121/458] + Add mode dyn-mode --- .../perl/centreon/plugins/script_simple.pm | 31 +++++++++++++------ .../lib/perl/centreon/plugins/script_snmp.pm | 31 +++++++++++++------ .../lib/perl/centreon/plugins/script_sql.pm | 31 +++++++++++++------ 3 files changed, 66 insertions(+), 27 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/script_simple.pm b/centreon/lib/perl/centreon/plugins/script_simple.pm index cc37cb39580..ad152a1dbf0 100644 --- a/centreon/lib/perl/centreon/plugins/script_simple.pm +++ b/centreon/lib/perl/centreon/plugins/script_simple.pm @@ -15,8 +15,9 @@ sub new { $self->{options}->add_options( arguments => { - 'mode:s' => { name => 'mode' }, - 'list-mode' => { name => 'list_mode' }, + 'mode:s' => { name => 'mode' }, + 'dyn-mode:s' => { name => 'dynmode_name' }, + 'list-mode' => { name => 'list_mode' }, } ); $self->{version} = '1.0'; @@ -49,19 +50,27 @@ sub init { if (defined($self->{list_mode})) { $self->list_mode(); } - if (!defined($self->{mode_name}) || $self->{mode_name} eq '') { - $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' option."); + if ((!defined($self->{mode_name}) || $self->{mode_name} eq '') && (!defined($self->{dynmode_name}))) { + $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' or '--dyn-mode' option."); $self->{output}->option_exit(); } - $self->is_mode(mode => $self->{mode_name}); + if (defined($self->{mode_name})) { + $self->is_mode(mode => $self->{mode_name}); + } # Output HELP $self->{options}->add_help(package => 'centreon::plugins::output', sections => 'OUTPUT OPTIONS'); # Load mode - (my $file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; - require $file; - $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + if (defined($self->{mode_name})) { + (my $file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; + require $file; + $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + } else { + (my $file = $self->{dynmode_name} . ".pm") =~ s{::}{/}g; + require $file; + $self->{mode} = $self->{dynmode_name}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + } if (defined($options{help})) { $self->{options}->add_help(package => $self->{modes}{$self->{mode_name}}, sections => 'MODE'); @@ -130,7 +139,11 @@ __END__ =item B<--mode> -Choose a mode (required). +Choose a mode. + +=item B<--dyn-mode> + +Specify a mode with the path (separated by '::'). =item B<--list-mode> diff --git a/centreon/lib/perl/centreon/plugins/script_snmp.pm b/centreon/lib/perl/centreon/plugins/script_snmp.pm index 2274f2fce51..1f3ccb7559b 100644 --- a/centreon/lib/perl/centreon/plugins/script_snmp.pm +++ b/centreon/lib/perl/centreon/plugins/script_snmp.pm @@ -16,8 +16,9 @@ sub new { $self->{options}->add_options( arguments => { - 'mode:s' => { name => 'mode' }, - 'list-mode' => { name => 'list_mode' }, + 'mode:s' => { name => 'mode' }, + 'dyn-mode:s' => { name => 'dynmode_name' }, + 'list-mode' => { name => 'list_mode' }, } ); $self->{version} = '1.0'; @@ -50,11 +51,13 @@ sub init { if (defined($self->{list_mode})) { $self->list_mode(); } - if (!defined($self->{mode_name}) || $self->{mode_name} eq '') { - $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' option."); + if ((!defined($self->{mode_name}) || $self->{mode_name} eq '') && (!defined($self->{dynmode_name}))) { + $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' or '--dyn-mode' option."); $self->{output}->option_exit(); } - $self->is_mode(mode => $self->{mode_name}); + if (defined($self->{mode_name})) { + $self->is_mode(mode => $self->{mode_name}); + } # Output HELP $self->{options}->add_help(package => 'centreon::plugins::output', sections => 'OUTPUT OPTIONS'); @@ -63,9 +66,15 @@ sub init { $self->{snmp} = centreon::plugins::snmp->new(options => $self->{options}, output => $self->{output}); # Load mode - (my $file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; - require $file; - $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + if (defined($self->{mode_name})) { + (my $file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; + require $file; + $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + } else { + (my $file = $self->{dynmode_name} . ".pm") =~ s{::}{/}g; + require $file; + $self->{mode} = $self->{dynmode_name}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + } if (defined($options{help})) { $self->{options}->add_help(package => $self->{modes}{$self->{mode_name}}, sections => 'MODE'); @@ -148,7 +157,11 @@ __END__ =item B<--mode> -Choose a mode (required). +Choose a mode. + +=item B<--dyn-mode> + +Specify a mode with the path (separated by '::'). =item B<--list-mode> diff --git a/centreon/lib/perl/centreon/plugins/script_sql.pm b/centreon/lib/perl/centreon/plugins/script_sql.pm index 8e4137f0ac2..c254dd58fcc 100644 --- a/centreon/lib/perl/centreon/plugins/script_sql.pm +++ b/centreon/lib/perl/centreon/plugins/script_sql.pm @@ -16,6 +16,7 @@ sub new { $self->{options}->add_options( arguments => { 'mode:s' => { name => 'mode_name' }, + 'dyn-mode:s' => { name => 'dynmode_name' }, 'list-mode' => { name => 'list_mode' }, 'sqlmode:s' => { name => 'sqlmode_name', default => 'dbi' }, 'list-sqlmode' => { name => 'list_sqlmode' }, @@ -48,11 +49,11 @@ sub init { # $options{version} = string version # $options{help} = string help - if (defined($options{help}) && !defined($self->{mode_name})) { + if (defined($options{help}) && !defined($self->{mode_name}) && !defined($self->{dynmode_name})) { $self->{options}->display_help(); $self->{output}->option_exit(); } - if (defined($options{version}) && !defined($self->{mode_name})) { + if (defined($options{version}) && !defined($self->{mode_name})&& !defined($self->{dynmode_name})) { $self->version(); } if (defined($self->{list_mode})) { @@ -62,11 +63,13 @@ sub init { $self->list_sqlmode(); } - if (!defined($self->{mode_name}) || $self->{mode_name} eq '') { - $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' option."); + if ((!defined($self->{mode_name}) || $self->{mode_name} eq '') && (!defined($self->{dynmode_name}))) { + $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' or '--dyn-mode' option."); $self->{output}->option_exit(); } - $self->is_mode(mode => $self->{mode_name}); + if (defined($self->{mode_name})) { + $self->is_mode(mode => $self->{mode_name}); + } $self->is_sqlmode(sqlmode => $self->{sqlmode_name}); # Output HELP @@ -79,9 +82,15 @@ sub init { $self->{sqlmode_current} = $self->{sql_modes}{$self->{sqlmode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{sqlmode_name}); # Load mode - ($file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; - require $file; - $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + if (defined($self->{mode_name})) { + ($file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; + require $file; + $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + } else { + ($file = $self->{dynmode_name} . ".pm") =~ s{::}{/}g; + require $file; + $self->{mode} = $self->{dynmode_name}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + } if (defined($options{help})) { $self->{options}->add_help(package => $self->{modes}{$self->{mode_name}}, sections => 'MODE'); @@ -201,12 +210,16 @@ __END__ =item B<--mode> -Choose a mode (required). +Choose a mode. =item B<--list-mode> List available modes. +=item B<--dyn-mode> + +Specify a mode with the path (separated by '::'). + =item B<--sqlmode> Choose a sql mode (Default: "dbi"). From 79a0a05d08f24e30f033b6ae76fc38770a3bb6df Mon Sep 17 00:00:00 2001 From: qgarnier Date: Fri, 1 Nov 2013 11:49:52 +0100 Subject: [PATCH 122/458] + refactoring some code --- centreon/lib/perl/centreon/plugins/misc.pm | 16 ++++++++ centreon/lib/perl/centreon/plugins/script.pm | 4 +- .../perl/centreon/plugins/script_simple.pm | 23 +++++------ .../lib/perl/centreon/plugins/script_snmp.pm | 24 +++++------ .../lib/perl/centreon/plugins/script_sql.pm | 40 +++++++++---------- 5 files changed, 59 insertions(+), 48 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/misc.pm b/centreon/lib/perl/centreon/plugins/misc.pm index 973504e5060..a974e8866b6 100644 --- a/centreon/lib/perl/centreon/plugins/misc.pm +++ b/centreon/lib/perl/centreon/plugins/misc.pm @@ -3,6 +3,22 @@ package centreon::plugins::misc; use strict; use warnings; +sub mymodule_load { + my (%options) = @_; + my $file; + ($file = $options{module} . ".pm") =~ s{::}{/}g; + + eval { + local $SIG{__DIE__} = 'IGNORE'; + require $file; + }; + if ($@) { + $options{output}->add_option_msg(long_msg => $@); + $options{output}->add_option_msg(short_msg => $options{error_msg}); + $options{output}->option_exit(); + } +} + sub backtick { my %arg = ( command => undef, diff --git a/centreon/lib/perl/centreon/plugins/script.pm b/centreon/lib/perl/centreon/plugins/script.pm index dc48211cbfe..ef799f53b6b 100644 --- a/centreon/lib/perl/centreon/plugins/script.pm +++ b/centreon/lib/perl/centreon/plugins/script.pm @@ -169,8 +169,8 @@ sub run { $self->check_relaunch(); - (my $file = $self->{plugin} . ".pm") =~ s{::}{/}g; - require $file; + centreon::plugins::misc::mymodule_load(output => $self->{output}, module => $self->{plugin}, + error_msg => "Cannot load module --plugin."); my $plugin = $self->{plugin}->new(options => $self->{options}, output => $self->{output}); $plugin->init(help => $self->{help}, version => $self->{version}); diff --git a/centreon/lib/perl/centreon/plugins/script_simple.pm b/centreon/lib/perl/centreon/plugins/script_simple.pm index ad152a1dbf0..69621dd7b2c 100644 --- a/centreon/lib/perl/centreon/plugins/script_simple.pm +++ b/centreon/lib/perl/centreon/plugins/script_simple.pm @@ -50,26 +50,23 @@ sub init { if (defined($self->{list_mode})) { $self->list_mode(); } - if ((!defined($self->{mode_name}) || $self->{mode_name} eq '') && (!defined($self->{dynmode_name}))) { - $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' or '--dyn-mode' option."); - $self->{output}->option_exit(); - } - if (defined($self->{mode_name})) { - $self->is_mode(mode => $self->{mode_name}); - } # Output HELP $self->{options}->add_help(package => 'centreon::plugins::output', sections => 'OUTPUT OPTIONS'); # Load mode - if (defined($self->{mode_name})) { - (my $file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; - require $file; + if (defined($self->{mode_name}) && $self->{mode_name} ne '') { + $self->is_mode(mode => $self->{mode_name}); + centreon::plugins::misc::mymodule_load(output => $self->{output}, module => $self->{modes}{$self->{mode_name}}, + error_msg => "Cannot load module --mode."); $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); - } else { - (my $file = $self->{dynmode_name} . ".pm") =~ s{::}{/}g; - require $file; + } elsif (defined($self->{dynmode_name}) && $self->{dynmode_name} ne '') { + centreon::plugins::misc::mymodule_load(output => $self->{output}, module => $self->{dynmode_name}, + error_msg => "Cannot load module --dyn-mode."); $self->{mode} = $self->{dynmode_name}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + } else { + $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' or '--dyn-mode' option."); + $self->{output}->option_exit(); } if (defined($options{help})) { diff --git a/centreon/lib/perl/centreon/plugins/script_snmp.pm b/centreon/lib/perl/centreon/plugins/script_snmp.pm index 1f3ccb7559b..cdd3fd1d446 100644 --- a/centreon/lib/perl/centreon/plugins/script_snmp.pm +++ b/centreon/lib/perl/centreon/plugins/script_snmp.pm @@ -3,6 +3,7 @@ package centreon::plugins::script_snmp; use strict; use warnings; use centreon::plugins::snmp; +use centreon::plugins::misc; sub new { my ($class, %options) = @_; @@ -51,13 +52,6 @@ sub init { if (defined($self->{list_mode})) { $self->list_mode(); } - if ((!defined($self->{mode_name}) || $self->{mode_name} eq '') && (!defined($self->{dynmode_name}))) { - $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' or '--dyn-mode' option."); - $self->{output}->option_exit(); - } - if (defined($self->{mode_name})) { - $self->is_mode(mode => $self->{mode_name}); - } # Output HELP $self->{options}->add_help(package => 'centreon::plugins::output', sections => 'OUTPUT OPTIONS'); @@ -66,14 +60,18 @@ sub init { $self->{snmp} = centreon::plugins::snmp->new(options => $self->{options}, output => $self->{output}); # Load mode - if (defined($self->{mode_name})) { - (my $file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; - require $file; + if (defined($self->{mode_name}) && $self->{mode_name} ne '') { + $self->is_mode(mode => $self->{mode_name}); + centreon::plugins::misc::mymodule_load(output => $self->{output}, module => $self->{modes}{$self->{mode_name}}, + error_msg => "Cannot load module --mode."); $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); - } else { - (my $file = $self->{dynmode_name} . ".pm") =~ s{::}{/}g; - require $file; + } elsif (defined($self->{dynmode_name}) && $self->{dynmode_name} ne '') { + centreon::plugins::misc::mymodule_load(output => $self->{output}, module => $self->{dynmode_name}, + error_msg => "Cannot load module --dyn-mode."); $self->{mode} = $self->{dynmode_name}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + } else { + $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' or '--dyn-mode' option."); + $self->{output}->option_exit(); } if (defined($options{help})) { diff --git a/centreon/lib/perl/centreon/plugins/script_sql.pm b/centreon/lib/perl/centreon/plugins/script_sql.pm index c254dd58fcc..d9352177c0e 100644 --- a/centreon/lib/perl/centreon/plugins/script_sql.pm +++ b/centreon/lib/perl/centreon/plugins/script_sql.pm @@ -2,6 +2,7 @@ package centreon::plugins::script_sql; use strict; use warnings; +use centreon::plugins::misc; sub new { my ($class, %options) = @_; @@ -62,34 +63,33 @@ sub init { if (defined($self->{list_sqlmode})) { $self->list_sqlmode(); } - - if ((!defined($self->{mode_name}) || $self->{mode_name} eq '') && (!defined($self->{dynmode_name}))) { - $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' or '--dyn-mode' option."); - $self->{output}->option_exit(); - } - if (defined($self->{mode_name})) { - $self->is_mode(mode => $self->{mode_name}); - } - $self->is_sqlmode(sqlmode => $self->{sqlmode_name}); # Output HELP $self->{options}->add_help(package => 'centreon::plugins::output', sections => 'OUTPUT OPTIONS'); - # Load Sql-Mode - (my $file = $self->{sql_modes}{$self->{sqlmode_name}} . ".pm") =~ s{::}{/}g; - require $file; - - $self->{sqlmode_current} = $self->{sql_modes}{$self->{sqlmode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{sqlmode_name}); + if (defined($self->{sqlmode_name}) && $self->{sqlmode_name} ne '') { + $self->is_sqlmode(sqlmode => $self->{sqlmode_name}); + centreon::plugins::misc::mymodule_load(output => $self->{output}, module => $self->{sql_modes}{$self->{sqlmode_name}}, + error_msg => "Cannot load module --sqlmode."); + $self->{sqlmode_current} = $self->{sql_modes}{$self->{sqlmode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{sqlmode_name}); + } else { + $self->{output}->add_option_msg(short_msg => "Need to specify '--sqlmode'."); + $self->{output}->option_exit(); + } # Load mode - if (defined($self->{mode_name})) { - ($file = $self->{modes}{$self->{mode_name}} . ".pm") =~ s{::}{/}g; - require $file; + if (defined($self->{mode_name}) && $self->{mode_name} ne '') { + $self->is_mode(mode => $self->{mode_name}); + centreon::plugins::misc::mymodule_load(output => $self->{output}, module => $self->{modes}{$self->{mode_name}}, + error_msg => "Cannot load module --mode."); $self->{mode} = $self->{modes}{$self->{mode_name}}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); - } else { - ($file = $self->{dynmode_name} . ".pm") =~ s{::}{/}g; - require $file; + } elsif (defined($self->{dynmode_name}) && $self->{dynmode_name} ne '') { + centreon::plugins::misc::mymodule_load(output => $self->{output}, module => $self->{dynmode_name}, + error_msg => "Cannot load module --dyn-mode."); $self->{mode} = $self->{dynmode_name}->new(options => $self->{options}, output => $self->{output}, mode => $self->{mode_name}); + } else { + $self->{output}->add_option_msg(short_msg => "Need to specify '--mode' or '--dyn-mode' option."); + $self->{output}->option_exit(); } if (defined($options{help})) { From 12604165cc2270514b6e2682e18aaeaef16ba614 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Fri, 1 Nov 2013 12:59:12 +0100 Subject: [PATCH 123/458] + Add mode memory Linux --- .../lib/perl/centreon/plugins/perfdata.pm | 2 +- centreon/lib/perl/centreon/plugins/snmp.pm | 7 + .../lib/perl/plugins/os/linux/mode/memory.pm | 147 ++++++++++++++++++ centreon/lib/perl/plugins/os/linux/plugin.pm | 1 + .../plugins/snmp_standard/mode/storage.pm | 1 - 5 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 centreon/lib/perl/plugins/os/linux/mode/memory.pm diff --git a/centreon/lib/perl/centreon/plugins/perfdata.pm b/centreon/lib/perl/centreon/plugins/perfdata.pm index d52cbac38d9..89d6e6aa2a3 100644 --- a/centreon/lib/perl/centreon/plugins/perfdata.pm +++ b/centreon/lib/perl/centreon/plugins/perfdata.pm @@ -194,7 +194,7 @@ sub change_bytes { $unit = defined($options{network}) ? 'Mb' : 'MB'; } if (($options{value} / $divide) >= 1) { - $value = $options{value} / $divide; + $options{value} = $options{value} / $divide; $unit = defined($options{network}) ? 'Gb' : 'GB'; } return (sprintf("%.2f", $options{value}), $unit); diff --git a/centreon/lib/perl/centreon/plugins/snmp.pm b/centreon/lib/perl/centreon/plugins/snmp.pm index 2d3ff8d1d3a..ad772987bed 100644 --- a/centreon/lib/perl/centreon/plugins/snmp.pm +++ b/centreon/lib/perl/centreon/plugins/snmp.pm @@ -235,6 +235,8 @@ sub get_table { # $options{end} = string (example: '.1.2') my ($dont_quit) = (defined($options{dont_quit}) && $options{dont_quit} == 1) ? 1 : 0; + my ($nothing_quit) = (defined($options{nothing_quit}) && $options{nothing_quit} == 1) ? 1 : 0; + if (defined($options{start})) { $options{start} = $self->clean_oid($options{start}); } @@ -323,6 +325,11 @@ sub get_table { } } + if ($nothing_quit == 1 && scalar(keys %$results) == 0) { + $self->{output}->add_option_msg(short_msg => "SNMP Table Request: Cant get a single value."); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); + } + return (0, $results); } diff --git a/centreon/lib/perl/plugins/os/linux/mode/memory.pm b/centreon/lib/perl/plugins/os/linux/mode/memory.pm new file mode 100644 index 00000000000..6b26a670f6f --- /dev/null +++ b/centreon/lib/perl/plugins/os/linux/mode/memory.pm @@ -0,0 +1,147 @@ +package os::linux::mode::memory; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %oids_hrStorageTable = ( + 'hrstoragedescr' => '.1.3.6.1.2.1.25.2.3.1.3', + 'hrfsmountpoint' => '.1.3.6.1.2.1.25.3.8.1.2', + 'hrstoragetype' => '.1.3.6.1.2.1.25.2.3.1.2', +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + $self->{cached_memory_id} = undef; + $self->{buffer_memory_id} = undef; + $self->{physical_memory_id} = undef; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_hrStorageDescr = '.1.3.6.1.2.1.25.2.3.1.3'; + + my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); + + foreach my $key (keys %$result) { + next if ($key !~ /\.([0-9]+)$/); + my $oid = $1; + if ($result->{$key} =~ /^Physical memory$/i) { + $self->{physical_memory_id} = $oid; + } + if ($result->{$key} =~ /^Cached memory$/i) { + $self->{cached_memory_id} = $oid; + } + if ($result->{$key} =~ /^Memory buffers$/i) { + $self->{buffer_memory_id} = $oid; + } + } + + if (!defined($self->{physical_memory_id})) { + $self->{output}->add_option_msg(short_msg => "Cannot find physical memory informations."); + $self->{output}->option_exit(); + } + if (!defined($self->{cached_memory_id})) { + $self->{output}->add_option_msg(short_msg => "Cannot find cached memory informations."); + $self->{output}->option_exit(); + } + if (!defined($self->{buffer_memory_id})) { + $self->{output}->add_option_msg(short_msg => "Cannot find buffer memory informations."); + $self->{output}->option_exit(); + } + + my $oid_hrStorageAllocationUnits = '.1.3.6.1.2.1.25.2.3.1.4'; + my $oid_hrStorageSize = '.1.3.6.1.2.1.25.2.3.1.5'; + my $oid_hrStorageUsed = '.1.3.6.1.2.1.25.2.3.1.6'; + + $self->{snmp}->load(oids => [$oid_hrStorageAllocationUnits, $oid_hrStorageSize, $oid_hrStorageUsed], + instances => [$self->{physical_memory_id}, $self->{cached_memory_id}, $self->{buffer_memory_id}]); + $result = $self->{snmp}->get_leef(); + + my $cached_used = $result->{$oid_hrStorageUsed . "." . $self->{cached_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{cached_memory_id}}; + my $buffer_used = $result->{$oid_hrStorageUsed . "." . $self->{buffer_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{buffer_memory_id}}; + my $physical_used = $result->{$oid_hrStorageUsed . "." . $self->{physical_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{physical_memory_id}}; + my $nobuf_used = $physical_used - $buffer_used - $cached_used; + + my $total_size = $result->{$oid_hrStorageSize . "." . $self->{physical_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{physical_memory_id}}; + + my $prct_used = $nobuf_used * 100 / $total_size; + $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + + my ($nobuf_value, $nobuf_unit) = $self->{perfdata}->change_bytes(value => $nobuf_used); + my ($buffer_value, $buffer_unit) = $self->{perfdata}->change_bytes(value => $buffer_used); + my ($cached_value, $cached_unit) = $self->{perfdata}->change_bytes(value => $cached_used); + + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Ram used (-buffers/cache) %s (%.2f%%), Buffer: %s, Cached: %s", + $nobuf_value . " " . $nobuf_unit, $prct_used, + $buffer_value . " " . $buffer_unit, + $cached_value . " " . $cached_unit)); + + $self->{output}->perfdata_add(label => "cached", + value => $cached_used, + min => 0); + $self->{output}->perfdata_add(label => "buffer", + value => $buffer_used, + min => 0); + $self->{output}->perfdata_add(label => "used", + value => $nobuf_used, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $total_size), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $total_size), + min => 0, max => $total_size); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check Linux physical memory. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/os/linux/plugin.pm b/centreon/lib/perl/plugins/os/linux/plugin.pm index 4d22cbf79da..c90b4890cf8 100644 --- a/centreon/lib/perl/plugins/os/linux/plugin.pm +++ b/centreon/lib/perl/plugins/os/linux/plugin.pm @@ -15,6 +15,7 @@ sub new { 'cpu' => 'snmp_standard::mode::cpu', 'load' => 'snmp_standard::mode::loadaverage', 'processcount' => 'snmp_standard::mode::processcount', + 'memory' => 'os::linux::mode::memory', 'storage' => 'snmp_standard::mode::storage', 'traffic' => 'snmp_standard::mode::traffic', 'uptime' => 'snmp_standard::mode::uptime', diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm index 3541eaeb111..ac3f090f8a8 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm @@ -7,7 +7,6 @@ use warnings; use centreon::plugins::statefile; use Digest::MD5 qw(md5_hex); -my @operstatus = ("up", "down", "testing", "unknown", "dormant", "notPresent", "lowerLayerDown"); my %oids_hrStorageTable = ( 'hrstoragedescr' => '.1.3.6.1.2.1.25.2.3.1.3', 'hrfsmountpoint' => '.1.3.6.1.2.1.25.3.8.1.2', From cad4b991f8129e5adec9b49749648f6a33f10639 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Fri, 1 Nov 2013 13:39:28 +0100 Subject: [PATCH 124/458] + Add mode linux swap --- .../lib/perl/plugins/os/linux/mode/memory.pm | 6 - .../lib/perl/plugins/os/linux/mode/swap.pm | 115 ++++++++++++++++++ centreon/lib/perl/plugins/os/linux/plugin.pm | 3 +- 3 files changed, 117 insertions(+), 7 deletions(-) create mode 100644 centreon/lib/perl/plugins/os/linux/mode/swap.pm diff --git a/centreon/lib/perl/plugins/os/linux/mode/memory.pm b/centreon/lib/perl/plugins/os/linux/mode/memory.pm index 6b26a670f6f..79c168279fc 100644 --- a/centreon/lib/perl/plugins/os/linux/mode/memory.pm +++ b/centreon/lib/perl/plugins/os/linux/mode/memory.pm @@ -5,12 +5,6 @@ use base qw(centreon::plugins::mode); use strict; use warnings; -my %oids_hrStorageTable = ( - 'hrstoragedescr' => '.1.3.6.1.2.1.25.2.3.1.3', - 'hrfsmountpoint' => '.1.3.6.1.2.1.25.3.8.1.2', - 'hrstoragetype' => '.1.3.6.1.2.1.25.2.3.1.2', -); - sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options); diff --git a/centreon/lib/perl/plugins/os/linux/mode/swap.pm b/centreon/lib/perl/plugins/os/linux/mode/swap.pm new file mode 100644 index 00000000000..dd3b6d1c371 --- /dev/null +++ b/centreon/lib/perl/plugins/os/linux/mode/swap.pm @@ -0,0 +1,115 @@ +package os::linux::mode::swap; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + $self->{swap_memory_id} = undef; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_hrStorageDescr = '.1.3.6.1.2.1.25.2.3.1.3'; + + my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); + + foreach my $key (keys %$result) { + next if ($key !~ /\.([0-9]+)$/); + my $oid = $1; + if ($result->{$key} =~ /^Swap space$/i) { + $self->{swap_memory_id} = $oid; + } + } + + if (!defined($self->{swap_memory_id})) { + $self->{output}->add_option_msg(short_msg => "Cannot find swap space informations."); + $self->{output}->option_exit(); + } + + my $oid_hrStorageAllocationUnits = '.1.3.6.1.2.1.25.2.3.1.4'; + my $oid_hrStorageSize = '.1.3.6.1.2.1.25.2.3.1.5'; + my $oid_hrStorageUsed = '.1.3.6.1.2.1.25.2.3.1.6'; + + $self->{snmp}->load(oids => [$oid_hrStorageAllocationUnits, $oid_hrStorageSize, $oid_hrStorageUsed], + instances => [$self->{swap_memory_id}]); + $result = $self->{snmp}->get_leef(); + + my $swap_used = $result->{$oid_hrStorageUsed . "." . $self->{swap_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{swap_memory_id}}; + my $total_size = $result->{$oid_hrStorageSize . "." . $self->{swap_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{swap_memory_id}}; + + my $prct_used = $swap_used * 100 / $total_size; + $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + + my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $total_size); + my ($swap_used_value, $swap_used_unit) = $self->{perfdata}->change_bytes(value => $swap_used); + my ($swap_free_value, $swap_free_unit) = $self->{perfdata}->change_bytes(value => ($total_size - $swap_used)); + + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Swap Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", + $total_value . " " . $total_unit, + $swap_used_value . " " . $swap_used_unit, $prct_used, + $swap_free_value . " " . $swap_free_unit, (100 - $prct_used))); + + $self->{output}->perfdata_add(label => "used", + value => $swap_used, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $total_size), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $total_size), + min => 0, max => $total_size); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check Linux swap memory. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/os/linux/plugin.pm b/centreon/lib/perl/plugins/os/linux/plugin.pm index c90b4890cf8..1a7248023d4 100644 --- a/centreon/lib/perl/plugins/os/linux/plugin.pm +++ b/centreon/lib/perl/plugins/os/linux/plugin.pm @@ -14,9 +14,10 @@ sub new { %{$self->{modes}} = ( 'cpu' => 'snmp_standard::mode::cpu', 'load' => 'snmp_standard::mode::loadaverage', - 'processcount' => 'snmp_standard::mode::processcount', 'memory' => 'os::linux::mode::memory', + 'processcount' => 'snmp_standard::mode::processcount', 'storage' => 'snmp_standard::mode::storage', + 'swap' => 'os::linux::mode::swap', 'traffic' => 'snmp_standard::mode::traffic', 'uptime' => 'snmp_standard::mode::uptime', ); From c042abc3335cf87e5f9ffcc497500d9a46e21b75 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sat, 2 Nov 2013 13:04:38 +0100 Subject: [PATCH 125/458] + Fix centos/rhel init scripts + Add mode swap and memory for Windows --- .../perl/plugins/os/windows/mode/memory.pm | 115 ++++++++++++++++++ .../lib/perl/plugins/os/windows/mode/swap.pm | 115 ++++++++++++++++++ .../lib/perl/plugins/os/windows/plugin.pm | 2 + 3 files changed, 232 insertions(+) create mode 100644 centreon/lib/perl/plugins/os/windows/mode/memory.pm create mode 100644 centreon/lib/perl/plugins/os/windows/mode/swap.pm diff --git a/centreon/lib/perl/plugins/os/windows/mode/memory.pm b/centreon/lib/perl/plugins/os/windows/mode/memory.pm new file mode 100644 index 00000000000..791e243036b --- /dev/null +++ b/centreon/lib/perl/plugins/os/windows/mode/memory.pm @@ -0,0 +1,115 @@ +package os::windows::mode::memory; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + $self->{physical_memory_id} = undef; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_hrStorageDescr = '.1.3.6.1.2.1.25.2.3.1.3'; + + my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); + + foreach my $key (keys %$result) { + next if ($key !~ /\.([0-9]+)$/); + my $oid = $1; + if ($result->{$key} =~ /^Physical memory$/i) { + $self->{physical_memory_id} = $oid; + } + } + + if (!defined($self->{physical_memory_id})) { + $self->{output}->add_option_msg(short_msg => "Cannot find physical memory informations."); + $self->{output}->option_exit(); + } + + my $oid_hrStorageAllocationUnits = '.1.3.6.1.2.1.25.2.3.1.4'; + my $oid_hrStorageSize = '.1.3.6.1.2.1.25.2.3.1.5'; + my $oid_hrStorageUsed = '.1.3.6.1.2.1.25.2.3.1.6'; + + $self->{snmp}->load(oids => [$oid_hrStorageAllocationUnits, $oid_hrStorageSize, $oid_hrStorageUsed], + instances => [$self->{physical_memory_id}]); + $result = $self->{snmp}->get_leef(); + + my $physical_used = $result->{$oid_hrStorageUsed . "." . $self->{physical_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{physical_memory_id}}; + my $total_size = $result->{$oid_hrStorageSize . "." . $self->{physical_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{physical_memory_id}}; + + my $prct_used = $physical_used * 100 / $total_size; + $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + + my ($physical_used_value, $physical_used_unit) = $self->{perfdata}->change_bytes(value => $physical_used); + my ($physical_free_value, $physical_free_unit) = $self->{perfdata}->change_bytes(value => $total_size - $physical_used); + my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $total_size); + + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("RAM Total: %s Used: %s (%.2f%%) Free: %s (%d%%)", + $total_value . " " . $total_unit, + $physical_used_value . " " . $physical_used_unit, $prct_used, + $physical_free_value . " " . $physical_free_unit, 100 - $prct_used)); + + $self->{output}->perfdata_add(label => "used", + value => $physical_used, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $total_size), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $total_size), + min => 0, max => $total_size); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check Windows physical memory. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/os/windows/mode/swap.pm b/centreon/lib/perl/plugins/os/windows/mode/swap.pm new file mode 100644 index 00000000000..639fb0855db --- /dev/null +++ b/centreon/lib/perl/plugins/os/windows/mode/swap.pm @@ -0,0 +1,115 @@ +package os::windows::mode::swap; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + $self->{swap_memory_id} = undef; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_hrStorageDescr = '.1.3.6.1.2.1.25.2.3.1.3'; + + my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); + + foreach my $key (keys %$result) { + next if ($key !~ /\.([0-9]+)$/); + my $oid = $1; + if ($result->{$key} =~ /^Virtual memory$/i) { + $self->{swap_memory_id} = $oid; + } + } + + if (!defined($self->{swap_memory_id})) { + $self->{output}->add_option_msg(short_msg => "Cannot find physical memory informations."); + $self->{output}->option_exit(); + } + + my $oid_hrStorageAllocationUnits = '.1.3.6.1.2.1.25.2.3.1.4'; + my $oid_hrStorageSize = '.1.3.6.1.2.1.25.2.3.1.5'; + my $oid_hrStorageUsed = '.1.3.6.1.2.1.25.2.3.1.6'; + + $self->{snmp}->load(oids => [$oid_hrStorageAllocationUnits, $oid_hrStorageSize, $oid_hrStorageUsed], + instances => [$self->{swap_memory_id}]); + $result = $self->{snmp}->get_leef(); + + my $swap_used = $result->{$oid_hrStorageUsed . "." . $self->{swap_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{swap_memory_id}}; + my $total_size = $result->{$oid_hrStorageSize . "." . $self->{swap_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{swap_memory_id}}; + + my $prct_used = $swap_used * 100 / $total_size; + $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + + my ($swap_used_value, $swap_used_unit) = $self->{perfdata}->change_bytes(value => $swap_used); + my ($swap_free_value, $swap_free_unit) = $self->{perfdata}->change_bytes(value => $total_size - $swap_used); + my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $total_size); + + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Swap Total: %s Used: %s (%.2f%%) Free: %s (%d%%)", + $total_value . " " . $total_unit, + $swap_used_value . " " . $swap_used_unit, $prct_used, + $swap_free_value . " " . $swap_free_unit, 100 - $prct_used)); + + $self->{output}->perfdata_add(label => "used", + value => $swap_used, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $total_size), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $total_size), + min => 0, max => $total_size); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check Windows swap memory. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/os/windows/plugin.pm b/centreon/lib/perl/plugins/os/windows/plugin.pm index 0a28371425e..9405a35075b 100644 --- a/centreon/lib/perl/plugins/os/windows/plugin.pm +++ b/centreon/lib/perl/plugins/os/windows/plugin.pm @@ -14,8 +14,10 @@ sub new { %{$self->{modes}} = ( 'cpu' => 'snmp_standard::mode::cpu', 'load' => 'snmp_standard::mode::loadaverage', + 'memory' => 'os::windows::mode::memory', 'processcount' => 'snmp_standard::mode::processcount', 'storage' => 'snmp_standard::mode::storage', + 'swap' => 'os::windows::mode::swap', 'traffic' => 'snmp_standard::mode::traffic', 'uptime' => 'snmp_standard::mode::uptime', ); From be1028bed574b16b085a3361301c43d750540a92 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sun, 3 Nov 2013 00:36:36 +0100 Subject: [PATCH 126/458] + Add mode diskio snmp_standard --- centreon/lib/perl/plugins/os/linux/plugin.pm | 2 +- .../perl/plugins/snmp_standard/mode/diskio.pm | 316 ++++++++++++++++++ .../plugins/snmp_standard/mode/storage.pm | 2 +- .../plugins/snmp_standard/mode/traffic.pm | 2 +- 4 files changed, 319 insertions(+), 3 deletions(-) create mode 100644 centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm diff --git a/centreon/lib/perl/plugins/os/linux/plugin.pm b/centreon/lib/perl/plugins/os/linux/plugin.pm index 1a7248023d4..810dc51ebf0 100644 --- a/centreon/lib/perl/plugins/os/linux/plugin.pm +++ b/centreon/lib/perl/plugins/os/linux/plugin.pm @@ -13,6 +13,7 @@ sub new { $self->{version} = '0.1'; %{$self->{modes}} = ( 'cpu' => 'snmp_standard::mode::cpu', + 'diskio' => 'snmp_standard::mode::diskio', 'load' => 'snmp_standard::mode::loadaverage', 'memory' => 'os::linux::mode::memory', 'processcount' => 'snmp_standard::mode::processcount', @@ -21,7 +22,6 @@ sub new { 'traffic' => 'snmp_standard::mode::traffic', 'uptime' => 'snmp_standard::mode::uptime', ); - #$self->{default} = { traffic => { warning => '-1'} }; return $self; } diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm b/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm new file mode 100644 index 00000000000..f30ccf5a3fa --- /dev/null +++ b/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm @@ -0,0 +1,316 @@ +package snmp_standard::mode::diskio; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; +use Digest::MD5 qw(md5_hex); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning-read:s" => { name => 'warning_read' }, + "critical-read:s" => { name => 'critical_read' }, + "warning-write:s" => { name => 'warning_write' }, + "critical-write:s" => { name => 'critical_write' }, + "reload-cache-time:s" => { name => 'reload_cache_time' }, + "name" => { name => 'use_name' }, + "device:s" => { name => 'device' }, + "regexp" => { name => 'use_regexp' }, + "regexp-isensitive" => { name => 'use_regexpi' }, + "show-cache" => { name => 'show_cache' }, + }); + + $self->{device_id_selected} = []; + $self->{statefile_cache} = centreon::plugins::statefile->new(%options); + $self->{statefile_value} = centreon::plugins::statefile->new(%options); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning-read', value => $self->{option_results}->{warning_read})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'read' threshold '" . $self->{option_results}->{warning_read} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical-read', value => $self->{option_results}->{critical_read})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'read' threshold '" . $self->{option_results}->{critical_read} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warning-write', value => $self->{option_results}->{warning_write})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'write' threshold '" . $self->{option_results}->{warning_write} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical-write', value => $self->{option_results}->{critical_write})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'write' threshold '" . $self->{option_results}->{critical_write} . "'."); + $self->{output}->option_exit(); + } + + $self->{statefile_cache}->check_options(%options); + $self->{statefile_value}->check_options(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + if ($self->{snmp}->is_snmpv1()) { + $self->{output}->add_option_msg(short_msg => "Need to use SNMP v2c or v3."); + $self->{output}->option_exit(); + } + + $self->{hostname} = $self->{snmp}->get_hostname(); + + $self->manage_selection(); + + my $oid_diskIODevice = '.1.3.6.1.4.1.2021.13.15.1.1.2'; + my $oid_diskIONReadX = '.1.3.6.1.4.1.2021.13.15.1.1.12'; # in B + my $oid_diskIONWrittenX = '.1.3.6.1.4.1.2021.13.15.1.1.13'; # in B + + my $new_datas = {}; + $self->{statefile_value}->read(statefile => $self->{hostname} . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{device}) ? md5_hex($self->{option_results}->{device}) : md5_hex('all'))); + + $self->{snmp}->load(oids => [$oid_diskIONReadX, $oid_diskIONWrittenX], + instances => $self->{device_id_selected}); + my $result = $self->{snmp}->get_leef(); + $new_datas->{last_timestamp} = time(); + my $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); + if (!defined($self->{option_results}->{device}) || defined($self->{option_results}->{use_regexp})) { + $self->{output}->output_add(severity => 'OK', + short_msg => 'All devices are ok.'); + } + + foreach (sort @{$self->{device_id_selected}}) { + my $device_name = $self->{statefile_cache}->get(name => "device_" . $_); + + if ($result->{$oid_diskIONReadX . "." . $_} == 0 && $result->{$oid_diskIONWrittenX . "." . $_} == 0 && + (!defined($self->{option_results}->{device}) || defined($self->{option_results}->{use_regexp}))) { + $self->{output}->add_option_msg(long_msg => "Skip device '" . $device_name . "' with no values."); + next; + } + + $new_datas->{'readio_' . $_} = $result->{$oid_diskIONReadX . "." . $_}; + $new_datas->{'writeio_' . $_} = $result->{$oid_diskIONWrittenX . "." . $_}; + + my $old_readio = $self->{statefile_value}->get(name => 'readio_' . $_); + my $old_writeio = $self->{statefile_value}->get(name => 'writeio_' . $_); + if (!defined($old_timestamp) || !defined($old_readio) || !defined($old_writeio)) { + next; + } + if ($new_datas->{'readio_' . $_} < $old_readio) { + # We set 0. Has reboot. + $old_readio = 0; + } + if ($new_datas->{'writeio_' . $_} < $old_writeio) { + # We set 0. Has reboot. + $old_writeio = 0; + } + + my $time_delta = $new_datas->{last_timestamp} - $old_timestamp; + if ($time_delta <= 0) { + # At least one second. two fast calls ;) + $time_delta = 1; + } + + my $readio_absolute_per_sec = ($new_datas->{'readio_' . $_} - $old_readio) / $time_delta; + my $writeio_absolute_per_sec = ($new_datas->{'writeio_' . $_} - $old_writeio) / $time_delta; + + ########### + # Manage Output + ########### + my $exit1 = $self->{perfdata}->threshold_check(value => $readio_absolute_per_sec, threshold => [ { label => 'critical-read', 'exit_litteral' => 'critical' }, { label => 'warning-read', exit_litteral => 'warning' } ]); + my $exit2 = $self->{perfdata}->threshold_check(value => $writeio_absolute_per_sec, threshold => [ { label => 'critical-write', 'exit_litteral' => 'critical' }, { label => 'warning-write', exit_litteral => 'warning' } ]); + + my ($readio_value, $readio_unit) = $self->{perfdata}->change_bytes(value => $readio_absolute_per_sec); + my ($writeio_value, $writeio_unit) = $self->{perfdata}->change_bytes(value => $writeio_absolute_per_sec); + my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2 ]); + $self->{output}->output_add(long_msg => sprintf("Device '%s' Read I/O : %s/s, Write I/O : %s/s", $device_name, + $readio_value . $readio_unit, + $writeio_value . $writeio_unit)); + if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1) || (defined($self->{option_results}->{device}) && !defined($self->{option_results}->{use_regexp}))) { + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Device '%s' Read I/O : %s/s, Write I/O : %s/s", $device_name, + $readio_value . $readio_unit, + $writeio_value . $writeio_unit)); + } + + my $extra_label = ''; + $extra_label = '_' . $device_name if (!defined($self->{option_results}->{device}) || defined($self->{option_results}->{use_regexp})); + $self->{output}->perfdata_add(label => 'readio' . $extra_label, unit => 'b/s', + value => sprintf("%.2f", $readio_absolute_per_sec), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-read'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-read'), + min => 0); + $self->{output}->perfdata_add(label => 'writeio' . $extra_label, unit => 'b/s', + value => sprintf("%.2f", $writeio_absolute_per_sec), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-write'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-write'), + min => 0); + } + + $self->{statefile_value}->write(data => $new_datas); + if (!defined($old_timestamp)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub reload_cache { + my ($self) = @_; + my $datas = {}; + + my $oid_diskIODevice = '.1.3.6.1.4.1.2021.13.15.1.1.2'; + my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_diskIODevice); + my $last_num = 0; + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($key !~ /\.([0-9]+)$/); + $datas->{"device_" . $1} = $result->{$key}; + $last_num = $1; + } + + if (scalar(keys %$datas) <= 0) { + $self->{output}->add_option_msg(short_msg => "Can't construct cache..."); + $self->{output}->option_exit(); + } + + $datas->{total_device} = $last_num; + $self->{statefile_cache}->write(data => $datas); +} + +sub manage_selection { + my ($self, %options) = @_; + + # init cache file + my $has_cache_file = $self->{statefile_cache}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + if (defined($self->{option_results}->{show_cache})) { + $self->{output}->add_option_msg(long_msg => $self->{statefile_cache}->get_string_content()); + $self->{output}->option_exit(); + } + + my $timestamp_cache = $self->{statefile_cache}->get(name => 'last_timestamp'); + if ($has_cache_file == 0 || + (defined($timestamp_cache) && (time() - $timestamp_cache) > (($self->{option_results}->{reload_cache_time}) * 60))) { + $self->reload_cache(); + $self->{statefile_cache}->read(); + } + + my $total_device = $self->{statefile_cache}->get(name => 'total_device'); + if (!defined($self->{option_results}->{use_name}) && defined($self->{option_results}->{device})) { + # get by ID + push @{$self->{device_id_selected}}, $self->{option_results}->{device}; + my $name = $self->{statefile_cache}->get(name => "device_" . $self->{option_results}->{device}); + if (!defined($name)) { + $self->{output}->add_option_msg(short_msg => "No device for id '" . $self->{option_results}->{device} . "'."); + $self->{output}->option_exit(); + } + } else { + for (my $i = 0; $i <= $total_device; $i++) { + my $filter_name = $self->{statefile_cache}->get(name => "device_" . $i); + next if (!defined($filter_name)); + if (!defined($self->{option_results}->{device})) { + push @{$self->{device_id_selected}}, $i; + next; + } + if (defined($self->{option_results}->{use_regexp}) && defined($self->{option_results}->{use_regexpi}) && $filter_name =~ /$self->{option_results}->{device}/i) { + push @{$self->{device_id_selected}}, $i; + } + if (defined($self->{option_results}->{use_regexp}) && !defined($self->{option_results}->{use_regexpi}) && $filter_name =~ /$self->{option_results}->{device}/) { + push @{$self->{device_id_selected}}, $i; + } + if (!defined($self->{option_results}->{use_regexp}) && !defined($self->{option_results}->{use_regexpi}) && $filter_name eq $self->{option_results}->{device}) { + push @{$self->{device_id_selected}}, $i; + } + } + + if (scalar(@{$self->{device_id_selected}}) <= 0) { + $self->{output}->add_option_msg(short_msg => "No device found for name '" . $self->{option_results}->{device} . "' (maybe you should reload cache file)."); + $self->{output}->option_exit(); + } + } +} + +sub disco_format { + my ($self, %options) = @_; + + $self->{output}->add_disco_format(elements => ['name', 'deviceid']); +} + +sub disco_show { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + $self->{hostname} = $self->{snmp}->get_hostname(); + + $self->manage_selection(); + foreach (sort @{$self->{device_id_selected}}) { + $self->{output}->add_disco_entry(name => $self->{statefile_cache}->get(name => "device_" . $_), + deviceid => $_); + } +} + +1; + +__END__ + +=head1 MODE + +Check read/write I/O disks. + +=over 8 + +=item B<--warning-read> + +Threshold warning in bytes for 'read' io disks. + +=item B<--critical-read> + +Threshold critical in bytes for 'read' io disks. + +=item B<--warning-write> + +Threshold warning in bytes for 'write' io disks. + +=item B<--critical-write> + +Threshold critical in bytes for 'write' io disks. + +=item B<--device> + +Set the device (number expected) ex: 1, 2,... (empty means 'check all devices'). + +=item B<--name> + +Allows to use device name with option --device instead of devoce oid index. + +=item B<--regexp> + +Allows to use regexp to filter devices (with option --name). + +=item B<--regexp-isensitive> + +Allows to use regexp non case-sensitive (with --regexp). + +=item B<--reload-cache-time> + +Time in seconds before reloading cache file (default: 180). + +=item B<--show-cache> + +Display cache interface datas. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm index ac3f090f8a8..4af2e3b0b03 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm @@ -246,7 +246,7 @@ sub manage_selection { } } - if (scalar(@{$self->{storage_id_selected}}) < 0) { + if (scalar(@{$self->{storage_id_selected}}) <= 0) { $self->{output}->add_option_msg(short_msg => "No storage found for name '" . $self->{option_results}->{storage} . "' (maybe you should reload cache file)."); $self->{output}->option_exit(); } diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index eb01e8c89c4..731bf226ff0 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -326,7 +326,7 @@ sub manage_selection { } } - if (scalar(@{$self->{interface_id_selected}}) < 0) { + if (scalar(@{$self->{interface_id_selected}}) <= 0) { $self->{output}->add_option_msg(short_msg => "No interface found for name '" . $self->{option_results}->{interface} . "' (maybe you should reload cache file)."); $self->{output}->option_exit(); } From 775160f844230adf533766523d319ad87572c67a Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sun, 3 Nov 2013 00:43:29 +0100 Subject: [PATCH 127/458] + Fix modules example --- centreon/lib/perl/plugins/example/mode/getvalue.pm | 2 +- centreon/lib/perl/plugins/example/mode/launchcmd.pm | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/centreon/lib/perl/plugins/example/mode/getvalue.pm b/centreon/lib/perl/plugins/example/mode/getvalue.pm index 463b845357a..551b621e9ab 100644 --- a/centreon/lib/perl/plugins/example/mode/getvalue.pm +++ b/centreon/lib/perl/plugins/example/mode/getvalue.pm @@ -1,4 +1,4 @@ -package plugin::example::mode::getvalue; +package example::mode::getvalue; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/example/mode/launchcmd.pm b/centreon/lib/perl/plugins/example/mode/launchcmd.pm index d24bf6f84c5..7d573dfdbd0 100644 --- a/centreon/lib/perl/plugins/example/mode/launchcmd.pm +++ b/centreon/lib/perl/plugins/example/mode/launchcmd.pm @@ -1,4 +1,4 @@ -package plugin::example::mode::launchcmd; +package example::mode::launchcmd; use base qw(centreon::plugins::mode); From 9e369e3848989d0c06ed5d61fb21ebf442582f2e Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 6 Nov 2013 23:53:56 +0100 Subject: [PATCH 128/458] + Add bluecoat plugin and modes --- .../bluecoat/mode/clientconnections.pm | 88 ++++++++++ .../network/bluecoat/mode/clientrequests.pm | 162 ++++++++++++++++++ .../network/bluecoat/mode/clienttraffic.pm | 146 ++++++++++++++++ .../perl/plugins/network/bluecoat/mode/cpu.pm | 122 +++++++++++++ .../plugins/network/bluecoat/mode/disk.pm | 90 ++++++++++ .../plugins/network/bluecoat/mode/hardware.pm | 131 ++++++++++++++ .../plugins/network/bluecoat/mode/memory.pm | 104 +++++++++++ .../bluecoat/mode/serverconnections.pm | 88 ++++++++++ .../perl/plugins/network/bluecoat/plugin.pm | 36 ++++ 9 files changed, 967 insertions(+) create mode 100644 centreon/lib/perl/plugins/network/bluecoat/mode/clientconnections.pm create mode 100644 centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm create mode 100644 centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm create mode 100644 centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm create mode 100644 centreon/lib/perl/plugins/network/bluecoat/mode/disk.pm create mode 100644 centreon/lib/perl/plugins/network/bluecoat/mode/hardware.pm create mode 100644 centreon/lib/perl/plugins/network/bluecoat/mode/memory.pm create mode 100644 centreon/lib/perl/plugins/network/bluecoat/mode/serverconnections.pm create mode 100644 centreon/lib/perl/plugins/network/bluecoat/plugin.pm diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/clientconnections.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/clientconnections.pm new file mode 100644 index 00000000000..8d227100d80 --- /dev/null +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/clientconnections.pm @@ -0,0 +1,88 @@ +package network::bluecoat::mode::clientconnections; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my ($exit, $result) = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.3.1.0', + '.1.3.6.1.4.1.3417.2.11.3.1.3.2.0', + '.1.3.6.1.4.1.3417.2.11.3.1.3.3.0'], nothing_quit => 1); + my $client_connections = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.1.0'}; + my $client_connections_active = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.2.0'}; + my $client_connections_idle = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.3.0'}; + + $exit = $self->{perfdata}->threshold_check(value => $client_connections_active, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit, + short_msg => "Client connections: Active " . $client_connections_active . ", Idle " . $client_connections_idle); + $self->{output}->perfdata_add(label => 'con', + value => $client_connections, + min => 0); + $self->{output}->perfdata_add(label => 'con_active', + value => $client_connections_active, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + $self->{output}->perfdata_add(label => 'con_idle', + value => $client_connections_idle, + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check current client connections. + +=over 8 + +=item B<--warning> + +Threshold warning (on active connections). + +=item B<--critical> + +Threshold critical (on active connections. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm new file mode 100644 index 00000000000..2026991d83b --- /dev/null +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm @@ -0,0 +1,162 @@ +package network::bluecoat::mode::clientrequests; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning-errors:s" => { name => 'warning_errors' }, + "critical-errors:s" => { name => 'critical_errors' }, + "warning-misses:s" => { name => 'warning_misses' }, + "critical-misses:s" => { name => 'critical_misses' }, + }); + $self->{statefile_value} = centreon::plugins::statefile->new(%options); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning_errors', value => $self->{option_results}->{warning_errors})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'errors' threshold '" . $self->{option_results}->{warning_errors} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical_errors', value => $self->{option_results}->{critical_errors})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'errors' threshold '" . $self->{option_results}->{critical_errors} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warning_misses', value => $self->{option_results}->{warning_misses})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'misses' threshold '" . $self->{option_results}->{warning_misses} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical_misses', value => $self->{option_results}->{critical_misses})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'misses' threshold '" . $self->{option_results}->{critical_misses} . "'."); + $self->{output}->option_exit(); + } + + $self->{statefile_value}->check_options(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + $self->{hostname} = $self->{snmp}->get_hostname(); + + if ($self->{snmp}->is_snmpv1()) { + $self->{output}->add_option_msg(short_msg => "Need to use SNMP v2c or v3."); + $self->{output}->option_exit(); + } + + $self->{statefile_value}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + my ($exit, $result) = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.1.1.0', + '.1.3.6.1.4.1.3417.2.11.3.1.1.2.0', + '.1.3.6.1.4.1.3417.2.11.3.1.1.3.0', + '.1.3.6.1.4.1.3417.2.11.3.1.1.4.0', + '.1.3.6.1.4.1.3417.2.11.3.1.1.5.0'], nothing_quit => 1); + + my $new_datas = {}; + my $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); + my $old_client_http_requests = $self->{statefile_value}->get(name => 'client_http_requests'); + my $old_client_http_hits = $self->{statefile_value}->get(name => 'client_http_hits'); + my $old_client_http_partial_hits = $self->{statefile_value}->get(name => 'client_http_partial_hits'); + my $old_client_http_misses = $self->{statefile_value}->get(name => 'client_http_misses'); + my $old_client_http_errors = $self->{statefile_value}->get(name => 'client_http_errors'); + + $new_datas->{last_timestamp} = time(); + $new_datas->{client_http_requests} = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.1.1.0'}; + $new_datas->{client_http_hits} = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.1.2.0'}; + $new_datas->{client_http_partial_hits} = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.1.3.0'}; + $new_datas->{client_http_misses} = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.1.4.0'}; + $new_datas->{client_http_errors} = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.1.5.0'}; + + $self->{statefile_value}->write(data => $new_datas); + + if (!defined($old_timestamp) || !defined($old_client_http_misses)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + $self->{output}->exit(); + } + + if ($new_datas->{client_http_requests} < $old_client_http_requests) { + # We set 0. Has reboot. + $old_client_http_requests = 0; + $old_client_http_hits = 0; + $old_client_http_partial_hits = 0; + $old_client_http_misses = 0; + $old_client_http_errors = 0; + } + + my $delta_http_requests = $new_datas->{client_http_requests} - $old_client_http_requests; + my $prct_misses = sprintf("%.2f", ($new_datas->{client_http_misses} - $old_client_http_misses) * 100 / $delta_http_requests); + my $prct_hits = sprintf("%.2f", ($new_datas->{client_http_hits} - $old_client_http_hits) * 100 / $delta_http_requests); + my $prct_partial_hits = sprintf("%.2f", ($new_datas->{client_http_partial_hits} - $old_client_http_partial_hits) * 100 / $delta_http_requests); + my $prct_errors = sprintf("%.2f", ($new_datas->{client_http_errors} - $old_client_http_errors) * 100 / $delta_http_requests); + + my $exit1 = $self->{perfdata}->threshold_check(value => $prct_errors, threshold => [ { label => 'critical_errors', 'exit_litteral' => 'critical' }, { label => 'warning_errors', exit_litteral => 'warning' } ]); + my $exit2 = $self->{perfdata}->threshold_check(value => $prct_misses, threshold => [ { label => 'critical_misses', 'exit_litteral' => 'critical' }, { label => 'warning_misses', exit_litteral => 'warning' } ]); + $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2 ]); + + $self->{output}->output_add(severity => $exit, + short_msg => "Client Requests: Hits = $prct_hits%, Partial Hits = $prct_partial_hits%, Misses = $prct_misses%, Errors = $prct_errors%"); + $self->{output}->perfdata_add(label => 'hits', unit => '%', + value => $prct_hits, + min => 0); + $self->{output}->perfdata_add(label => 'partial_hits', unit => '%', + value => $prct_partial_hits, + min => 0); + $self->{output}->perfdata_add(label => 'misses', unit => '%', + value => $prct_misses, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_misses'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_misses'), + min => 0); + $self->{output}->perfdata_add(label => 'errors', unit => '%', + value => $prct_errors, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_errors'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_errors'), + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check http client requests (in percent by type: hit, partial, misses, errors) + +=over 8 + +=item B<--warning-errors> + +Threshold warning of client http errors in percent. + +=item B<--critical-errors> + +Threshold critical of client http errors in percent. + +=item B<--warning-misses> + +Threshold warning of client http misses in percent. + +=item B<--critical-misses> + +Threshold critial of client http misses in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm new file mode 100644 index 00000000000..f14c0aba898 --- /dev/null +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm @@ -0,0 +1,146 @@ +package network::bluecoat::mode::clienttraffic; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning-received:s" => { name => 'warning_received' }, + "critical-received:s" => { name => 'critical_received' }, + "warning-delivered:s" => { name => 'warning_delivered' }, + "critical-delivered:s" => { name => 'critical_delivered' }, + }); + $self->{statefile_value} = centreon::plugins::statefile->new(%options); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning_received', value => $self->{option_results}->{warning_received})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'received' threshold '" . $self->{option_results}->{warning_received} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical_received', value => $self->{option_results}->{critical_received})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'received' threshold '" . $self->{option_results}->{critical_received} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warning_delivered', value => $self->{option_results}->{warning_delivered})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'delivered' threshold '" . $self->{option_results}->{warning_delivered} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical_delivered', value => $self->{option_results}->{critical_delivered})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'delivered' threshold '" . $self->{option_results}->{critical_delivered} . "'."); + $self->{output}->option_exit(); + } + + $self->{statefile_value}->check_options(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + $self->{hostname} = $self->{snmp}->get_hostname(); + + if ($self->{snmp}->is_snmpv1()) { + $self->{output}->add_option_msg(short_msg => "Need to use SNMP v2c or v3."); + $self->{output}->option_exit(); + } + + $self->{statefile_value}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + + my ($exit, $result) = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.1.9.0', + '.1.3.6.1.4.1.3417.2.11.3.1.1.10.0'], nothing_quit => 1); + + my $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); + my $old_client_in_bytes = $self->{statefile_value}->get(name => 'client_in_bytes'); + my $old_client_out_bytes = $self->{statefile_value}->get(name => 'client_out_bytes'); + + my $new_datas = {}; + $new_datas->{last_timestamp} = time(); + $new_datas->{client_in_bytes} = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.1.9.0'}; + $new_datas->{client_out_bytes} = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.1.10.0'}; + + $self->{statefile_value}->write(data => $new_datas); + + if (!defined($old_timestamp) || !defined($old_client_in_bytes)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + $self->{output}->exit(); + } + + if ($new_datas->{client_in_bytes} < $old_client_in_bytes) { + # We set 0. Has reboot. + $old_client_in_bytes = 0; + $old_client_out_bytes = 0; + } + + my $delta_time = $new_datas->{last_timestamp} - $old_timestamp; + my $in_bytes_sec = sprintf("%.2f", ($new_datas->{client_in_bytes} - $old_client_in_bytes) / $delta_time); + my $out_bytes_sec = sprintf("%.2f", ($new_datas->{client_out_bytes} - $old_client_out_bytes) / $delta_time); + + my $exit1 = $self->{perfdata}->threshold_check(value => $in_bytes_sec, threshold => [ { label => 'critical_received', 'exit_litteral' => 'critical' }, { label => 'warning_received', exit_litteral => 'warning' } ]); + my $exit2 = $self->{perfdata}->threshold_check(value => $out_bytes_sec, threshold => [ { label => 'critical_delivered', 'exit_litteral' => 'critical' }, { label => 'warning_delivered', exit_litteral => 'warning' } ]); + $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2 ]); + + my ($value_in, $unit_in) = $self->{perfdata}->change_bytes(value => $in_bytes_sec); + my ($value_out, $unit_out) = $self->{perfdata}->change_bytes(value => $out_bytes_sec); + + $self->{output}->output_add(severity => $exit, + short_msg => "Traffic: In $value_in $unit_in/s, Out $value_out $unit_out/s"); + $self->{output}->perfdata_add(label => 'traffic_in', unit => 'B/s', + value => $in_bytes_sec, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_received'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_received'), + min => 0); + $self->{output}->perfdata_add(label => 'traffic_out', unit => 'B/s', + value => $out_bytes_sec, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning_delivered'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical_delivered'), + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check bytes/s received/delivered to clients + +=over 8 + +=item B<--warning-received> + +Threshold warning for received (in bytes/s). + +=item B<--critical-received> + +Threshold critical for received (in bytes/s). + +=item B<--warning-delivered> + +Threshold warning2 for delivered (in bytes/s). + +=item B<--critical-delivered> + +Threshold critical for delivered (in bytes/s). + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm new file mode 100644 index 00000000000..9a1df7a7328 --- /dev/null +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm @@ -0,0 +1,122 @@ +package network::bluecoat::mode::cpu; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + $self->{statefile_value} = centreon::plugins::statefile->new(%options); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } + + $self->{statefile_value}->check_options(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + $self->{hostname} = $self->{snmp}->get_hostname(); + + if ($self->{snmp}->is_snmpv1()) { + $self->{output}->add_option_msg(short_msg => "Need to use SNMP v2c or v3."); + $self->{output}->option_exit(); + } + + my $new_datas = {}; + my $old_timestamp = undef; + + $self->{statefile_value}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + + my ($exit, $result) = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.11.2.4.1', nothing_quit => 1); + $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); + $new_datas->{last_timestamp} = time(); + for (my $i = 1; defined($result->{'.1.3.6.1.4.1.3417.2.11.2.4.1.3.' . $i}); $i++) { + $new_datas->{'cpu_' . $i . '_busy'} = $result->{'.1.3.6.1.4.1.3417.2.11.2.4.1.3.' . $i}; + $new_datas->{'cpu_' . $i . '_idle'} = $result->{'.1.3.6.1.4.1.3417.2.11.2.4.1.4.' . $i}; + + if (!defined($old_timestamp)) { + next; + } + + my $old_cpu_busy = $self->{statefile_value}->get(name => 'cpu_' . $i . '_busy'); + my $old_cpu_idle = $self->{statefile_value}->get(name => 'cpu_' . $i . '_idle'); + if (!defined($old_cpu_busy) || !defined($old_cpu_idle)) { + next; + } + + if ($new_datas->{'cpu_' . $i . '_busy'} < $old_cpu_busy) { + # We set 0. Has reboot. + $old_cpu_busy = 0; + $old_cpu_idle = 0; + } + + my $total_elapsed = (($new_datas->{'cpu_' . $i . '_busy'} - $old_cpu_busy) + ($new_datas->{'cpu_' . $i . '_idle'} - $old_cpu_idle)); + my $prct_usage = (($new_datas->{'cpu_' . $i . '_busy'} - $old_cpu_busy) * 100 / ($total_elapsed)); + $exit = $self->{perfdata}->threshold_check(value => $prct_usage, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("CPU $i Usage is %.2f%%", $prct_usage)); + $self->{output}->perfdata_add(label => 'cpu_' . $i, unit => '%', + value => sprintf("%.2f", $prct_usage), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0, max => 100); + } + + $self->{statefile_value}->write(data => $new_datas); + if (!defined($old_timestamp)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check CPU Usage + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/disk.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/disk.pm new file mode 100644 index 00000000000..e89ef3b165d --- /dev/null +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/disk.pm @@ -0,0 +1,90 @@ +package network::bluecoat::mode::disk; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $disk_num = 1; + my ($exit, $result) = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.4.1.1.1'); + for (my $i = 1; defined($result->{'.1.3.6.1.4.1.3417.2.4.1.1.1.3.' . $i}); $i++) { + if ($result->{'.1.3.6.1.4.1.3417.2.4.1.1.1.3.' . $i} !~ /^DISK$/i) { + next; + } + + my $disk_usage = $result->{'.1.3.6.1.4.1.3417.2.4.1.1.1.4.' . $i}; + $exit = $self->{perfdata}->threshold_check(value => $disk_usage, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Disk $disk_num usage is %.2f%%", $disk_usage)); + $self->{output}->perfdata_add(label => 'disk_' . $disk_num, unit => '%', + value => sprintf("%.2f", $disk_usage), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0, max => 100); + $disk_num++; + } + + if ($disk_num == 1) { + $self->{output}->add_option_msg(short_msg => "No disk information found..."); + $self->{output}->option_exit(); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check disks usage. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/hardware.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/hardware.pm new file mode 100644 index 00000000000..41c36b87936 --- /dev/null +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/hardware.pm @@ -0,0 +1,131 @@ +package network::bluecoat::mode::hardware; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %device_status_msg = (2 => "unaivalable", 3 => "non operationnal"); +my %device_units = ( + 1 => '', # other + 2 => '', # truthvalue + 3 => '', # specialEnum + 4 => 'volts', + 5 => 'celsius', + 6 => 'rpm' + ); + my %device_code = ( + 1 => ["The device sensor '%s' is ok", 'OK'], 2 => ["The device sensor '%s' is unknown", 'UNKNOWN'], 3 => ["The device sensor '%s' is not installed", 'UNKNOWN'], + 4 => ["The device sensor '%s' has a low voltage", 'WARNING'], 5 => ["The device sensor '%s' has a low voltage", 'CRITICAL'], + 6 => ["The device sensor '%s' has no power", 'CRITICAL'], + 7 => ["The device sensor '%s' has a high voltage", 'WARNING'], + 8 => ["The device sensor '%s' has a high voltage", 'CRITICAL'], + 9 => ["The device sensor '%s' has a very (!!!) high voltage", 'CRITICAL'], + 10 => ["The device sensor '%s' has a high temperature", 'WARNING'], + 11 => ["The device sensor '%s' has a high temperature", 'CRITICAL'], + 12 => ["The device sensor '%s' has a very high (!!!) temperature", 'CRITICAL'], + 13 => ["The fan '%s' is slow", 'WARNING'], + 14 => ["The fan '%s' is slow", 'CRITICAL'], + 15 => ["The fan '%s' is stopped", 'CRITICAL'], + ); +my %disk_status = ( + 1 => ["Disk '%s' is present", 'OK'], 2 => ["Disk '%s' is initializing", 'OK'], 3 => ["Disk '%s' is inserted", 'OK'], + 4 => ["Disk '%s' is offline", 'WARNING'], 5 => ["Disk '%s' is removed", 'WARNING'], + 6 => ["Disk '%s' is not present", 'WARNING'], + 7 => ["Disk '%s' is empty", 'WARNING'], + 8 => ["Disk '%s' has io errors", 'CRITICAL'], + 9 => ["Disk '%s' is unusable", 'CRITICAL'], + 10 => ["Disk status '%s' is unknown", 'UNKNOWN'], + ); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "skip" => { name => 'skip' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->{output}->output_add(severity => 'OK', + short_msg => "All disks and sensors are ok."); + + my $oid_DeviceSensorValueEntry = '.1.3.6.1.4.1.3417.2.1.1.1.1.1'; + my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_DeviceSensorValueEntry, nothing_quit => 1); + + for (my $i = 0; defined($result->{'.1.3.6.1.4.1.3417.2.1.1.1.1.1.9.' . $i}); $i++) { + my $sensor_name = $result->{'.1.3.6.1.4.1.3417.2.1.1.1.1.1.9.' . $i}; + my $sensor_status = $result->{'.1.3.6.1.4.1.3417.2.1.1.1.1.1.7.' . $i}; + my $sensor_units = $result->{'.1.3.6.1.4.1.3417.2.1.1.1.1.1.3.' . $i}; + my $sensor_code = $result->{'.1.3.6.1.4.1.3417.2.1.1.1.1.1.4.' . $i}; + my $sensor_value = $result->{'.1.3.6.1.4.1.3417.2.1.1.1.1.1.5.' . $i}; + my $sensor_scale = $result->{'.1.3.6.1.4.1.3417.2.1.1.1.1.1.4.' . $i}; + + $self->{output}->output_add(long_msg => "Device sensor '" . $sensor_name . "' status = '" . $sensor_status . "', code = '" . $sensor_code . "'"); + + # Check 'nonoperationnal' and 'unavailable' + if ($sensor_status == 2 || $sensor_status == 3) { + if (!defined($self->{option_results}->{skip})) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Device sensor '" . $sensor_name . "' is " . $sensor_status); + } + next; + } + + if ($sensor_code != 1) { + $self->{output}->output_add(severity => ${$device_code{$sensor_code}}[1], + short_msg => sprintf(${$device_code{$sensor_code}}[0], $sensor_name)); + } + + $self->{output}->perfdata_add(label => $sensor_name, unit => $device_units{sensor_units}, + value => ($sensor_value * (10 ** $sensor_scale))); + } + + ($exit, $result) = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.2.1.1.1.1'); + for (my $i = 0; defined($result->{'.1.3.6.1.4.1.3417.2.2.1.1.1.1.8.' . $i}); $i++) { + my $disk_serial = $result->{'.1.3.6.1.4.1.3417.2.2.1.1.1.1.8.' . $i}; + my $disk_status = $result->{'.1.3.6.1.4.1.3417.2.2.1.1.1.1.3.' . $i}; + + if ($disk_status > 3) { + $self->{output}->output_add(severity => ${$disk_status{$disk_status}}[1], + short_msg => sprintf(${$disk_status{$disk_status}}[0], $disk_serial)); + } + $self->{output}->output_add(long_msg => sprintf(${$disk_status{$disk_status}}[0], $disk_serial)); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check bluecoat hardware sensors and disks. + +=over 8 + +=item B<--skip> + +Skip 'nonoperationnal' and 'unavailable' sensors. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/memory.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/memory.pm new file mode 100644 index 00000000000..3e6106ca4f3 --- /dev/null +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/memory.pm @@ -0,0 +1,104 @@ +package network::bluecoat::mode::memory; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + "nocache" => { name => 'nocache' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + if ($self->{snmp}->is_snmpv1()) { + $self->{output}->add_option_msg(short_msg => "Need to use SNMP v2c or v3."); + $self->{output}->option_exit(); + } + + my ($exit, $result) = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.11.2.3', nothing_quit => 1); + + my $mem_total = $result->{'.1.3.6.1.4.1.3417.2.11.2.3.1.0'}; + my $mem_cache = $result->{'.1.3.6.1.4.1.3417.2.11.2.3.2.0'}; + my $mem_sys = $result->{'.1.3.6.1.4.1.3417.2.11.2.3.3.0'}; + my $mem_used; + + if (defined($self->{option_results}->{nocache})) { + $mem_used = $mem_sys; + } else { + $mem_used = $mem_sys + $mem_cache; + } + + my $prct_used = sprintf("%.2f", $mem_used * 100 / $mem_total); + $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my ($used_value, $used_unit) = $self->{perfdata}->change_bytes(value => $mem_used); + my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $mem_total); + + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Memory used : %s - size : %s - percent : " . $prct_used . " %", + $used_value . " " . $used_unit, $total_value . " " . $total_unit)); + + $self->{output}->perfdata_add(label => 'used', + value => sprintf("%.2f", $mem_used), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $mem_total), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $mem_total), + min => 0, max => $mem_total); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check bluecoat memory. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=item B<--nocache> + +Skip cache value. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/serverconnections.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/serverconnections.pm new file mode 100644 index 00000000000..9fa25364018 --- /dev/null +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/serverconnections.pm @@ -0,0 +1,88 @@ +package network::bluecoat::mode::serverconnections; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my ($exit, $result) = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.3.4.0', + '.1.3.6.1.4.1.3417.2.11.3.1.3.5.0', + '.1.3.6.1.4.1.3417.2.11.3.1.3.6.0'], nothing_quit => 1); + my $server_connections = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.4.0'}; + my $server_connections_active = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.5.0'}; + my $server_connections_idle = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.6.0'}; + + $exit = $self->{perfdata}->threshold_check(value => $server_connections_active, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit, + short_msg => "Server connections: Active " . $server_connections_active . ", Idle " . $server_connections_idle); + $self->{output}->perfdata_add(label => 'con', + value => $server_connections, + min => 0); + $self->{output}->perfdata_add(label => 'con_active', + value => $server_connections_active, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + $self->{output}->perfdata_add(label => 'con_idle', + value => $server_connections_idle, + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check current client connections. + +=over 8 + +=item B<--warning> + +Threshold warning (on active connections). + +=item B<--critical> + +Threshold critical (on active connections. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/bluecoat/plugin.pm b/centreon/lib/perl/plugins/network/bluecoat/plugin.pm new file mode 100644 index 00000000000..c9f14d5155f --- /dev/null +++ b/centreon/lib/perl/plugins/network/bluecoat/plugin.pm @@ -0,0 +1,36 @@ +package network::bluecoat::plugin; + +use strict; +use warnings; +use base qw(centreon::plugins::script_snmp); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '1.0'; + %{$self->{modes}} = ( + 'client-connections' => 'network::bluecoat::mode::clientconnections', + 'client-requests' => 'network::bluecoat::mode::clientrequests', + 'client-traffic' => 'network::bluecoat::mode::clienttraffic', + 'cpu' => 'network::bluecoat::mode::cpu', + 'disk' => 'network::bluecoat::mode::disk', + 'hardware' => 'network::bluecoat::mode::hardware', + 'memory' => 'network::bluecoat::mode::memory', + 'server-connections' => 'network::bluecoat::mode::serverconnections', + ); + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check Bluecoat hardware in SNMP. + +=cut From 9900022aabd8bedb39008ca58d83be122a857d97 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 7 Nov 2013 00:04:41 +0100 Subject: [PATCH 129/458] + mod name --- .../lib/perl/plugins/network/bluecoat/mode/clientrequests.pm | 2 +- .../lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm | 2 +- centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm | 2 +- centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm | 4 ++-- centreon/lib/perl/plugins/snmp_standard/mode/storage.pm | 2 +- centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm | 4 ++-- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm index 2026991d83b..516a6ae8e2b 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm @@ -59,7 +59,7 @@ sub run { $self->{output}->option_exit(); } - $self->{statefile_value}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + $self->{statefile_value}->read(statefile => 'bluecoat_' . $self->{hostname} . '_' . $self->{mode}); my ($exit, $result) = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.1.1.0', '.1.3.6.1.4.1.3417.2.11.3.1.1.2.0', '.1.3.6.1.4.1.3417.2.11.3.1.1.3.0', diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm index f14c0aba898..bfee0a053c8 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm @@ -59,7 +59,7 @@ sub run { $self->{output}->option_exit(); } - $self->{statefile_value}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + $self->{statefile_value}->read(statefile => 'bluecoat_' . $self->{hostname} . '_' . $self->{mode}); my ($exit, $result) = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.1.9.0', '.1.3.6.1.4.1.3417.2.11.3.1.1.10.0'], nothing_quit => 1); diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm index 9a1df7a7328..7221bcad897 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm @@ -52,7 +52,7 @@ sub run { my $new_datas = {}; my $old_timestamp = undef; - $self->{statefile_value}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + $self->{statefile_value}->read(statefile => 'bluecoat_' . $self->{hostname} . '_' . $self->{mode}); my ($exit, $result) = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.11.2.4.1', nothing_quit => 1); $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm b/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm index f30ccf5a3fa..5706b21a625 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm @@ -78,7 +78,7 @@ sub run { my $oid_diskIONWrittenX = '.1.3.6.1.4.1.2021.13.15.1.1.13'; # in B my $new_datas = {}; - $self->{statefile_value}->read(statefile => $self->{hostname} . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{device}) ? md5_hex($self->{option_results}->{device}) : md5_hex('all'))); + $self->{statefile_value}->read(statefile => "snmpstandard_" . $self->{hostname} . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{device}) ? md5_hex($self->{option_results}->{device}) : md5_hex('all'))); $self->{snmp}->load(oids => [$oid_diskIONReadX, $oid_diskIONWrittenX], instances => $self->{device_id_selected}); @@ -194,7 +194,7 @@ sub manage_selection { my ($self, %options) = @_; # init cache file - my $has_cache_file = $self->{statefile_cache}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + my $has_cache_file = $self->{statefile_cache}->read(statefile => 'cache_snmpstandard_' . $self->{hostname} . '_' . $self->{mode}); if (defined($self->{option_results}->{show_cache})) { $self->{output}->add_option_msg(long_msg => $self->{statefile_cache}->get_string_content()); $self->{output}->option_exit(); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm index 4af2e3b0b03..31b4fca9ade 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm @@ -202,7 +202,7 @@ sub manage_selection { my ($self, %options) = @_; # init cache file - my $has_cache_file = $self->{statefile_cache}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + my $has_cache_file = $self->{statefile_cache}->read(statefile => 'cache_snmpstandard_' . $self->{hostname} . '_' . $self->{mode}); if (defined($self->{option_results}->{show_cache})) { $self->{output}->add_option_msg(long_msg => $self->{statefile_cache}->get_string_content()); $self->{output}->option_exit(); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index 731bf226ff0..0c0023d79d8 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -100,7 +100,7 @@ sub run { my $oid_out64 = '.1.3.6.1.2.1.31.1.1.1.10'; # in B my $new_datas = {}; - $self->{statefile_value}->read(statefile => $self->{hostname} . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{interface}) ? md5_hex($self->{option_results}->{interface}) : md5_hex('all'))); + $self->{statefile_value}->read(statefile => "snmpstandard_" . $self->{hostname} . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{interface}) ? md5_hex($self->{option_results}->{interface}) : md5_hex('all'))); foreach (@{$self->{interface_id_selected}}) { $self->{snmp}->load(oids => [$oid_adminstatus . "." . $_, $oid_operstatus . "." . $_, $oid_in32 . "." . $_, $oid_out32 . "." . $_]); @@ -282,7 +282,7 @@ sub manage_selection { my ($self, %options) = @_; # init cache file - my $has_cache_file = $self->{statefile_cache}->read(statefile => 'cache_' . $self->{hostname} . '_' . $self->{mode}); + my $has_cache_file = $self->{statefile_cache}->read(statefile => 'cache_snmpstandard_' . $self->{hostname} . '_' . $self->{mode}); if (defined($self->{option_results}->{show_cache})) { $self->{output}->add_option_msg(long_msg => $self->{statefile_cache}->get_string_content()); $self->{output}->option_exit(); From 7d11064694cf685fec1feacd9e790295cc647125 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 7 Nov 2013 19:26:11 +0100 Subject: [PATCH 130/458] + Fix some minor bugs --- centreon/lib/perl/centreon/plugins/snmp.pm | 2 +- centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm | 2 +- centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm | 2 +- centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm | 2 +- centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm | 4 ++-- centreon/lib/perl/plugins/snmp_standard/mode/storage.pm | 4 ++-- centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm | 4 ++-- centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm | 2 +- 8 files changed, 11 insertions(+), 11 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/snmp.pm b/centreon/lib/perl/centreon/plugins/snmp.pm index ad772987bed..3dd3b69f6bf 100644 --- a/centreon/lib/perl/centreon/plugins/snmp.pm +++ b/centreon/lib/perl/centreon/plugins/snmp.pm @@ -196,7 +196,7 @@ sub get_leef { if ($self->{session}->{ErrorNum}) { my $msg = 'SNMP GET Request : ' . $self->{session}->{ErrorStr}; - if ($dont_quit == 1) { + if ($dont_quit == 0) { $self->{output}->add_option_msg(short_msg => $msg); $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); } diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm b/centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm index 8b30467b481..7c724569d2e 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm @@ -40,7 +40,7 @@ sub run { $self->{snmp} = $options{snmp}; my $oid_cputable = '.1.3.6.1.2.1.25.3.3.1.2'; - my $result = $self->{snmp}->get_table(oid => $oid_cputable); + my ($exit_snmp, $result) = $self->{snmp}->get_table(oid => $oid_cputable); my $cpu = 0; my $i = 0; diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm b/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm index 5706b21a625..fd7e9f5f520 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm @@ -82,7 +82,7 @@ sub run { $self->{snmp}->load(oids => [$oid_diskIONReadX, $oid_diskIONWrittenX], instances => $self->{device_id_selected}); - my $result = $self->{snmp}->get_leef(); + my ($exit_snmp, $result) = $self->{snmp}->get_leef(); $new_datas->{last_timestamp} = time(); my $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); if (!defined($self->{option_results}->{device}) || defined($self->{option_results}->{use_regexp})) { diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm index 65ee695a18b..435c46f2406 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm @@ -62,7 +62,7 @@ sub run { my $oid_CpuLoad5m = '.1.3.6.1.4.1.2021.10.1.3.2'; my $oid_CpuLoad15m = '.1.3.6.1.4.1.2021.10.1.3.3'; - my $result = $self->{snmp}->get_leef(oids => [$oid_CpuLoad1m, $oid_CpuLoad5m, $oid_CpuLoad15m]); + my ($exit_snmp, $result) = $self->{snmp}->get_leef(oids => [$oid_CpuLoad1m, $oid_CpuLoad5m, $oid_CpuLoad15m]); my $exit1 = $self->{perfdata}->threshold_check(value => $result->{$oid_CpuLoad1m}, threshold => [ { label => 'crit1', 'exit_litteral' => 'critical' }, { label => 'warn1', exit_litteral => 'warning' } ]); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm b/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm index cbda70bcf3b..770a35a052a 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm @@ -77,7 +77,7 @@ sub run { } } - my $result = $self->{snmp}->get_table(oid => $oids->{$oid2check_filter}); + my ($exit_snmp, $result) = $self->{snmp}->get_table(oid => $oids->{$oid2check_filter}); my $instances_keep = {}; foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { my $val = $self->{option_results}->{'process_' . $oid2check_filter}; @@ -91,7 +91,7 @@ sub run { if (scalar(keys %$instances_keep) > 0) { $self->{snmp}->load(oids => $more_oids, instances => [keys %$instances_keep ]); - my $result2 = $self->{snmp}->get_leef(); + ($exit_snmp, my $result2) = $self->{snmp}->get_leef(); foreach my $key (keys %$instances_keep) { # 1 = running, 2 = runnable, 3 = notRunnable, 4 => invalid diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm index 31b4fca9ade..d2cb46a724b 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm @@ -85,7 +85,7 @@ sub run { my $oid_hrStorageNetworkDisk = '.1.3.6.1.2.1.25.2.1.10'; $self->{snmp}->load(oids => [$oid_hrStorageAllocationUnits, $oid_hrStorageSize, $oid_hrStorageUsed], instances => $self->{storage_id_selected}); - my $result = $self->{snmp}->get_leef(); + my ($exit_snmp, $result) = $self->{snmp}->get_leef(); if (!defined($self->{option_results}->{storage}) || defined($self->{option_results}->{use_regexp})) { $self->{output}->output_add(severity => 'OK', @@ -284,7 +284,7 @@ sub disco_show { $self->manage_selection(); $self->{snmp}->load(oids => [$oid_hrStorageAllocationUnits, $oid_hrStorageSize], instances => $self->{storage_id_selected}); - my $result = $self->{snmp}->get_leef(); + my ($exit_snmp, $result) = $self->{snmp}->get_leef(); foreach (sort @{$self->{storage_id_selected}}) { my $display_value = $self->get_display_value(id => $_); my $storage_type = $self->{statefile_cache}->get(name => "type_" . $_); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index 0c0023d79d8..3e35ce218d6 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -115,7 +115,7 @@ sub run { } } - my $result = $self->{snmp}->get_leef(); + my ($exit_snmp, $result) = $self->{snmp}->get_leef(); $new_datas->{last_timestamp} = time(); my $old_timestamp; if (!defined($self->{option_results}->{interface}) || defined($self->{option_results}->{use_regexp})) { @@ -350,7 +350,7 @@ sub disco_show { $self->manage_selection(); $self->{snmp}->load(oids => [$oid_operstatus, $oid_speed32], instances => $self->{interface_id_selected}); - my $result = $self->{snmp}->get_leef(); + my ($exit_snmp, $result) = $self->{snmp}->get_leef(); foreach (sort @{$self->{interface_id_selected}}) { my $display_value = $self->get_display_value(id => $_); my $interface_speed = int($result->{$oid_speed32 . "." . $_} / 1000 / 1000); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm b/centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm index ece22ec7acd..4cc4d17d78f 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm @@ -42,7 +42,7 @@ sub run { $self->{snmp} = $options{snmp}; my $oid_hrSystemUptime = '.1.3.6.1.2.1.25.1.1.0'; - my $result = $self->{snmp}->get_leef(oids => [ $oid_hrSystemUptime ]); + my ($exit_snmp, $result) = $self->{snmp}->get_leef(oids => [ $oid_hrSystemUptime ]); my $exit_code = $self->{perfdata}->threshold_check(value => floor($result->{$oid_hrSystemUptime} / 100), threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); From d3da2b8537cb3dfba8fc2222ba0c5e85b2930c62 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 7 Nov 2013 19:31:30 +0100 Subject: [PATCH 131/458] + Add help --- centreon/lib/perl/centreon/plugins/script_simple.pm | 4 ++++ centreon/lib/perl/centreon/plugins/script_snmp.pm | 4 ++++ centreon/lib/perl/centreon/plugins/script_sql.pm | 4 ++++ 3 files changed, 12 insertions(+) diff --git a/centreon/lib/perl/centreon/plugins/script_simple.pm b/centreon/lib/perl/centreon/plugins/script_simple.pm index 69621dd7b2c..a30869f0a18 100644 --- a/centreon/lib/perl/centreon/plugins/script_simple.pm +++ b/centreon/lib/perl/centreon/plugins/script_simple.pm @@ -146,6 +146,10 @@ Specify a mode with the path (separated by '::'). List available modes. +=item B<--version> + +Display plugin version. + =back =head1 DESCRIPTION diff --git a/centreon/lib/perl/centreon/plugins/script_snmp.pm b/centreon/lib/perl/centreon/plugins/script_snmp.pm index cdd3fd1d446..c5e0adb6306 100644 --- a/centreon/lib/perl/centreon/plugins/script_snmp.pm +++ b/centreon/lib/perl/centreon/plugins/script_snmp.pm @@ -165,6 +165,10 @@ Specify a mode with the path (separated by '::'). List available modes. +=item B<--version> + +Display plugin version. + =back =head1 DESCRIPTION diff --git a/centreon/lib/perl/centreon/plugins/script_sql.pm b/centreon/lib/perl/centreon/plugins/script_sql.pm index d9352177c0e..dffe151b9fd 100644 --- a/centreon/lib/perl/centreon/plugins/script_sql.pm +++ b/centreon/lib/perl/centreon/plugins/script_sql.pm @@ -216,6 +216,10 @@ Choose a mode. List available modes. +=item B<--version> + +Display plugin version. + =item B<--dyn-mode> Specify a mode with the path (separated by '::'). From 3b3344168d7787a84d3daed91b93f9f270fcb61e Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 7 Nov 2013 19:40:17 +0100 Subject: [PATCH 132/458] + minor fix plugin --- centreon/lib/perl/plugins/example/mode/getvalue.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/centreon/lib/perl/plugins/example/mode/getvalue.pm b/centreon/lib/perl/plugins/example/mode/getvalue.pm index 551b621e9ab..847cacfb979 100644 --- a/centreon/lib/perl/plugins/example/mode/getvalue.pm +++ b/centreon/lib/perl/plugins/example/mode/getvalue.pm @@ -46,7 +46,7 @@ sub run { $self->{snmp} = $options{snmp}; $self->{hostname} = $self->{snmp}->get_hostname(); - my $result = $self->{snmp}->get_leef(oids => [$self->{option_results}->{oid}], nothing_quit => 1); + my ($exit_snmp, $result) = $self->{snmp}->get_leef(oids => [$self->{option_results}->{oid}], nothing_quit => 1); my $value = $result->{$self->{option_results}->{oid}}; my $exit = $self->{perfdata}->threshold_check(value => $value, From 7d3e5ea842a6298dccc8dbcd1cdd97de35f2b288 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Fri, 8 Nov 2013 19:23:05 +0100 Subject: [PATCH 133/458] + Add GPL Licence --- centreon/lib/perl/centreon/plugins/dbi.pm | 34 ++++++++ centreon/lib/perl/centreon/plugins/misc.pm | 35 ++++++++ centreon/lib/perl/centreon/plugins/mode.pm | 35 ++++++++ centreon/lib/perl/centreon/plugins/options.pm | 34 ++++++++ centreon/lib/perl/centreon/plugins/output.pm | 34 ++++++++ .../lib/perl/centreon/plugins/perfdata.pm | 34 ++++++++ centreon/lib/perl/centreon/plugins/script.pm | 35 ++++++++ .../perl/centreon/plugins/script_simple.pm | 35 ++++++++ .../lib/perl/centreon/plugins/script_snmp.pm | 35 ++++++++ .../lib/perl/centreon/plugins/script_sql.pm | 35 ++++++++ centreon/lib/perl/centreon/plugins/snmp.pm | 80 ++++++++++++++++--- .../lib/perl/centreon/plugins/statefile.pm | 34 ++++++++ centreon/lib/perl/plugins/centreon_plugins.pl | 34 ++++++++ .../database/mysql/mode/connectiontime.pm | 35 ++++++++ .../database/mysql/mode/databasessize.pm | 35 ++++++++ .../mysql/mode/innodbbufferpoolhitrate.pm | 35 ++++++++ .../mysql/mode/myisamkeycachehitrate.pm | 35 ++++++++ .../plugins/database/mysql/mode/openfiles.pm | 35 ++++++++ .../plugins/database/mysql/mode/queries.pm | 35 ++++++++ .../mysql/mode/replicationmasterslave.pm | 35 ++++++++ .../database/mysql/mode/slowqueries.pm | 35 ++++++++ .../database/mysql/mode/threadsconnected.pm | 35 ++++++++ .../plugins/database/mysql/mode/uptime.pm | 35 ++++++++ .../perl/plugins/database/mysql/mysqlcmd.pm | 34 ++++++++ .../lib/perl/plugins/database/mysql/plugin.pm | 35 ++++++++ .../lib/perl/plugins/example/mode/getvalue.pm | 37 ++++++++- .../perl/plugins/example/mode/launchcmd.pm | 35 ++++++++ .../perl/plugins/example/plugin_command.pm | 35 ++++++++ .../lib/perl/plugins/example/plugin_snmp.pm | 35 ++++++++ .../bluecoat/mode/clientconnections.pm | 43 +++++++++- .../network/bluecoat/mode/clientrequests.pm | 47 +++++++++-- .../network/bluecoat/mode/clienttraffic.pm | 41 +++++++++- .../perl/plugins/network/bluecoat/mode/cpu.pm | 39 ++++++++- .../plugins/network/bluecoat/mode/disk.pm | 39 ++++++++- .../plugins/network/bluecoat/mode/hardware.pm | 39 ++++++++- .../plugins/network/bluecoat/mode/memory.pm | 39 ++++++++- .../bluecoat/mode/serverconnections.pm | 43 +++++++++- .../perl/plugins/network/bluecoat/plugin.pm | 35 ++++++++ .../lib/perl/plugins/os/linux/mode/memory.pm | 39 ++++++++- .../lib/perl/plugins/os/linux/mode/swap.pm | 39 ++++++++- centreon/lib/perl/plugins/os/linux/plugin.pm | 35 ++++++++ .../perl/plugins/os/windows/mode/memory.pm | 39 ++++++++- .../lib/perl/plugins/os/windows/mode/swap.pm | 39 ++++++++- .../lib/perl/plugins/os/windows/plugin.pm | 35 ++++++++ .../perl/plugins/snmp_standard/mode/cpu.pm | 37 ++++++++- .../perl/plugins/snmp_standard/mode/diskio.pm | 39 ++++++++- .../plugins/snmp_standard/mode/loadaverage.pm | 37 ++++++++- .../snmp_standard/mode/processcount.pm | 39 ++++++++- .../plugins/snmp_standard/mode/storage.pm | 45 +++++++++-- .../plugins/snmp_standard/mode/traffic.pm | 51 ++++++++++-- .../perl/plugins/snmp_standard/mode/uptime.pm | 37 ++++++++- 51 files changed, 1868 insertions(+), 63 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/dbi.pm b/centreon/lib/perl/centreon/plugins/dbi.pm index 3b98c260208..f512594d95c 100644 --- a/centreon/lib/perl/centreon/plugins/dbi.pm +++ b/centreon/lib/perl/centreon/plugins/dbi.pm @@ -1,3 +1,37 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### package centreon::plugins::dbi; diff --git a/centreon/lib/perl/centreon/plugins/misc.pm b/centreon/lib/perl/centreon/plugins/misc.pm index a974e8866b6..a921d1b97ed 100644 --- a/centreon/lib/perl/centreon/plugins/misc.pm +++ b/centreon/lib/perl/centreon/plugins/misc.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package centreon::plugins::misc; use strict; diff --git a/centreon/lib/perl/centreon/plugins/mode.pm b/centreon/lib/perl/centreon/plugins/mode.pm index 7e5fe3be918..cc4a895cd28 100644 --- a/centreon/lib/perl/centreon/plugins/mode.pm +++ b/centreon/lib/perl/centreon/plugins/mode.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package centreon::plugins::mode; use strict; diff --git a/centreon/lib/perl/centreon/plugins/options.pm b/centreon/lib/perl/centreon/plugins/options.pm index 80667da8758..73acddc6cab 100644 --- a/centreon/lib/perl/centreon/plugins/options.pm +++ b/centreon/lib/perl/centreon/plugins/options.pm @@ -1,3 +1,37 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### package centreon::plugins::options; use Pod::Usage; diff --git a/centreon/lib/perl/centreon/plugins/output.pm b/centreon/lib/perl/centreon/plugins/output.pm index c1c5074d9d6..7771a5fee10 100644 --- a/centreon/lib/perl/centreon/plugins/output.pm +++ b/centreon/lib/perl/centreon/plugins/output.pm @@ -1,3 +1,37 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### package centreon::plugins::output; diff --git a/centreon/lib/perl/centreon/plugins/perfdata.pm b/centreon/lib/perl/centreon/plugins/perfdata.pm index 89d6e6aa2a3..7f9e0d80320 100644 --- a/centreon/lib/perl/centreon/plugins/perfdata.pm +++ b/centreon/lib/perl/centreon/plugins/perfdata.pm @@ -1,3 +1,37 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### package centreon::plugins::perfdata; diff --git a/centreon/lib/perl/centreon/plugins/script.pm b/centreon/lib/perl/centreon/plugins/script.pm index ef799f53b6b..a0a7c109778 100644 --- a/centreon/lib/perl/centreon/plugins/script.pm +++ b/centreon/lib/perl/centreon/plugins/script.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package centreon::plugins::script; use strict; diff --git a/centreon/lib/perl/centreon/plugins/script_simple.pm b/centreon/lib/perl/centreon/plugins/script_simple.pm index a30869f0a18..43cf8bfe9a4 100644 --- a/centreon/lib/perl/centreon/plugins/script_simple.pm +++ b/centreon/lib/perl/centreon/plugins/script_simple.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package centreon::plugins::script_simple; use strict; diff --git a/centreon/lib/perl/centreon/plugins/script_snmp.pm b/centreon/lib/perl/centreon/plugins/script_snmp.pm index c5e0adb6306..f5bf29dc782 100644 --- a/centreon/lib/perl/centreon/plugins/script_snmp.pm +++ b/centreon/lib/perl/centreon/plugins/script_snmp.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package centreon::plugins::script_snmp; use strict; diff --git a/centreon/lib/perl/centreon/plugins/script_sql.pm b/centreon/lib/perl/centreon/plugins/script_sql.pm index dffe151b9fd..92c92fc4957 100644 --- a/centreon/lib/perl/centreon/plugins/script_sql.pm +++ b/centreon/lib/perl/centreon/plugins/script_sql.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package centreon::plugins::script_sql; use strict; diff --git a/centreon/lib/perl/centreon/plugins/snmp.pm b/centreon/lib/perl/centreon/plugins/snmp.pm index 3dd3b69f6bf..5d8c3e46830 100644 --- a/centreon/lib/perl/centreon/plugins/snmp.pm +++ b/centreon/lib/perl/centreon/plugins/snmp.pm @@ -1,5 +1,37 @@ - -# use net-snmp api. +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### package centreon::plugins::snmp; @@ -58,6 +90,9 @@ sub new { # Dont try to translate OID (we keep value) $self->{UseNumeric} = 1; + $self->{error_msg} = undef; + $self->{error_status} = 0; + return $self; } @@ -122,11 +157,13 @@ sub get_leef { my ($dont_quit) = (defined($options{dont_quit}) && $options{dont_quit} == 1) ? 1 : 0; my ($nothing_quit) = (defined($options{nothing_quit}) && $options{nothing_quit} == 1) ? 1 : 0; + $self->set_error(); if (!defined($options{oids})) { if ($#{$self->{oids_loaded}} < 0) { if ($dont_quit == 1) { - return (-1, undef, "Need to specify OIDs"); + $self->set_error(error_status => -1, error_msg => "Need to specify OIDs"); + return undef; } $self->{output}->add_option_msg(short_msg => 'Need to specify OIDs'); $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); @@ -201,7 +238,8 @@ sub get_leef { $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); } - return (-1, undef, $msg); + $self->set_error(error_status => -1, error_msg => $msg); + return undef; } my $total = 0; @@ -224,7 +262,7 @@ sub get_leef { $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); } - return (0, $results); + return $results; } sub get_table { @@ -236,6 +274,7 @@ sub get_table { my ($dont_quit) = (defined($options{dont_quit}) && $options{dont_quit} == 1) ? 1 : 0; my ($nothing_quit) = (defined($options{nothing_quit}) && $options{nothing_quit} == 1) ? 1 : 0; + $self->set_error(); if (defined($options{start})) { $options{start} = $self->clean_oid($options{start}); @@ -257,7 +296,8 @@ sub get_table { # Transform asking if ($options{oid} !~ /(.*)\.(\d+)([\.\s]*)$/) { if ($dont_quit == 1) { - return (-1, undef, "Method 'get_table': Wrong OID '" . $options{oid} . "'."); + $self->set_error(error_status => -1, error_msg => "Method 'get_table': Wrong OID '" . $options{oid} . "'."); + return undef; } $self->{output}->add_option_msg(short_msg => "Method 'get_table': Wrong OID '" . $options{oid} . "'."); $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); @@ -300,8 +340,9 @@ sub get_table { $self->{output}->add_option_msg(short_msg => $msg); $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); } - - return (-1, undef, $msg); + + $self->set_error(error_status => -1, error_msg => $msg); + return undef; } # Manage @@ -330,7 +371,7 @@ sub get_table { $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); } - return (0, $results); + return $results; } sub is_snmpv1 { @@ -458,6 +499,27 @@ sub check_options { } } +sub set_error { + my ($self, %options) = @_; + # $options{error_msg} = string error + # $options{error_status} = integer status + + $self->{error_status} = defined($options{error_status}) ? $options{error_status} : 0; + $self->{error_msg} = defined($options{error_msg}) ? $options{error_msg} : undef; +} + +sub error_status { + my ($self) = @_; + + return $self->{error_status}; +} + +sub error { + my ($self) = @_; + + return $self->{error_msg}; +} + sub get_hostname { my ($self) = @_; diff --git a/centreon/lib/perl/centreon/plugins/statefile.pm b/centreon/lib/perl/centreon/plugins/statefile.pm index 87a0713da50..a1fa0756a55 100644 --- a/centreon/lib/perl/centreon/plugins/statefile.pm +++ b/centreon/lib/perl/centreon/plugins/statefile.pm @@ -1,3 +1,37 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### package centreon::plugins::statefile; use Data::Dumper; diff --git a/centreon/lib/perl/plugins/centreon_plugins.pl b/centreon/lib/perl/plugins/centreon_plugins.pl index ca946402458..d420d23b2f2 100644 --- a/centreon/lib/perl/plugins/centreon_plugins.pl +++ b/centreon/lib/perl/plugins/centreon_plugins.pl @@ -1,4 +1,38 @@ #!/usr/bin/perl +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### use strict; use warnings; diff --git a/centreon/lib/perl/plugins/database/mysql/mode/connectiontime.pm b/centreon/lib/perl/plugins/database/mysql/mode/connectiontime.pm index 2d1c0ebf872..4e311f9a336 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/connectiontime.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/connectiontime.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package database::mysql::mode::connectiontime; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm b/centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm index cb064bceee5..2959dfc8a3b 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/databasessize.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package database::mysql::mode::databasessize; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate.pm b/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate.pm index 8606c43376a..ca176ae719c 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/innodbbufferpoolhitrate.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package database::mysql::mode::innodbbufferpoolhitrate; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/database/mysql/mode/myisamkeycachehitrate.pm b/centreon/lib/perl/plugins/database/mysql/mode/myisamkeycachehitrate.pm index 1fd0c262055..ff21d57afce 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/myisamkeycachehitrate.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/myisamkeycachehitrate.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package database::mysql::mode::myisamkeycachehitrate; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/database/mysql/mode/openfiles.pm b/centreon/lib/perl/plugins/database/mysql/mode/openfiles.pm index e42d6f0da5a..edbfe821844 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/openfiles.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/openfiles.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package database::mysql::mode::openfiles; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/database/mysql/mode/queries.pm b/centreon/lib/perl/plugins/database/mysql/mode/queries.pm index fb409cbb766..8c141761d5a 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/queries.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/queries.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package database::mysql::mode::queries; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/database/mysql/mode/replicationmasterslave.pm b/centreon/lib/perl/plugins/database/mysql/mode/replicationmasterslave.pm index e863798e076..7ceb65b177d 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/replicationmasterslave.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/replicationmasterslave.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package database::mysql::mode::replicationmasterslave; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/database/mysql/mode/slowqueries.pm b/centreon/lib/perl/plugins/database/mysql/mode/slowqueries.pm index 51e77e0e6a5..25a05442a35 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/slowqueries.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/slowqueries.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package database::mysql::mode::slowqueries; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/database/mysql/mode/threadsconnected.pm b/centreon/lib/perl/plugins/database/mysql/mode/threadsconnected.pm index 982ddb9f137..c10095f9532 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/threadsconnected.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/threadsconnected.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package database::mysql::mode::threadsconnected; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/database/mysql/mode/uptime.pm b/centreon/lib/perl/plugins/database/mysql/mode/uptime.pm index bddc762c136..d1b53bdb8e7 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/uptime.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/uptime.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package database::mysql::mode::uptime; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm index 313fd1792e1..98734f126b6 100644 --- a/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm +++ b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm @@ -1,3 +1,37 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### package database::mysql::mysqlcmd; diff --git a/centreon/lib/perl/plugins/database/mysql/plugin.pm b/centreon/lib/perl/plugins/database/mysql/plugin.pm index 5b9903a0aa3..8ca7976c5cc 100644 --- a/centreon/lib/perl/plugins/database/mysql/plugin.pm +++ b/centreon/lib/perl/plugins/database/mysql/plugin.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package database::mysql::plugin; use strict; diff --git a/centreon/lib/perl/plugins/example/mode/getvalue.pm b/centreon/lib/perl/plugins/example/mode/getvalue.pm index 847cacfb979..26c9b0154e1 100644 --- a/centreon/lib/perl/plugins/example/mode/getvalue.pm +++ b/centreon/lib/perl/plugins/example/mode/getvalue.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package example::mode::getvalue; use base qw(centreon::plugins::mode); @@ -46,7 +81,7 @@ sub run { $self->{snmp} = $options{snmp}; $self->{hostname} = $self->{snmp}->get_hostname(); - my ($exit_snmp, $result) = $self->{snmp}->get_leef(oids => [$self->{option_results}->{oid}], nothing_quit => 1); + my $result = $self->{snmp}->get_leef(oids => [$self->{option_results}->{oid}], nothing_quit => 1); my $value = $result->{$self->{option_results}->{oid}}; my $exit = $self->{perfdata}->threshold_check(value => $value, diff --git a/centreon/lib/perl/plugins/example/mode/launchcmd.pm b/centreon/lib/perl/plugins/example/mode/launchcmd.pm index 7d573dfdbd0..45d5842064a 100644 --- a/centreon/lib/perl/plugins/example/mode/launchcmd.pm +++ b/centreon/lib/perl/plugins/example/mode/launchcmd.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package example::mode::launchcmd; use base qw(centreon::plugins::mode); diff --git a/centreon/lib/perl/plugins/example/plugin_command.pm b/centreon/lib/perl/plugins/example/plugin_command.pm index 79b5e0668d8..c5f8d9dd2f9 100644 --- a/centreon/lib/perl/plugins/example/plugin_command.pm +++ b/centreon/lib/perl/plugins/example/plugin_command.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package example::plugin_command; use strict; diff --git a/centreon/lib/perl/plugins/example/plugin_snmp.pm b/centreon/lib/perl/plugins/example/plugin_snmp.pm index ff689ab8233..c496f3ae229 100644 --- a/centreon/lib/perl/plugins/example/plugin_snmp.pm +++ b/centreon/lib/perl/plugins/example/plugin_snmp.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package example::plugin_snmp; use strict; diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/clientconnections.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/clientconnections.pm index 8d227100d80..411a3131541 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/mode/clientconnections.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/clientconnections.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package network::bluecoat::mode::clientconnections; use base qw(centreon::plugins::mode); @@ -39,14 +74,14 @@ sub run { # $options{snmp} = snmp object $self->{snmp} = $options{snmp}; - my ($exit, $result) = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.3.1.0', - '.1.3.6.1.4.1.3417.2.11.3.1.3.2.0', - '.1.3.6.1.4.1.3417.2.11.3.1.3.3.0'], nothing_quit => 1); + my $result = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.3.1.0', + '.1.3.6.1.4.1.3417.2.11.3.1.3.2.0', + '.1.3.6.1.4.1.3417.2.11.3.1.3.3.0'], nothing_quit => 1); my $client_connections = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.1.0'}; my $client_connections_active = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.2.0'}; my $client_connections_idle = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.3.0'}; - $exit = $self->{perfdata}->threshold_check(value => $client_connections_active, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my $exit = $self->{perfdata}->threshold_check(value => $client_connections_active, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); $self->{output}->output_add(severity => $exit, short_msg => "Client connections: Active " . $client_connections_active . ", Idle " . $client_connections_idle); $self->{output}->perfdata_add(label => 'con', diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm index 516a6ae8e2b..e12ca30a75b 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/clientrequests.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package network::bluecoat::mode::clientrequests; use base qw(centreon::plugins::mode); @@ -60,11 +95,11 @@ sub run { } $self->{statefile_value}->read(statefile => 'bluecoat_' . $self->{hostname} . '_' . $self->{mode}); - my ($exit, $result) = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.1.1.0', - '.1.3.6.1.4.1.3417.2.11.3.1.1.2.0', - '.1.3.6.1.4.1.3417.2.11.3.1.1.3.0', - '.1.3.6.1.4.1.3417.2.11.3.1.1.4.0', - '.1.3.6.1.4.1.3417.2.11.3.1.1.5.0'], nothing_quit => 1); + my $result = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.1.1.0', + '.1.3.6.1.4.1.3417.2.11.3.1.1.2.0', + '.1.3.6.1.4.1.3417.2.11.3.1.1.3.0', + '.1.3.6.1.4.1.3417.2.11.3.1.1.4.0', + '.1.3.6.1.4.1.3417.2.11.3.1.1.5.0'], nothing_quit => 1); my $new_datas = {}; my $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); @@ -106,7 +141,7 @@ sub run { my $exit1 = $self->{perfdata}->threshold_check(value => $prct_errors, threshold => [ { label => 'critical_errors', 'exit_litteral' => 'critical' }, { label => 'warning_errors', exit_litteral => 'warning' } ]); my $exit2 = $self->{perfdata}->threshold_check(value => $prct_misses, threshold => [ { label => 'critical_misses', 'exit_litteral' => 'critical' }, { label => 'warning_misses', exit_litteral => 'warning' } ]); - $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2 ]); + my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2 ]); $self->{output}->output_add(severity => $exit, short_msg => "Client Requests: Hits = $prct_hits%, Partial Hits = $prct_partial_hits%, Misses = $prct_misses%, Errors = $prct_errors%"); diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm index bfee0a053c8..b770a095a4a 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/clienttraffic.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package network::bluecoat::mode::clienttraffic; use base qw(centreon::plugins::mode); @@ -61,8 +96,8 @@ sub run { $self->{statefile_value}->read(statefile => 'bluecoat_' . $self->{hostname} . '_' . $self->{mode}); - my ($exit, $result) = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.1.9.0', - '.1.3.6.1.4.1.3417.2.11.3.1.1.10.0'], nothing_quit => 1); + my $result = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.1.9.0', + '.1.3.6.1.4.1.3417.2.11.3.1.1.10.0'], nothing_quit => 1); my $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); my $old_client_in_bytes = $self->{statefile_value}->get(name => 'client_in_bytes'); @@ -93,7 +128,7 @@ sub run { my $exit1 = $self->{perfdata}->threshold_check(value => $in_bytes_sec, threshold => [ { label => 'critical_received', 'exit_litteral' => 'critical' }, { label => 'warning_received', exit_litteral => 'warning' } ]); my $exit2 = $self->{perfdata}->threshold_check(value => $out_bytes_sec, threshold => [ { label => 'critical_delivered', 'exit_litteral' => 'critical' }, { label => 'warning_delivered', exit_litteral => 'warning' } ]); - $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2 ]); + my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2 ]); my ($value_in, $unit_in) = $self->{perfdata}->change_bytes(value => $in_bytes_sec); my ($value_out, $unit_out) = $self->{perfdata}->change_bytes(value => $out_bytes_sec); diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm index 7221bcad897..30a2bb0d547 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/cpu.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package network::bluecoat::mode::cpu; use base qw(centreon::plugins::mode); @@ -54,7 +89,7 @@ sub run { $self->{statefile_value}->read(statefile => 'bluecoat_' . $self->{hostname} . '_' . $self->{mode}); - my ($exit, $result) = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.11.2.4.1', nothing_quit => 1); + my $result = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.11.2.4.1', nothing_quit => 1); $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); $new_datas->{last_timestamp} = time(); for (my $i = 1; defined($result->{'.1.3.6.1.4.1.3417.2.11.2.4.1.3.' . $i}); $i++) { @@ -79,7 +114,7 @@ sub run { my $total_elapsed = (($new_datas->{'cpu_' . $i . '_busy'} - $old_cpu_busy) + ($new_datas->{'cpu_' . $i . '_idle'} - $old_cpu_idle)); my $prct_usage = (($new_datas->{'cpu_' . $i . '_busy'} - $old_cpu_busy) * 100 / ($total_elapsed)); - $exit = $self->{perfdata}->threshold_check(value => $prct_usage, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my $exit = $self->{perfdata}->threshold_check(value => $prct_usage, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); $self->{output}->output_add(severity => $exit, short_msg => sprintf("CPU $i Usage is %.2f%%", $prct_usage)); $self->{output}->perfdata_add(label => 'cpu_' . $i, unit => '%', diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/disk.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/disk.pm index e89ef3b165d..7c23d7da50a 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/mode/disk.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/disk.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package network::bluecoat::mode::disk; use base qw(centreon::plugins::mode); @@ -40,14 +75,14 @@ sub run { $self->{snmp} = $options{snmp}; my $disk_num = 1; - my ($exit, $result) = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.4.1.1.1'); + my $result = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.4.1.1.1'); for (my $i = 1; defined($result->{'.1.3.6.1.4.1.3417.2.4.1.1.1.3.' . $i}); $i++) { if ($result->{'.1.3.6.1.4.1.3417.2.4.1.1.1.3.' . $i} !~ /^DISK$/i) { next; } my $disk_usage = $result->{'.1.3.6.1.4.1.3417.2.4.1.1.1.4.' . $i}; - $exit = $self->{perfdata}->threshold_check(value => $disk_usage, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my $exit = $self->{perfdata}->threshold_check(value => $disk_usage, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); $self->{output}->output_add(severity => $exit, short_msg => sprintf("Disk $disk_num usage is %.2f%%", $disk_usage)); $self->{output}->perfdata_add(label => 'disk_' . $disk_num, unit => '%', diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/hardware.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/hardware.pm index 41c36b87936..4b255877346 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/mode/hardware.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/hardware.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package network::bluecoat::mode::hardware; use base qw(centreon::plugins::mode); @@ -66,7 +101,7 @@ sub run { short_msg => "All disks and sensors are ok."); my $oid_DeviceSensorValueEntry = '.1.3.6.1.4.1.3417.2.1.1.1.1.1'; - my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_DeviceSensorValueEntry, nothing_quit => 1); + my $result = $self->{snmp}->get_table(oid => $oid_DeviceSensorValueEntry, nothing_quit => 1); for (my $i = 0; defined($result->{'.1.3.6.1.4.1.3417.2.1.1.1.1.1.9.' . $i}); $i++) { my $sensor_name = $result->{'.1.3.6.1.4.1.3417.2.1.1.1.1.1.9.' . $i}; @@ -96,7 +131,7 @@ sub run { value => ($sensor_value * (10 ** $sensor_scale))); } - ($exit, $result) = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.2.1.1.1.1'); + $result = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.2.1.1.1.1'); for (my $i = 0; defined($result->{'.1.3.6.1.4.1.3417.2.2.1.1.1.1.8.' . $i}); $i++) { my $disk_serial = $result->{'.1.3.6.1.4.1.3417.2.2.1.1.1.1.8.' . $i}; my $disk_status = $result->{'.1.3.6.1.4.1.3417.2.2.1.1.1.1.3.' . $i}; diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/memory.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/memory.pm index 3e6106ca4f3..8931365bfa8 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/mode/memory.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/memory.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package network::bluecoat::mode::memory; use base qw(centreon::plugins::mode); @@ -45,7 +80,7 @@ sub run { $self->{output}->option_exit(); } - my ($exit, $result) = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.11.2.3', nothing_quit => 1); + my $result = $self->{snmp}->get_table(oid => '.1.3.6.1.4.1.3417.2.11.2.3', nothing_quit => 1); my $mem_total = $result->{'.1.3.6.1.4.1.3417.2.11.2.3.1.0'}; my $mem_cache = $result->{'.1.3.6.1.4.1.3417.2.11.2.3.2.0'}; @@ -59,7 +94,7 @@ sub run { } my $prct_used = sprintf("%.2f", $mem_used * 100 / $mem_total); - $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); my ($used_value, $used_unit) = $self->{perfdata}->change_bytes(value => $mem_used); my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $mem_total); diff --git a/centreon/lib/perl/plugins/network/bluecoat/mode/serverconnections.pm b/centreon/lib/perl/plugins/network/bluecoat/mode/serverconnections.pm index 9fa25364018..4d8e64f9b92 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/mode/serverconnections.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/mode/serverconnections.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package network::bluecoat::mode::serverconnections; use base qw(centreon::plugins::mode); @@ -39,14 +74,14 @@ sub run { # $options{snmp} = snmp object $self->{snmp} = $options{snmp}; - my ($exit, $result) = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.3.4.0', - '.1.3.6.1.4.1.3417.2.11.3.1.3.5.0', - '.1.3.6.1.4.1.3417.2.11.3.1.3.6.0'], nothing_quit => 1); + my $result = $self->{snmp}->get_leef(oids => ['.1.3.6.1.4.1.3417.2.11.3.1.3.4.0', + '.1.3.6.1.4.1.3417.2.11.3.1.3.5.0', + '.1.3.6.1.4.1.3417.2.11.3.1.3.6.0'], nothing_quit => 1); my $server_connections = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.4.0'}; my $server_connections_active = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.5.0'}; my $server_connections_idle = $result->{'.1.3.6.1.4.1.3417.2.11.3.1.3.6.0'}; - $exit = $self->{perfdata}->threshold_check(value => $server_connections_active, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my $exit = $self->{perfdata}->threshold_check(value => $server_connections_active, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); $self->{output}->output_add(severity => $exit, short_msg => "Server connections: Active " . $server_connections_active . ", Idle " . $server_connections_idle); $self->{output}->perfdata_add(label => 'con', diff --git a/centreon/lib/perl/plugins/network/bluecoat/plugin.pm b/centreon/lib/perl/plugins/network/bluecoat/plugin.pm index c9f14d5155f..227e2de7049 100644 --- a/centreon/lib/perl/plugins/network/bluecoat/plugin.pm +++ b/centreon/lib/perl/plugins/network/bluecoat/plugin.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package network::bluecoat::plugin; use strict; diff --git a/centreon/lib/perl/plugins/os/linux/mode/memory.pm b/centreon/lib/perl/plugins/os/linux/mode/memory.pm index 79c168279fc..387a6ff3baf 100644 --- a/centreon/lib/perl/plugins/os/linux/mode/memory.pm +++ b/centreon/lib/perl/plugins/os/linux/mode/memory.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package os::linux::mode::memory; use base qw(centreon::plugins::mode); @@ -45,7 +80,7 @@ sub run { my $oid_hrStorageDescr = '.1.3.6.1.2.1.25.2.3.1.3'; - my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); + my $result = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); foreach my $key (keys %$result) { next if ($key !~ /\.([0-9]+)$/); @@ -90,7 +125,7 @@ sub run { my $total_size = $result->{$oid_hrStorageSize . "." . $self->{physical_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{physical_memory_id}}; my $prct_used = $nobuf_used * 100 / $total_size; - $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); my ($nobuf_value, $nobuf_unit) = $self->{perfdata}->change_bytes(value => $nobuf_used); my ($buffer_value, $buffer_unit) = $self->{perfdata}->change_bytes(value => $buffer_used); diff --git a/centreon/lib/perl/plugins/os/linux/mode/swap.pm b/centreon/lib/perl/plugins/os/linux/mode/swap.pm index dd3b6d1c371..99bf206a39d 100644 --- a/centreon/lib/perl/plugins/os/linux/mode/swap.pm +++ b/centreon/lib/perl/plugins/os/linux/mode/swap.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package os::linux::mode::swap; use base qw(centreon::plugins::mode); @@ -43,7 +78,7 @@ sub run { my $oid_hrStorageDescr = '.1.3.6.1.2.1.25.2.3.1.3'; - my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); + my $result = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); foreach my $key (keys %$result) { next if ($key !~ /\.([0-9]+)$/); @@ -70,7 +105,7 @@ sub run { my $total_size = $result->{$oid_hrStorageSize . "." . $self->{swap_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{swap_memory_id}}; my $prct_used = $swap_used * 100 / $total_size; - $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $total_size); my ($swap_used_value, $swap_used_unit) = $self->{perfdata}->change_bytes(value => $swap_used); diff --git a/centreon/lib/perl/plugins/os/linux/plugin.pm b/centreon/lib/perl/plugins/os/linux/plugin.pm index 810dc51ebf0..c87e6677936 100644 --- a/centreon/lib/perl/plugins/os/linux/plugin.pm +++ b/centreon/lib/perl/plugins/os/linux/plugin.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package os::linux::plugin; use strict; diff --git a/centreon/lib/perl/plugins/os/windows/mode/memory.pm b/centreon/lib/perl/plugins/os/windows/mode/memory.pm index 791e243036b..dae7d7a915c 100644 --- a/centreon/lib/perl/plugins/os/windows/mode/memory.pm +++ b/centreon/lib/perl/plugins/os/windows/mode/memory.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package os::windows::mode::memory; use base qw(centreon::plugins::mode); @@ -43,7 +78,7 @@ sub run { my $oid_hrStorageDescr = '.1.3.6.1.2.1.25.2.3.1.3'; - my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); + my $result = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); foreach my $key (keys %$result) { next if ($key !~ /\.([0-9]+)$/); @@ -70,7 +105,7 @@ sub run { my $total_size = $result->{$oid_hrStorageSize . "." . $self->{physical_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{physical_memory_id}}; my $prct_used = $physical_used * 100 / $total_size; - $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); my ($physical_used_value, $physical_used_unit) = $self->{perfdata}->change_bytes(value => $physical_used); my ($physical_free_value, $physical_free_unit) = $self->{perfdata}->change_bytes(value => $total_size - $physical_used); diff --git a/centreon/lib/perl/plugins/os/windows/mode/swap.pm b/centreon/lib/perl/plugins/os/windows/mode/swap.pm index 639fb0855db..4714a90ea05 100644 --- a/centreon/lib/perl/plugins/os/windows/mode/swap.pm +++ b/centreon/lib/perl/plugins/os/windows/mode/swap.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package os::windows::mode::swap; use base qw(centreon::plugins::mode); @@ -43,7 +78,7 @@ sub run { my $oid_hrStorageDescr = '.1.3.6.1.2.1.25.2.3.1.3'; - my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); + my $result = $self->{snmp}->get_table(oid => $oid_hrStorageDescr); foreach my $key (keys %$result) { next if ($key !~ /\.([0-9]+)$/); @@ -70,7 +105,7 @@ sub run { my $total_size = $result->{$oid_hrStorageSize . "." . $self->{swap_memory_id}} * $result->{$oid_hrStorageAllocationUnits . "." . $self->{swap_memory_id}}; my $prct_used = $swap_used * 100 / $total_size; - $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); my ($swap_used_value, $swap_used_unit) = $self->{perfdata}->change_bytes(value => $swap_used); my ($swap_free_value, $swap_free_unit) = $self->{perfdata}->change_bytes(value => $total_size - $swap_used); diff --git a/centreon/lib/perl/plugins/os/windows/plugin.pm b/centreon/lib/perl/plugins/os/windows/plugin.pm index 9405a35075b..07182d33e5f 100644 --- a/centreon/lib/perl/plugins/os/windows/plugin.pm +++ b/centreon/lib/perl/plugins/os/windows/plugin.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package os::windows::plugin; use strict; diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm b/centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm index 7c724569d2e..0a6543236fd 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/cpu.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package snmp_standard::mode::cpu; use base qw(centreon::plugins::mode); @@ -40,7 +75,7 @@ sub run { $self->{snmp} = $options{snmp}; my $oid_cputable = '.1.3.6.1.2.1.25.3.3.1.2'; - my ($exit_snmp, $result) = $self->{snmp}->get_table(oid => $oid_cputable); + my $result = $self->{snmp}->get_table(oid => $oid_cputable); my $cpu = 0; my $i = 0; diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm b/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm index fd7e9f5f520..2dcacb6535f 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/diskio.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package snmp_standard::mode::diskio; use base qw(centreon::plugins::mode); @@ -82,7 +117,7 @@ sub run { $self->{snmp}->load(oids => [$oid_diskIONReadX, $oid_diskIONWrittenX], instances => $self->{device_id_selected}); - my ($exit_snmp, $result) = $self->{snmp}->get_leef(); + my $result = $self->{snmp}->get_leef(); $new_datas->{last_timestamp} = time(); my $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); if (!defined($self->{option_results}->{device}) || defined($self->{option_results}->{use_regexp})) { @@ -173,7 +208,7 @@ sub reload_cache { my $datas = {}; my $oid_diskIODevice = '.1.3.6.1.4.1.2021.13.15.1.1.2'; - my ($exit, $result) = $self->{snmp}->get_table(oid => $oid_diskIODevice); + my $result = $self->{snmp}->get_table(oid => $oid_diskIODevice); my $last_num = 0; foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($key !~ /\.([0-9]+)$/); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm index 435c46f2406..3fd28a90ce2 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/loadaverage.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package snmp_standard::mode::loadaverage; use base qw(centreon::plugins::mode); @@ -62,7 +97,7 @@ sub run { my $oid_CpuLoad5m = '.1.3.6.1.4.1.2021.10.1.3.2'; my $oid_CpuLoad15m = '.1.3.6.1.4.1.2021.10.1.3.3'; - my ($exit_snmp, $result) = $self->{snmp}->get_leef(oids => [$oid_CpuLoad1m, $oid_CpuLoad5m, $oid_CpuLoad15m]); + my $result = $self->{snmp}->get_leef(oids => [$oid_CpuLoad1m, $oid_CpuLoad5m, $oid_CpuLoad15m]); my $exit1 = $self->{perfdata}->threshold_check(value => $result->{$oid_CpuLoad1m}, threshold => [ { label => 'crit1', 'exit_litteral' => 'critical' }, { label => 'warn1', exit_litteral => 'warning' } ]); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm b/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm index 770a35a052a..cfbe3003c03 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package snmp_standard::mode::processcount; use base qw(centreon::plugins::mode); @@ -77,7 +112,7 @@ sub run { } } - my ($exit_snmp, $result) = $self->{snmp}->get_table(oid => $oids->{$oid2check_filter}); + my $result = $self->{snmp}->get_table(oid => $oids->{$oid2check_filter}); my $instances_keep = {}; foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { my $val = $self->{option_results}->{'process_' . $oid2check_filter}; @@ -91,7 +126,7 @@ sub run { if (scalar(keys %$instances_keep) > 0) { $self->{snmp}->load(oids => $more_oids, instances => [keys %$instances_keep ]); - ($exit_snmp, my $result2) = $self->{snmp}->get_leef(); + my $result2 = $self->{snmp}->get_leef(); foreach my $key (keys %$instances_keep) { # 1 = running, 2 = runnable, 3 = notRunnable, 4 => invalid diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm index d2cb46a724b..b1d0a92ba2b 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package snmp_standard::mode::storage; use base qw(centreon::plugins::mode); @@ -85,7 +120,7 @@ sub run { my $oid_hrStorageNetworkDisk = '.1.3.6.1.2.1.25.2.1.10'; $self->{snmp}->load(oids => [$oid_hrStorageAllocationUnits, $oid_hrStorageSize, $oid_hrStorageUsed], instances => $self->{storage_id_selected}); - my ($exit_snmp, $result) = $self->{snmp}->get_leef(); + my $result = $self->{snmp}->get_leef(); if (!defined($self->{option_results}->{storage}) || defined($self->{option_results}->{use_regexp})) { $self->{output}->output_add(severity => 'OK', @@ -167,7 +202,7 @@ sub reload_cache { $datas->{oid_filter} = $self->{option_results}->{oid_filter}; $datas->{oid_display} = $self->{option_results}->{oid_display}; - my ($exit, $result) = $self->{snmp}->get_table(oid => $oids_hrStorageTable{$self->{option_results}->{oid_filter}}); + my $result = $self->{snmp}->get_table(oid => $oids_hrStorageTable{$self->{option_results}->{oid_filter}}); my $last_num = 0; foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($key !~ /\.([0-9]+)$/); @@ -181,14 +216,14 @@ sub reload_cache { } if ($self->{option_results}->{oid_filter} ne $self->{option_results}->{oid_display}) { - ($exit, $result) = $self->{snmp}->get_table(oid => $oids_hrStorageTable{$self->{option_results}->{oid_display}}); + $result = $self->{snmp}->get_table(oid => $oids_hrStorageTable{$self->{option_results}->{oid_display}}); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($key !~ /\.([0-9]+)$/); $datas->{$self->{option_results}->{oid_display} . "_" . $1} = $result->{$key}; } } - ($exit, $result) = $self->{snmp}->get_table(oid => $oids_hrStorageTable{hrstoragetype}); + $result = $self->{snmp}->get_table(oid => $oids_hrStorageTable{hrstoragetype}); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($key !~ /\.([0-9]+)$/); $datas->{"type_" . $1} = $result->{$key}; @@ -284,7 +319,7 @@ sub disco_show { $self->manage_selection(); $self->{snmp}->load(oids => [$oid_hrStorageAllocationUnits, $oid_hrStorageSize], instances => $self->{storage_id_selected}); - my ($exit_snmp, $result) = $self->{snmp}->get_leef(); + my $result = $self->{snmp}->get_leef(); foreach (sort @{$self->{storage_id_selected}}) { my $display_value = $self->get_display_value(id => $_); my $storage_type = $self->{statefile_cache}->get(name => "type_" . $_); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index 3e35ce218d6..3fde38fdd7c 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package snmp_standard::mode::traffic; use base qw(centreon::plugins::mode); @@ -33,8 +68,8 @@ sub new { "skip" => { name => 'skip' }, "regexp" => { name => 'use_regexp' }, "regexp-isensitive" => { name => 'use_regexpi' }, - "oid-filter:s" => { name => 'oid_filter', default => 'ifDesc'}, - "oid-display:s" => { name => 'oid_display', default => 'ifDesc'}, + "oid-filter:s" => { name => 'oid_filter', default => 'ifname'}, + "oid-display:s" => { name => 'oid_display', default => 'ifname'}, "display-transform-src:s" => { name => 'display_transform_src' }, "display-transform-dst:s" => { name => 'display_transform_dst' }, "show-cache" => { name => 'show_cache' }, @@ -115,7 +150,7 @@ sub run { } } - my ($exit_snmp, $result) = $self->{snmp}->get_leef(); + my $result = $self->{snmp}->get_leef(); $new_datas->{last_timestamp} = time(); my $old_timestamp; if (!defined($self->{option_results}->{interface}) || defined($self->{option_results}->{use_regexp})) { @@ -253,7 +288,7 @@ sub reload_cache { $datas->{oid_filter} = $self->{option_results}->{oid_filter}; $datas->{oid_display} = $self->{option_results}->{oid_display}; - my ($exit, $result) = $self->{snmp}->get_table(oid => $oids_iftable{$self->{option_results}->{oid_filter}}); + my $result = $self->{snmp}->get_table(oid => $oids_iftable{$self->{option_results}->{oid_filter}}); my $last_num = 0; foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($key !~ /\.([0-9]+)$/); @@ -267,7 +302,7 @@ sub reload_cache { } if ($self->{option_results}->{oid_filter} ne $self->{option_results}->{oid_display}) { - ($exit, $result) = $self->{snmp}->get_table(oid => $oids_iftable{$self->{option_results}->{oid_display}}); + $result = $self->{snmp}->get_table(oid => $oids_iftable{$self->{option_results}->{oid_display}}); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($key !~ /\.([0-9]+)$/); $datas->{$self->{option_results}->{oid_display} . "_" . $1} = $result->{$key}; @@ -350,7 +385,7 @@ sub disco_show { $self->manage_selection(); $self->{snmp}->load(oids => [$oid_operstatus, $oid_speed32], instances => $self->{interface_id_selected}); - my ($exit_snmp, $result) = $self->{snmp}->get_leef(); + my $result = $self->{snmp}->get_leef(); foreach (sort @{$self->{interface_id_selected}}) { my $display_value = $self->get_display_value(id => $_); my $interface_speed = int($result->{$oid_speed32 . "." . $_} / 1000 / 1000); @@ -419,11 +454,11 @@ Time in seconds before reloading cache file (default: 180). =item B<--oid-filter> -Choose OID used to filter interface (default: ifDesc) (values: ifDesc, ifAlias, ifName). +Choose OID used to filter interface (default: ifName) (values: ifDesc, ifAlias, ifName). =item B<--oid-display> -Choose OID used to display interface (default: ifDesc) (values: ifDesc, ifAlias, ifName). +Choose OID used to display interface (default: ifName) (values: ifDesc, ifAlias, ifName). =item B<--display-transform-src> diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm b/centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm index 4cc4d17d78f..b49190e495c 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/uptime.pm @@ -1,3 +1,38 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + package snmp_standard::mode::uptime; use base qw(centreon::plugins::mode); @@ -42,7 +77,7 @@ sub run { $self->{snmp} = $options{snmp}; my $oid_hrSystemUptime = '.1.3.6.1.2.1.25.1.1.0'; - my ($exit_snmp, $result) = $self->{snmp}->get_leef(oids => [ $oid_hrSystemUptime ]); + my $result = $self->{snmp}->get_leef(oids => [ $oid_hrSystemUptime ]); my $exit_code = $self->{perfdata}->threshold_check(value => floor($result->{$oid_hrSystemUptime} / 100), threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); From 7139a15b8b48f19da9ace44a97ab4a1e877d81ef Mon Sep 17 00:00:00 2001 From: qgarnier Date: Fri, 8 Nov 2013 22:38:58 +0100 Subject: [PATCH 134/458] + Add plugin HP Blade Chassis --- .../server/hpbladechassis/mode/hardware.pm | 620 ++++++++++++++++++ .../hardware/server/hpbladechassis/plugin.pm | 64 ++ 2 files changed, 684 insertions(+) create mode 100644 centreon/lib/perl/plugins/hardware/server/hpbladechassis/mode/hardware.pm create mode 100644 centreon/lib/perl/plugins/hardware/server/hpbladechassis/plugin.pm diff --git a/centreon/lib/perl/plugins/hardware/server/hpbladechassis/mode/hardware.pm b/centreon/lib/perl/plugins/hardware/server/hpbladechassis/mode/hardware.pm new file mode 100644 index 00000000000..dbc6f277929 --- /dev/null +++ b/centreon/lib/perl/plugins/hardware/server/hpbladechassis/mode/hardware.pm @@ -0,0 +1,620 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package hardware::server::hpbladechassis::mode::hardware; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %conditions = (1 => ['other', 'CRITICAL'], + 2 => ['ok', 'OK'], + 3 => ['degraded', 'WARNING'], + 4 => ['failed', 'CRITICAL']); +my %present_map = (1 => 'other', + 2 => 'absent', + 3 => 'present', + 4 => 'Weird!!!', # for blades it can return 4, which is NOT spesified in MIB +); +my %device_type = (1 => 'noconnect', + 2 => 'network', + 3 => 'fibrechannel', + 4 => 'sas', + 5 => 'inifiband', + 6 => 'pciexpress' +); +my %psu_status = (1 => 'noError', + 2 => 'generalFailure', + 3 => 'bistFailure', + 4 => 'fanFailure', + 5 => 'tempFailure', + 6 => 'interlockOpen', + 7 => 'epromFailed', + 8 => 'vrefFailed', + 9 => 'dacFailed', + 10 => 'ramTestFailed', + 11 => 'voltageChannelFailed', + 12 => 'orringdiodeFailed', + 13 => 'brownOut', + 14 => 'giveupOnStartup', + 15 => 'nvramInvalid', + 16 => 'calibrationTableInvalid', +); +my %inputline_status = (1 => 'noError', + 2 => 'lineOverVoltage', + 3 => 'lineUnderVoltage', + 4 => 'lineHit', + 5 => 'brownOut', + 6 => 'linePowerLoss', +); +my %map_role = (1 => 'Standby', + 2 => 'Active', +); +my %map_has = (1 => 'false', + 2 => 'true', +); +my %map_temp_type = (1 => 'other', + 5 => 'blowout', + 9 => 'caution', + 15 => 'critical', +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "exclude" => { name => 'exclude' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->{components_fans} = 0; + $self->{components_blades} = 0; + $self->{components_nc} = 0; + $self->{components_psu} = 0; + $self->{components_temperatures} = 0; + $self->{components_fuse} = 0; + + $self->check_enclosure_status(); + $self->check_managers(); + $self->check_fans(); + $self->check_blades(); + $self->check_iom(); + $self->check_psu(); + $self->check_temperatures(); + $self->check_fuse(); + + $self->{output}->output_add(severity => 'OK', + short_msg => sprintf("All %d components [%d fans, %d blades, %d network connectors, %d psu, %d temperatures, %d fuses] are ok.", + ($self->{components_fans} + $self->{components_blades} + $self->{components_nc} + $self->{components_psu} + $self->{components_temperatures} + $self->{components_fuse}), + $self->{components_fans}, $self->{components_blades}, $self->{components_nc}, $self->{components_psu}, $self->{components_temperatures}, $self->{components_fuse})); + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub check_enclosure_status { + my ($self) = @_; + + my $oid_cpqRackCommonEnclosurePartNumber = '.1.3.6.1.4.1.232.22.2.3.1.1.1.5.1'; + my $oid_cpqRackCommonEnclosureSparePartNumber = '.1.3.6.1.4.1.232.22.2.3.1.1.1.6.1'; + my $oid_cpqRackCommonEnclosureSerialNum = '.1.3.6.1.4.1.232.22.2.3.1.1.1.7.1'; + my $oid_cpqRackCommonEnclosureFWRev = '.1.3.6.1.4.1.232.22.2.3.1.1.1.8.1'; + my $oid_cpqRackCommonEnclosureCondition = '.1.3.6.1.4.1.232.22.2.3.1.1.1.16.1'; + my $oid_cpqRackCommonEnclosureHasServerBlades = '.1.3.6.1.4.1.232.22.2.3.1.1.1.17.1'; + my $oid_cpqRackCommonEnclosureHasPowerSupplies = '.1.3.6.1.4.1.232.22.2.3.1.1.1.18.1'; + my $oid_cpqRackCommonEnclosureHasNetConnectors = '.1.3.6.1.4.1.232.22.2.3.1.1.1.19.1'; + my $oid_cpqRackCommonEnclosureHasTempSensors = '.1.3.6.1.4.1.232.22.2.3.1.1.1.20.1'; + my $oid_cpqRackCommonEnclosureHasFans = '.1.3.6.1.4.1.232.22.2.3.1.1.1.21.1'; + my $oid_cpqRackCommonEnclosureHasFuses = '.1.3.6.1.4.1.232.22.2.3.1.1.1.22.1'; + #my $oid_cpqRackServerBladeHasManagementDevice = '.1.3.6.1.4.1.232.22.2.4.1.1.1.29.1'; + + $self->{global_results} = $self->{snmp}->get_leef(oids => [$oid_cpqRackCommonEnclosurePartNumber, $oid_cpqRackCommonEnclosureSparePartNumber, + $oid_cpqRackCommonEnclosureSerialNum, $oid_cpqRackCommonEnclosureFWRev, + $oid_cpqRackCommonEnclosureCondition, $oid_cpqRackCommonEnclosureHasServerBlades, + $oid_cpqRackCommonEnclosureHasPowerSupplies, $oid_cpqRackCommonEnclosureHasNetConnectors, + $oid_cpqRackCommonEnclosureHasTempSensors, $oid_cpqRackCommonEnclosureHasFans, + $oid_cpqRackCommonEnclosureHasFuses], nothing_quit => 1); + + $self->{output}->output_add(long_msg => sprintf("Enclosure overall health condition is %s [part: %s, spare: %s, sn: %s, fw: %s].", + ${$conditions{$self->{global_results}->{$oid_cpqRackCommonEnclosureCondition}}}[0], + $self->{global_results}->{$oid_cpqRackCommonEnclosurePartNumber}, + $self->{global_results}->{$oid_cpqRackCommonEnclosureSparePartNumber}, + $self->{global_results}->{$oid_cpqRackCommonEnclosureSerialNum}, + $self->{global_results}->{$oid_cpqRackCommonEnclosureFWRev})); + if ($self->{global_results}->{$oid_cpqRackCommonEnclosureCondition} != 2) { + $self->{output}->output_add(severity => ${$conditions{$self->{global_results}->{$oid_cpqRackCommonEnclosureCondition}}}[1], + short_msg => sprintf("Enclosure overall health condition is %s", ${$conditions{$self->{global_results}->{$oid_cpqRackCommonEnclosureCondition}}}[0])); + } +} + +sub check_managers { + my ($self) = @_; + + #my $oid_cpqRackServerBladeHasManagementDevice = '.1.3.6.1.4.1.232.22.2.4.1.1.1.29.1'; + #if (defined($map_has{$global_results->{$oid_cpqRackServerBladeHasManagementDevice}}) && + # $map_has{$global_results->{$oid_cpqRackServerBladeHasManagementDevice}} =~ /^false$/i) { + # output_add(long_msg => sprintf("Skipping Managers: enclosure doesnt contain managers.")); + # return ; + #} + + return if ($self->check_exclude('managers')); + + # No check if OK + if ($self->{output}->is_status(compare => 'ok', litteral => 1)) { + return ; + } + + my $oid_cpqRackCommonEnclosureManagerIndex = '.1.3.6.1.4.1.232.22.2.3.1.6.1.3'; + my $oid_cpqRackCommonEnclosureManagerPartNumber = '.1.3.6.1.4.1.232.22.2.3.1.6.1.6'; + my $oid_cpqRackCommonEnclosureManagerSparePartNumber = '.1.3.6.1.4.1.232.22.2.3.1.6.1.7'; + my $oid_cpqRackCommonEnclosureManagerSerialNum = '.1.3.6.1.4.1.232.22.2.3.1.6.1.8'; + my $oid_cpqRackCommonEnclosureManagerRole = '.1.3.6.1.4.1.232.22.2.3.1.6.1.9'; + my $oid_cpqRackCommonEnclosureManagerCondition = '.1.3.6.1.4.1.232.22.2.3.1.6.1.12'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqRackCommonEnclosureManagerIndex); + + $self->{snmp}->load(oids => [$oid_cpqRackCommonEnclosureManagerPartNumber, $oid_cpqRackCommonEnclosureManagerSparePartNumber, + $oid_cpqRackCommonEnclosureManagerSerialNum, $oid_cpqRackCommonEnclosureManagerRole, + $oid_cpqRackCommonEnclosureManagerCondition], + instances => [keys %$result]); + my $result2 = $self->{snmp}->get_leef(); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + $key =~ /(\d+)$/; + my $instance = $1; + + my $man_part = $result2->{$oid_cpqRackCommonEnclosureManagerPartNumber . '.' . $instance}; + my $man_spare = $result2->{$oid_cpqRackCommonEnclosureManagerSparePartNumber . '.' . $instance}; + my $man_serial = $result2->{$oid_cpqRackCommonEnclosureManagerSerialNum . '.' . $instance}; + my $man_role = $result2->{$oid_cpqRackCommonEnclosureManagerRole . '.' . $instance}; + my $man_condition = $result2->{$oid_cpqRackCommonEnclosureManagerCondition . '.' . $instance}; + + $self->{output}->output_add(long_msg => sprintf("Enclosure management module %d is %s, status is %s [serial: %s, part: %s, spare: %s].", + $instance, ${$conditions{$man_condition}}[0], $map_role{$man_role}, + $man_serial, $man_part, $man_spare)); + if ($man_condition != 2) { + $self->{output}->output_add(severity => ${$conditions{$man_condition}}[1], + short_msg => sprintf("Enclosure management module %d is %s, status is %s", + $instance, ${$conditions{$man_condition}}[0], $map_role{$man_role})); + } + } +} + +sub check_fans { + my ($self) = @_; + + return if ($self->check_exclude('fans')); + + my $oid_cpqRackCommonEnclosureHasFans = '.1.3.6.1.4.1.232.22.2.3.1.1.1.21.1'; + if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasFans}}) && + $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasFans}} =~ /^false$/i) { + $self->{output}->output_add(long_msg => sprintf("Skipping Fans: enclosure cannot house fans (??!!).")); + return ; + } + + my $oid_cpqRackCommonEnclosureFanPresent = '.1.3.6.1.4.1.232.22.2.3.1.3.1.8'; + my $oid_cpqRackCommonEnclosureFanIndex = '.1.3.6.1.4.1.232.22.2.3.1.3.1.3'; + my $oid_cpqRackCommonEnclosureFanPartNumber = '.1.3.6.1.4.1.232.22.2.3.1.3.1.6'; + my $oid_cpqRackCommonEnclosureFanSparePartNumber = '.1.3.6.1.4.1.232.22.2.3.1.3.1.7'; + my $oid_cpqRackCommonEnclosureFanCondition = '.1.3.6.1.4.1.232.22.2.3.1.3.1.11'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqRackCommonEnclosureFanPresent); + my @get_oids = (); + my @oids_end = (); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($present_map{$result->{$key}} ne 'present'); + $key =~ /\.([0-9]+)$/; + my $oid_end = $1; + + push @oids_end, $oid_end; + push @get_oids, $oid_cpqRackCommonEnclosureFanIndex . "." . $oid_end, $oid_cpqRackCommonEnclosureFanPartNumber . "." . $oid_end, + $oid_cpqRackCommonEnclosureFanSparePartNumber . "." . $oid_end, $oid_cpqRackCommonEnclosureFanCondition . "." . $oid_end; + } + $result = $self->{snmp}->get_leef(oids => \@get_oids); + foreach (@oids_end) { + my $fan_index = $result->{$oid_cpqRackCommonEnclosureFanIndex . '.' . $_}; + my $fan_condition = $result->{$oid_cpqRackCommonEnclosureFanCondition . '.' . $_}; + my $fan_part = $result->{$oid_cpqRackCommonEnclosureFanPartNumber . '.' . $_}; + my $fan_spare = $result->{$oid_cpqRackCommonEnclosureFanSparePartNumber . '.' . $_}; + + $self->{components_fans}++; + $self->{output}->output_add(long_msg => sprintf("Fan %d condition is %s [part: %s, spare: %s].", + $fan_index, ${$conditions{$fan_condition}}[0], + $fan_part, $fan_spare)); + if ($fan_condition != 2) { + $self->{output}->output_add(severity => ${$conditions{$fan_condition}}[1], + short_msg => sprintf("Fan %d condition is %s", $fan_index, ${$conditions{$fan_condition}}[0])); + } + } +} + +sub check_blades { + my ($self) = @_; + + return if ($self->check_exclude('blades')); + + my $oid_cpqRackCommonEnclosureHasServerBlades = '.1.3.6.1.4.1.232.22.2.3.1.1.1.17.1'; + if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasServerBlades}}) && + $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasServerBlades}} =~ /^false$/i) { + $self->{output}->output_add(long_msg => sprintf("Skipping Blades: enclosure cannot house blades (??!!).")); + return ; + } + + my $oid_cpqRackServerBladePresent = '.1.3.6.1.4.1.232.22.2.4.1.1.1.12'; + my $oid_cpqRackServerBladeIndex = '.1.3.6.1.4.1.232.22.2.4.1.1.1.3'; + my $oid_cpqRackServerBladeName = '.1.3.6.1.4.1.232.22.2.4.1.1.1.4'; + my $oid_cpqRackServerBladePartNumber = '.1.3.6.1.4.1.232.22.2.4.1.1.1.6'; + my $oid_cpqRackServerBladeSparePartNumber = '.1.3.6.1.4.1.232.22.2.4.1.1.1.7'; + my $oid_cpqRackServerBladeProductId = '.1.3.6.1.4.1.232.22.2.4.1.1.1.17'; + my $oid_cpqRackServerBladeStatus = '.1.3.6.1.4.1.232.22.2.4.1.1.1.21'; # v2 + my $oid_cpqRackServerBladeFaultDiagnosticString = '.1.3.6.1.4.1.232.22.2.4.1.1.1.24'; # v2 + + my $result = $self->{snmp}->get_table(oid => $oid_cpqRackServerBladePresent); + my @get_oids = (); + my @oids_end = (); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($present_map{$result->{$key}} ne 'present'); + $key =~ /\.([0-9]+)$/; + my $oid_end = $1; + + push @oids_end, $oid_end; + push @get_oids, $oid_cpqRackServerBladeIndex . "." . $oid_end, $oid_cpqRackServerBladeName . "." . $oid_end, + $oid_cpqRackServerBladePartNumber . "." . $oid_end, $oid_cpqRackServerBladeSparePartNumber . "." . $oid_end, + $oid_cpqRackServerBladeProductId . "." . $oid_end, + $oid_cpqRackServerBladeStatus . "." . $oid_end, $oid_cpqRackServerBladeFaultDiagnosticString . "." . $oid_end; + } + + $result = $self->{snmp}->get_leef(oids => \@get_oids); + foreach (@oids_end) { + my $blade_index = $result->{$oid_cpqRackServerBladeIndex . '.' . $_}; + my $blade_status = defined($result->{$oid_cpqRackServerBladeStatus . '.' . $_}) ? $result->{$oid_cpqRackServerBladeStatus . '.' . $_} : ''; + my $blade_name = $result->{$oid_cpqRackServerBladeName . '.' . $_}; + my $blade_part = $result->{$oid_cpqRackServerBladePartNumber . '.' . $_}; + my $blade_spare = $result->{$oid_cpqRackServerBladeSparePartNumber . '.' . $_}; + my $blade_productid = $result->{$oid_cpqRackServerBladeProductId . '.' . $_}; + my $blade_diago = defined($result->{$oid_cpqRackServerBladeFaultDiagnosticString . '.' . $_}) ? $result->{$oid_cpqRackServerBladeFaultDiagnosticString . '.' . $_} : ''; + + $self->{components_blades}++; + if ($blade_status eq '') { + $self->{output}->output_add(long_msg => sprintf("Skipping Blade %d (%s, %s). Cant get status.", + $blade_index, $blade_name, $blade_productid)); + next; + } + $self->{output}->output_add(long_msg => sprintf("Blade %d (%s, %s) status is %s [part: %s, spare: %s]%s.", + $blade_index, $blade_name, $blade_productid, + ${$conditions{$blade_status}}[0], + $blade_part, $blade_spare, + ($blade_diago ne '') ? " (Diagnostic '$blade_diago')" : '' + )); + if ($blade_status != 2) { + $self->{output}->output_add(severity => ${$conditions{$blade_status}}[1], + short_msg => sprintf("Blade %d (%s, %s) status is %s", + $blade_index, $blade_name, $blade_productid, + ${$conditions{$blade_status}}[0] + )); + } + } +} + + +sub check_iom { + my ($self) = @_; + + return if ($self->check_exclude('network')); + + my $oid_cpqRackCommonEnclosureHasNetConnectors = '.1.3.6.1.4.1.232.22.2.3.1.1.1.19.1'; + if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasNetConnectors}}) && + $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasNetConnectors}} =~ /^false$/i) { + $self->{output}->output_add(long_msg => sprintf("Skipping Network Connectors: enclosure cannot house network connectors (??!!).")); + return ; + } + + my $oid_cpqRackNetConnectorPresent = '.1.3.6.1.4.1.232.22.2.6.1.1.1.13'; + my $oid_cpqRackNetConnectorIndex = '.1.3.6.1.4.1.232.22.2.6.1.1.1.3'; + my $oid_cpqRackNetConnectorModel = '.1.3.6.1.4.1.232.22.2.6.1.1.1.6'; + my $oid_cpqRackNetConnectorSerialNum = '.1.3.6.1.4.1.232.22.2.6.1.1.1.7'; + my $oid_cpqRackNetConnectorPartNumber = '.1.3.6.1.4.1.232.22.2.6.1.1.1.8'; + my $oid_cpqRackNetConnectorSparePartNumber = '.1.3.6.1.4.1.232.22.2.6.1.1.1.9'; + my $oid_cpqRackNetConnectorDeviceType = '.1.3.6.1.4.1.232.22.2.6.1.1.1.17'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqRackNetConnectorPresent); + my @get_oids = (); + my @oids_end = (); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($present_map{$result->{$key}} ne 'present'); + $key =~ /\.([0-9]+)$/; + my $oid_end = $1; + + push @oids_end, $oid_end; + push @get_oids, $oid_cpqRackNetConnectorIndex . "." . $oid_end, $oid_cpqRackNetConnectorModel . "." . $oid_end, + $oid_cpqRackNetConnectorSerialNum . "." . $oid_end, $oid_cpqRackNetConnectorPartNumber . "." . $oid_end, + $oid_cpqRackNetConnectorSparePartNumber . "." . $oid_end, $oid_cpqRackNetConnectorDeviceType . "." . $oid_end; + } + $result = $self->{snmp}->get_leef(oids => \@get_oids); + foreach (@oids_end) { + my $nc_index = $result->{$oid_cpqRackNetConnectorIndex . '.' . $_}; + my $nc_model = $result->{$oid_cpqRackNetConnectorModel . '.' . $_}; + my $nc_serial = $result->{$oid_cpqRackNetConnectorSerialNum . '.' . $_}; + my $nc_part = $result->{$oid_cpqRackNetConnectorPartNumber . '.' . $_}; + my $nc_spare = $result->{$oid_cpqRackNetConnectorSparePartNumber . '.' . $_}; + my $nc_device = $result->{$oid_cpqRackNetConnectorDeviceType . '.' . $_}; + + $self->{components_nc}++; + $self->{output}->output_add(long_msg => sprintf("Network Connector %d (%s) type '%s' is present [serial: %s, part: %s, spare: %s].", + $nc_index, $nc_model, + $device_type{$nc_device}, + $nc_serial, $nc_part, $nc_spare + )); + } +} + +sub check_psu { + my ($self) = @_; + + # We dont check 'cpqRackPowerEnclosureTable' (the overall power system status) + # We check 'cpqRackPowerSupplyTable' (unitary) + + return if ($self->check_exclude('psu')); + + my $oid_cpqRackCommonEnclosureHasPowerSupplies = '.1.3.6.1.4.1.232.22.2.3.1.1.1.18.1'; + if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasPowerSupplies}}) && + $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasPowerSupplies}} =~ /^false$/i) { + $self->{output}->output_add(long_msg => sprintf("Skipping PSU: enclosure cannot house power supplies (??!!).")); + return ; + } + + my $oid_cpqRackPowerSupplyPresent = '.1.3.6.1.4.1.232.22.2.5.1.1.1.16'; + my $oid_cpqRackPowerSupplyIndex = '.1.3.6.1.4.1.232.22.2.5.1.1.1.3'; + my $oid_cpqRackPowerSupplySerialNum = '.1.3.6.1.4.1.232.22.2.5.1.1.1.5'; + my $oid_cpqRackPowerSupplyPartNumber = '.1.3.6.1.4.1.232.22.2.5.1.1.1.6'; + my $oid_cpqRackPowerSupplySparePartNumber = '.1.3.6.1.4.1.232.22.2.5.1.1.1.7'; + my $oid_cpqRackPowerSupplyStatus = '.1.3.6.1.4.1.232.22.2.5.1.1.1.14'; + my $oid_cpqRackPowerSupplyInputLineStatus = '.1.3.6.1.4.1.232.22.2.5.1.1.1.15'; + my $oid_cpqRackPowerSupplyCondition = '.1.3.6.1.4.1.232.22.2.5.1.1.1.17'; + my $oid_cpqRackPowerSupplyCurPwrOutput = '.1.3.6.1.4.1.232.22.2.5.1.1.1.10'; # Watts + my $oid_cpqRackPowerSupplyIntakeTemp = '.1.3.6.1.4.1.232.22.2.5.1.1.1.12'; + my $oid_cpqRackPowerSupplyExhaustTemp = '.1.3.6.1.4.1.232.22.2.5.1.1.1.13'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqRackPowerSupplyPresent); + my @get_oids = (); + my @oids_end = (); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($present_map{$result->{$key}} ne 'present'); + $key =~ /\.([0-9]+)$/; + my $oid_end = $1; + + push @oids_end, $oid_end; + push @get_oids, $oid_cpqRackPowerSupplyIndex . "." . $oid_end, $oid_cpqRackPowerSupplySerialNum . "." . $oid_end, + $oid_cpqRackPowerSupplyPartNumber . "." . $oid_end, $oid_cpqRackPowerSupplySparePartNumber . "." . $oid_end, + $oid_cpqRackPowerSupplyStatus . "." . $oid_end, $oid_cpqRackPowerSupplyInputLineStatus . "." . $oid_end, + $oid_cpqRackPowerSupplyCondition . "." . $oid_end, $oid_cpqRackPowerSupplyCurPwrOutput . "." . $oid_end, + $oid_cpqRackPowerSupplyIntakeTemp . "." . $oid_end, $oid_cpqRackPowerSupplyExhaustTemp . "." . $oid_end; + } + $result = $self->{snmp}->get_leef(oids => \@get_oids); + my $total_watts = 0; + foreach (@oids_end) { + my $psu_index = $result->{$oid_cpqRackPowerSupplyIndex . '.' . $_}; + my $psu_status = $result->{$oid_cpqRackPowerSupplyStatus . '.' . $_}; + my $psu_serial = $result->{$oid_cpqRackPowerSupplySerialNum . '.' . $_}; + my $psu_part = $result->{$oid_cpqRackPowerSupplyPartNumber . '.' . $_}; + my $psu_spare = $result->{$oid_cpqRackPowerSupplySparePartNumber . '.' . $_}; + my $psu_inputlinestatus = $result->{$oid_cpqRackPowerSupplyInputLineStatus . '.' . $_}; + my $psu_condition = $result->{$oid_cpqRackPowerSupplyCondition . '.' . $_}; + my $psu_pwrout = $result->{$oid_cpqRackPowerSupplyCurPwrOutput . '.' . $_}; + my $psu_intemp = $result->{$oid_cpqRackPowerSupplyIntakeTemp . '.' . $_}; + my $psu_exhtemp = $result->{$oid_cpqRackPowerSupplyExhaustTemp . '.' . $_}; + + $total_watts += $psu_pwrout; + $self->{components_psu}++; + $self->{output}->output_add(long_msg => sprintf("PSU %d status is %s [serial: %s, part: %s, spare: %s] (input line status %s) (status %s).", + $psu_index, ${$conditions{$psu_condition}}[0], + $psu_serial, $psu_part, $psu_spare, + $inputline_status{$psu_inputlinestatus}, + $psu_status{$psu_status} + )); + if ($psu_condition != 2) { + $self->{output}->output_add(severity => ${$conditions{$psu_condition}}[1], + short_msg => sprintf("PSU %d status is %s", + $psu_index, ${$conditions{$psu_condition}}[0])); + } + + $self->{output}->perfdata_add(label => "psu_" . $psu_index . "_power", unit => 'W', + value => $psu_pwrout); + if (defined($psu_intemp) && $psu_intemp != -1) { + $self->{output}->perfdata_add(label => "psu_" . $psu_index . "_temp_intake", unit => 'C', + value => $psu_intemp); + } + if (defined($psu_exhtemp) && $psu_exhtemp != -1) { + $self->{output}->perfdata_add(label => "psu_" . $psu_index . "_temp_exhaust", unit => 'C', + value => $psu_exhtemp); + } + } + + $self->{output}->perfdata_add(label => "total_power", unit => 'W', + value => $total_watts); +} + +sub check_temperatures { + my ($self) = @_; + + return if ($self->check_exclude('temperatures')); + + my $oid_cpqRackCommonEnclosureHasTempSensors = '.1.3.6.1.4.1.232.22.2.3.1.1.1.20.1'; + if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasTempSensors}}) && + $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasTempSensors}} =~ /^false$/i) { + $self->{output}->output_add(long_msg => sprintf("Skipping Temperatures: enclosure doesnt contain temperatures sensors.")); + return ; + } + + my $oid_cpqRackCommonEnclosureTempSensorIndex = '.1.3.6.1.4.1.232.22.2.3.1.2.1.3'; + my $oid_cpqRackCommonEnclosureTempSensorEnclosureName = '.1.3.6.1.4.1.232.22.2.3.1.2.1.4'; + my $oid_cpqRackCommonEnclosureTempLocation = '.1.3.6.1.4.1.232.22.2.3.1.2.1.5'; + my $oid_cpqRackCommonEnclosureTempCurrent = '.1.3.6.1.4.1.232.22.2.3.1.2.1.6'; + my $oid_cpqRackCommonEnclosureTempThreshold = '.1.3.6.1.4.1.232.22.2.3.1.2.1.7'; + my $oid_cpqRackCommonEnclosureTempCondition = '.1.3.6.1.4.1.232.22.2.3.1.2.1.8'; + my $oid_cpqRackCommonEnclosureTempType = '.1.3.6.1.4.1.232.22.2.3.1.2.1.9'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqRackCommonEnclosureTempSensorIndex); + my @get_oids = (); + my @oids_end = (); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + my $oid_end = $result->{$key}; + + push @oids_end, $oid_end; + push @get_oids, $oid_cpqRackCommonEnclosureTempSensorEnclosureName . "." . $oid_end, $oid_cpqRackCommonEnclosureTempLocation . "." . $oid_end, + $oid_cpqRackCommonEnclosureTempCurrent . "." . $oid_end, $oid_cpqRackCommonEnclosureTempThreshold . "." . $oid_end, + $oid_cpqRackCommonEnclosureTempCondition . "." . $oid_end, $oid_cpqRackCommonEnclosureTempType . "." . $oid_end; + } + $result = $self->{snmp}->get_leef(oids => \@get_oids); + foreach (@oids_end) { + my $temp_index = $_; + my $temp_name = $result->{$oid_cpqRackCommonEnclosureTempSensorEnclosureName . '.' . $_}; + my $temp_location = $result->{$oid_cpqRackCommonEnclosureTempLocation . '.' . $_}; + my $temp_current = $result->{$oid_cpqRackCommonEnclosureTempCurrent . '.' . $_}; + my $temp_threshold = $result->{$oid_cpqRackCommonEnclosureTempThreshold . '.' . $_}; + my $temp_condition = $result->{$oid_cpqRackCommonEnclosureTempCondition . '.' . $_}; + my $temp_type = $result->{$oid_cpqRackCommonEnclosureTempType . '.' . $_}; + + $self->{components_temperatures}++; + $self->{output}->output_add(long_msg => sprintf("Temperature %d status is %s [name: %s, location: %s] (value = %s, threshold = %s%s).", + $temp_index, ${$conditions{$temp_condition}}[0], + $temp_name, $temp_location, + $temp_current, $temp_threshold, + defined($map_temp_type{$temp_type}) ? ", status type = " . $map_temp_type{$temp_type} : '')); + if ($temp_condition != 2) { + $self->{output}->output_add(severity => ${$conditions{$temp_condition}}[1], + short_msg => sprintf("Temperature %d status is %s", + $temp_index, ${$conditions{$temp_condition}}[0])); + } + + $self->{output}->perfdata_add(label => "temp_" . $temp_index, unit => 'C', + value => $temp_current, + warning => $temp_threshold); + } +} + +sub check_fuse { + my ($self) = @_; + + return if ($self->check_exclude('fuse')); + + my $oid_cpqRackCommonEnclosureHasFuses = '.1.3.6.1.4.1.232.22.2.3.1.1.1.22.1'; + if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasFuses}}) && + $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasFuses}} =~ /^false$/i) { + $self->{output}->output_add(long_msg => sprintf("Skipping Fuse: enclosure doesnt contain fuse.")); + return ; + } + + my $oid_cpqRackCommonEnclosureFusePresent = '.1.3.6.1.4.1.232.22.2.3.1.4.1.6'; + my $oid_cpqRackCommonEnclosureFuseIndex = '.1.3.6.1.4.1.232.22.2.3.1.4.1.3'; + my $oid_cpqRackCommonEnclosureFuseEnclosureName = '.1.3.6.1.4.1.232.22.2.3.1.4.1.4'; + my $oid_cpqRackCommonEnclosureFuseLocation = '.1.3.6.1.4.1.232.22.2.3.1.4.1.5'; + my $oid_cpqRackCommonEnclosureFuseCondition = '.1.3.6.1.4.1.232.22.2.3.1.4.1.7'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqRackCommonEnclosureFusePresent); + my @get_oids = (); + my @oids_end = (); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($present_map{$result->{$key}} ne 'present'); + $key =~ /\.([0-9]+)$/; + my $oid_end = $1; + + push @oids_end, $oid_end; + push @get_oids, $oid_cpqRackCommonEnclosureFuseIndex . "." . $oid_end, $oid_cpqRackCommonEnclosureFuseEnclosureName . "." . $oid_end, + $oid_cpqRackCommonEnclosureFuseLocation . "." . $oid_end, $oid_cpqRackCommonEnclosureFuseCondition . "." . $oid_end; + } + $result = $self->{snmp}->get_leef(oids => \@get_oids); + foreach (@oids_end) { + my $fuse_index = $result->{$oid_cpqRackCommonEnclosureFuseIndex . '.' . $_}; + my $fuse_name = $result->{$oid_cpqRackCommonEnclosureFuseEnclosureName . '.' . $_}; + my $fuse_location = $result->{$oid_cpqRackCommonEnclosureFuseLocation . '.' . $_}; + my $fuse_condition = $result->{$oid_cpqRackCommonEnclosureFuseCondition . '.' . $_}; + + $self->{components_fuse}++; + $self->{output}->output_add(long_msg => sprintf("Fuse %d status is %s [name: %s, location: %s].", + $fuse_index, ${$conditions{$fuse_condition}}[0], + $fuse_name, $fuse_location)); + if ($fuse_condition != 2) { + $self->{output}->output_add(severity => ${$conditions{$fuse_condition}}[1], + short_msg => sprintf("Fuse %d status is %s", + $fuse_index, ${$conditions{$fuse_condition}}[0])); + } + } +} + +sub check_exclude { + my ($self, $section) = @_; + + if (defined($self->{option_results}->{exclude}) && $self->{option_results}->{exclude} =~ /(^|\s|,)$section(\s|,|$)/) { + $self->{output}->output_add(long_msg => sprintf("Skipping $section section.")); + return 1; + } + return 0; +} + +1; + +__END__ + +=head1 MODE + +Check Hardware (Fans, Power Supplies, Blades, Temperatures, Fuses). + +=over 8 + +=item B<--exclude> + +Exclude some parts (comma seperated list) (Example: --exclude=temperatures,psu). + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/hardware/server/hpbladechassis/plugin.pm b/centreon/lib/perl/plugins/hardware/server/hpbladechassis/plugin.pm new file mode 100644 index 00000000000..7b48efa1c7a --- /dev/null +++ b/centreon/lib/perl/plugins/hardware/server/hpbladechassis/plugin.pm @@ -0,0 +1,64 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package hardware::server::hpbladechassis::plugin; + +use strict; +use warnings; +use base qw(centreon::plugins::script_snmp); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '1.0'; + %{$self->{modes}} = ( + 'hardware' => 'hardware::server::hpbladechassis::mode::hardware', + ); + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check HP Blades chassis in SNMP. + +=cut From 3557e937f83cd48bf8d0762865c68a2574543878 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sun, 10 Nov 2013 23:10:24 +0100 Subject: [PATCH 135/458] + Working on proliant --- .../server/hpbladechassis/mode/hardware.pm | 30 +- .../server/hpproliant/mode/hardware.pm | 396 ++++++++++++++++++ .../hardware/server/hpproliant/plugin.pm | 64 +++ 3 files changed, 482 insertions(+), 8 deletions(-) create mode 100644 centreon/lib/perl/plugins/hardware/server/hpproliant/mode/hardware.pm create mode 100644 centreon/lib/perl/plugins/hardware/server/hpproliant/plugin.pm diff --git a/centreon/lib/perl/plugins/hardware/server/hpbladechassis/mode/hardware.pm b/centreon/lib/perl/plugins/hardware/server/hpbladechassis/mode/hardware.pm index dbc6f277929..ecb3982edb9 100644 --- a/centreon/lib/perl/plugins/hardware/server/hpbladechassis/mode/hardware.pm +++ b/centreon/lib/perl/plugins/hardware/server/hpbladechassis/mode/hardware.pm @@ -45,7 +45,7 @@ my %conditions = (1 => ['other', 'CRITICAL'], 3 => ['degraded', 'WARNING'], 4 => ['failed', 'CRITICAL']); my %present_map = (1 => 'other', - 2 => 'absent', + 2 => 'absent', 3 => 'present', 4 => 'Weird!!!', # for blades it can return 4, which is NOT spesified in MIB ); @@ -192,6 +192,7 @@ sub check_managers { if ($self->{output}->is_status(compare => 'ok', litteral => 1)) { return ; } + $self->{output}->output_add(long_msg => "Checking managers"); my $oid_cpqRackCommonEnclosureManagerIndex = '.1.3.6.1.4.1.232.22.2.3.1.6.1.3'; my $oid_cpqRackCommonEnclosureManagerPartNumber = '.1.3.6.1.4.1.232.22.2.3.1.6.1.6'; @@ -201,6 +202,7 @@ sub check_managers { my $oid_cpqRackCommonEnclosureManagerCondition = '.1.3.6.1.4.1.232.22.2.3.1.6.1.12'; my $result = $self->{snmp}->get_table(oid => $oid_cpqRackCommonEnclosureManagerIndex); + return if (scalar(keys %$result) <= 0); $self->{snmp}->load(oids => [$oid_cpqRackCommonEnclosureManagerPartNumber, $oid_cpqRackCommonEnclosureManagerSparePartNumber, $oid_cpqRackCommonEnclosureManagerSerialNum, $oid_cpqRackCommonEnclosureManagerRole, @@ -231,12 +233,13 @@ sub check_managers { sub check_fans { my ($self) = @_; + $self->{output}->output_add(long_msg => "Checking fans"); return if ($self->check_exclude('fans')); my $oid_cpqRackCommonEnclosureHasFans = '.1.3.6.1.4.1.232.22.2.3.1.1.1.21.1'; if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasFans}}) && $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasFans}} =~ /^false$/i) { - $self->{output}->output_add(long_msg => sprintf("Skipping Fans: enclosure cannot house fans (??!!).")); + $self->{output}->output_add(long_msg => "Skipping Fans: enclosure cannot house fans (??!!)."); return ; } @@ -247,6 +250,7 @@ sub check_fans { my $oid_cpqRackCommonEnclosureFanCondition = '.1.3.6.1.4.1.232.22.2.3.1.3.1.11'; my $result = $self->{snmp}->get_table(oid => $oid_cpqRackCommonEnclosureFanPresent); + return if (scalar(keys %$result) <= 0); my @get_oids = (); my @oids_end = (); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { @@ -279,12 +283,13 @@ sub check_fans { sub check_blades { my ($self) = @_; + $self->{output}->output_add(long_msg => "Checking blades"); return if ($self->check_exclude('blades')); my $oid_cpqRackCommonEnclosureHasServerBlades = '.1.3.6.1.4.1.232.22.2.3.1.1.1.17.1'; if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasServerBlades}}) && $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasServerBlades}} =~ /^false$/i) { - $self->{output}->output_add(long_msg => sprintf("Skipping Blades: enclosure cannot house blades (??!!).")); + $self->{output}->output_add(long_msg => "Skipping Blades: enclosure cannot house blades (??!!)."); return ; } @@ -298,6 +303,7 @@ sub check_blades { my $oid_cpqRackServerBladeFaultDiagnosticString = '.1.3.6.1.4.1.232.22.2.4.1.1.1.24'; # v2 my $result = $self->{snmp}->get_table(oid => $oid_cpqRackServerBladePresent); + return if (scalar(keys %$result) <= 0); my @get_oids = (); my @oids_end = (); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { @@ -348,12 +354,13 @@ sub check_blades { sub check_iom { my ($self) = @_; + $self->{output}->output_add(long_msg => "Checking network connectors"); return if ($self->check_exclude('network')); my $oid_cpqRackCommonEnclosureHasNetConnectors = '.1.3.6.1.4.1.232.22.2.3.1.1.1.19.1'; if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasNetConnectors}}) && $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasNetConnectors}} =~ /^false$/i) { - $self->{output}->output_add(long_msg => sprintf("Skipping Network Connectors: enclosure cannot house network connectors (??!!).")); + $self->{output}->output_add(long_msg => "Skipping Network Connectors: enclosure cannot house network connectors (??!!)."); return ; } @@ -366,6 +373,7 @@ sub check_iom { my $oid_cpqRackNetConnectorDeviceType = '.1.3.6.1.4.1.232.22.2.6.1.1.1.17'; my $result = $self->{snmp}->get_table(oid => $oid_cpqRackNetConnectorPresent); + return if (scalar(keys %$result) <= 0); my @get_oids = (); my @oids_end = (); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { @@ -402,12 +410,13 @@ sub check_psu { # We dont check 'cpqRackPowerEnclosureTable' (the overall power system status) # We check 'cpqRackPowerSupplyTable' (unitary) + $self->{output}->output_add(long_msg => "Checking power supplies"); return if ($self->check_exclude('psu')); my $oid_cpqRackCommonEnclosureHasPowerSupplies = '.1.3.6.1.4.1.232.22.2.3.1.1.1.18.1'; if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasPowerSupplies}}) && $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasPowerSupplies}} =~ /^false$/i) { - $self->{output}->output_add(long_msg => sprintf("Skipping PSU: enclosure cannot house power supplies (??!!).")); + $self->{output}->output_add(long_msg => "Skipping PSU: enclosure cannot house power supplies (??!!)."); return ; } @@ -424,6 +433,7 @@ sub check_psu { my $oid_cpqRackPowerSupplyExhaustTemp = '.1.3.6.1.4.1.232.22.2.5.1.1.1.13'; my $result = $self->{snmp}->get_table(oid => $oid_cpqRackPowerSupplyPresent); + return if (scalar(keys %$result) <= 0); my @get_oids = (); my @oids_end = (); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { @@ -485,12 +495,13 @@ sub check_psu { sub check_temperatures { my ($self) = @_; + $self->{output}->output_add(long_msg => "Checking temperatures"); return if ($self->check_exclude('temperatures')); my $oid_cpqRackCommonEnclosureHasTempSensors = '.1.3.6.1.4.1.232.22.2.3.1.1.1.20.1'; if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasTempSensors}}) && $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasTempSensors}} =~ /^false$/i) { - $self->{output}->output_add(long_msg => sprintf("Skipping Temperatures: enclosure doesnt contain temperatures sensors.")); + $self->{output}->output_add(long_msg => "Skipping Temperatures: enclosure doesnt contain temperatures sensors."); return ; } @@ -503,6 +514,7 @@ sub check_temperatures { my $oid_cpqRackCommonEnclosureTempType = '.1.3.6.1.4.1.232.22.2.3.1.2.1.9'; my $result = $self->{snmp}->get_table(oid => $oid_cpqRackCommonEnclosureTempSensorIndex); + return if (scalar(keys %$result) <= 0); my @get_oids = (); my @oids_end = (); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { @@ -544,12 +556,13 @@ sub check_temperatures { sub check_fuse { my ($self) = @_; + $self->{output}->output_add(long_msg => "Checking fuse"); return if ($self->check_exclude('fuse')); - + my $oid_cpqRackCommonEnclosureHasFuses = '.1.3.6.1.4.1.232.22.2.3.1.1.1.22.1'; if (defined($map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasFuses}}) && $map_has{$self->{global_results}->{$oid_cpqRackCommonEnclosureHasFuses}} =~ /^false$/i) { - $self->{output}->output_add(long_msg => sprintf("Skipping Fuse: enclosure doesnt contain fuse.")); + $self->{output}->output_add(long_msg => "Skipping Fuse: enclosure doesnt contain fuse."); return ; } @@ -560,6 +573,7 @@ sub check_fuse { my $oid_cpqRackCommonEnclosureFuseCondition = '.1.3.6.1.4.1.232.22.2.3.1.4.1.7'; my $result = $self->{snmp}->get_table(oid => $oid_cpqRackCommonEnclosureFusePresent); + return if (scalar(keys %$result) <= 0); my @get_oids = (); my @oids_end = (); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { diff --git a/centreon/lib/perl/plugins/hardware/server/hpproliant/mode/hardware.pm b/centreon/lib/perl/plugins/hardware/server/hpproliant/mode/hardware.pm new file mode 100644 index 00000000000..238663d9e90 --- /dev/null +++ b/centreon/lib/perl/plugins/hardware/server/hpproliant/mode/hardware.pm @@ -0,0 +1,396 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package hardware::server::hpproliant::mode::hardware; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %cpustatus = ( + 1 => ['unknown', 'UNKNOWN'], + 2 => ['ok', 'OK'], + 3 => ['degraded', 'WARNING'], + 4 => ['failed', 'CRITICAL'], + 5 => ['disabled', 'OK'] +); +my %conditions = ( + 1 => ['other', 'CRITICAL'], + 2 => ['ok', 'OK'], + 3 => ['degraded', 'WARNING'], + 4 => ['failed', 'CRITICAL'] +); +my %present_map = ( + 1 => 'other', + 2 => 'absent', + 3 => 'present', +); +my %redundant_map = ( + 1 => 'other', + 2 => 'not redundant', + 3 => 'redundant', +); +my %psustatus = ( + 1 => 'noError', + 2 => 'generalFailure', + 3 => 'bistFailure', + 4 => 'fanFailure', + 5 => 'tempFailure', + 6 => 'interlockOpen', + 7 => 'epromFailed', + 8 => 'vrefFailed', + 9 => 'dacFailed', + 10 => 'ramTestFailed', + 11 => 'voltageChannelFailed', + 12 => 'orringdiodeFailed', + 13 => 'brownOut', + 14 => 'giveupOnStartup', + 15 => 'nvramInvalid', + 16 => 'calibrationTableInvalid', +); +my %fan_location = ( + 1 => "other", + 2 => "unknown", + 3 => "system", + 4 => "systemBoard", + 5 => "ioBoard", + 6 => "cpu", + 7 => "memory", + 8 => "storage", + 9 => "removableMedia", + 10 => "powerSupply", + 11 => "ambient", + 12 => "chassis", + 13 => "bridgeCard", +); +my %fanspeed = ( + 1 => "other", + 2 => "normal", + 3 => "high", +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "exclude" => { name => 'exclude' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->{components_cpu} = 0; + $self->{components_psu} = 0; + $self->{components_pc} = 0; + $self->{components_fan} = 0; + + # In 'CPQSINFO-MIB' + # my $cpqSiSysSerialNum = "1.3.6.1.4.1.232.2.2.2.1.0"; + # my $cpqSiProductName = "1.3.6.1.4.1.232.2.2.4.2.0"; + # my $cpqSeSysRomVer = "1.3.6.1.4.1.232.1.2.6.1.0"; + + $self->check_cpu(); + $self->check_psu(); + $self->check_pc(); + $self->check_fan(); + +# $self->{output}->output_add(severity => 'OK', +# short_msg => sprintf("All %d components [%d fans, %d blades, %d network connectors, %d psu, %d temperatures, %d fuses] are ok.", +# ($self->{components_fans} + $self->{components_blades} + $self->{components_nc} + $self->{components_psu} + $self->{components_temperatures} + $self->{components_fuse}), +# $self->{components_fans}, $self->{components_blades}, $self->{components_nc}, $self->{components_psu}, $self->{components_temperatures}, $self->{components_fuse})); + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub check_cpu { + my ($self) = @_; + # In MIB 'CPQSTDEQ-MIB.mib' + + $self->{output}->output_add(long_msg => "Checking cpu"); + return if ($self->check_exclude('cpu')); + + my $oid_cpqSeCpuUnitIndex = '.1.3.6.1.4.1.232.1.2.2.1.1.1'; + my $oid_cpqSeCpuSlot = '.1.3.6.1.4.1.232.1.2.2.1.1.2'; + my $oid_cpqSeCpuName = '.1.3.6.1.4.1.232.1.2.2.1.1.3'; + my $oid_cpqSeCpuStatus = '.1.3.6.1.4.1.232.1.2.2.1.1.6'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqSeCpuUnitIndex); + return if (scalar(keys %$result) <= 0); + + $self->{snmp}->load(oids => [$oid_cpqSeCpuSlot, $oid_cpqSeCpuName, + $oid_cpqSeCpuStatus], + instances => [keys %$result]); + my $result2 = $self->{snmp}->get_leef(); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + $key =~ /(\d+)$/; + my $instance = $1; + + my $cpu_slot = $result2->{$oid_cpqSeCpuSlot . '.' . $instance}; + my $cpu_name = $result2->{$oid_cpqSeCpuName . '.' . $instance}; + my $cpu_status = $result2->{$oid_cpqSeCpuStatus . '.' . $instance}; + + $self->{components_cpu}++; + $self->{output}->output_add(long_msg => sprintf("cpu [slot: %s, unit: %s, name: %s] status is %s.", + $cpu_slot, $result->{$key}, $cpu_name, + ${$cpustatus{$cpu_status}}[0])); + if (${$cpustatus{$cpu_status}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$cpustatus{$cpu_status}}[1], + short_msg => sprintf("cpu %d is %s", + $result->{$key}, ${$cpustatus{$cpu_status}}[0])); + } + } +} + +sub check_psu { + my ($self) = @_; + + # In MIB 'CPQHLTH-MIB.mib' + $self->{output}->output_add(long_msg => "Checking power supplies"); + return if ($self->check_exclude('psu')); + + my $oid_cpqHeFltTolPowerSupplyPresent = '.1.3.6.1.4.1.232.6.2.9.3.1.3'; + my $oid_cpqHeFltTolPowerSupplyChassis = '.1.3.6.1.4.1.232.6.2.9.3.1.1'; + my $oid_cpqHeFltTolPowerSupplyBay = '.1.3.6.1.4.1.232.6.2.9.3.1.2'; + my $oid_cpqHeFltTolPowerSupplyCondition = '.1.3.6.1.4.1.232.6.2.9.3.1.4'; + my $oid_cpqHeFltTolPowerSupplyStatus = '.1.3.6.1.4.1.232.6.2.9.3.1.5'; + my $oid_cpqHeFltTolPowerSupplyRedundant = '.1.3.6.1.4.1.232.6.2.9.3.1.9'; + my $oid_cpqHeFltTolPowerSupplyCapacityUsed = '.1.3.6.1.4.1.232.6.2.9.3.1.7'; # Watts + my $oid_cpqHeFltTolPowerSupplyCapacityMaximum = '.1.3.6.1.4.1.232.6.2.9.3.1.8'; + my $oid_cpqHeFltTolPowerSupplyMainVoltage = '.1.3.6.1.4.1.232.6.2.9.3.1.6'; # Volts + my $oid_cpqHeFltTolPowerSupplyRedundantPartner = '.1.3.6.1.4.1.232.6.2.9.3.1.17'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqHeFltTolPowerSupplyPresent); + return if (scalar(keys %$result) <= 0); + my @get_oids = (); + my @oids_end = (); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($present_map{$result->{$key}} ne 'present'); + $key =~ /\.([0-9]+)$/; + my $oid_end = $1; + + push @oids_end, $oid_end; + push @get_oids, $oid_cpqHeFltTolPowerSupplyChassis . "." . $oid_end, $oid_cpqHeFltTolPowerSupplyBay . "." . $oid_end, + $oid_cpqHeFltTolPowerSupplyCondition . "." . $oid_end, $oid_cpqHeFltTolPowerSupplyStatus . "." . $oid_end, + $oid_cpqHeFltTolPowerSupplyRedundant . "." . $oid_end, $oid_cpqHeFltTolPowerSupplyCapacityUsed . "." . $oid_end, + $oid_cpqHeFltTolPowerSupplyCapacityMaximum . "." . $oid_end, $oid_cpqHeFltTolPowerSupplyMainVoltage . "." . $oid_end, + $oid_cpqHeFltTolPowerSupplyRedundantPartner . "." . $oid_end; + } + $result = $self->{snmp}->get_leef(oids => \@get_oids); + my $total_watts = 0; + foreach (@oids_end) { + my $psu_chassis = $result->{$oid_cpqHeFltTolPowerSupplyChassis . '.' . $_}; + my $psu_bay = $result->{$oid_cpqHeFltTolPowerSupplyBay . '.' . $_}; + my $psu_condition = $result->{$oid_cpqHeFltTolPowerSupplyCondition . '.' . $_}; + my $psu_status = $result->{$oid_cpqHeFltTolPowerSupplyStatus . '.' . $_}; + my $psu_redundant = $result->{$oid_cpqHeFltTolPowerSupplyRedundant . '.' . $_}; + my $psu_redundantpartner = $result->{$oid_cpqHeFltTolPowerSupplyRedundantPartner . '.' . $_}; + my $psu_capacityused = $result->{$oid_cpqHeFltTolPowerSupplyCapacityUsed . '.' . $_}; + my $psu_capacitymaximum = $result->{$oid_cpqHeFltTolPowerSupplyCapacityMaximum . '.' . $_}; + my $psu_voltage = $result->{$oid_cpqHeFltTolPowerSupplyMainVoltage . '.' . $_}; + + $self->{components_psu}++; + $self->{output}->output_add(long_msg => sprintf("powersupply %d status is %s [chassis: %s, redundance: %s, redundant partner: %s] (status %s).", + $psu_bay, ${$conditions{$psu_condition}}[0], + $psu_chassis, $redundant_map{$psu_redundant}, $psu_redundantpartner, + $psustatus{$psu_status} + )); + if ($psu_condition != 2) { + $self->{output}->output_add(severity => ${$conditions{$psu_condition}}[1], + short_msg => sprintf("powersupply %d status is %s", + $psu_bay, ${$conditions{$psu_condition}}[0])); + } + + $self->{output}->perfdata_add(label => "psu_" . $psu_bay . "_power", unit => 'W', + value => $psu_capacityused, + critical => $psu_capacitymaximum); + $self->{output}->perfdata_add(label => "psu_" . $psu_bay . "_voltage", unit => 'V', + value => $psu_voltage); + } +} + +sub check_pc { + my ($self) = @_; + + # In MIB 'CPQHLTH-MIB.mib' + $self->{output}->output_add(long_msg => "Checking power converters"); + return if ($self->check_exclude('pc')); + + my $oid_cpqHePwrConvPresent = '.1.3.6.1.4.1.232.6.2.13.3.1.3'; + my $oid_cpqHePwrConvIndex = '.1.3.6.1.4.1.232.6.2.13.3.1.2'; + my $oid_cpqHePwrConvChassis = '.1.3.6.1.4.1.232.6.2.13.3.1.1'; + my $oid_cpqHePwrConvCondition = '.1.3.6.1.4.1.232.6.2.13.3.1.8'; + my $oid_cpqHePwrConvRedundant = '.1.3.6.1.4.1.232.6.2.13.3.1.6'; + my $oid_cpqHePwrConvRedundantGroupId = '.1.3.6.1.4.1.232.6.2.13.3.1.7'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqHePwrConvPresent); + return if (scalar(keys %$result) <= 0); + my @get_oids = (); + my @oids_end = (); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($present_map{$result->{$key}} ne 'present'); + $key =~ /\.([0-9]+)$/; + my $oid_end = $1; + + push @oids_end, $oid_end; + push @get_oids, $oid_cpqHePwrConvIndex . "." . $oid_end, $oid_cpqHePwrConvChassis . "." . $oid_end, + $oid_cpqHePwrConvCondition . "." . $oid_end, $oid_cpqHePwrConvRedundant . "." . $oid_end, + $oid_cpqHePwrConvRedundantGroupId . "." . $oid_end; + } + $result = $self->{snmp}->get_leef(oids => \@get_oids); + foreach (@oids_end) { + my $pc_chassis = $result->{$oid_cpqHePwrConvChassis . '.' . $_}; + my $pc_index = $result->{$oid_cpqHePwrConvIndex . '.' . $_}; + my $pc_condition = $result->{$oid_cpqHePwrConvIndex . '.' . $_}; + my $pc_redundant = $result->{$oid_cpqHePwrConvRedundant . '.' . $_}; + my $pc_redundantgroup = $result->{$oid_cpqHePwrConvRedundantGroupId . '.' . $_}; + + $self->{components_psu}++; + $self->{output}->output_add(long_msg => sprintf("powerconverter %d status is %s [chassis: %s, redundance: %s, redundant group: %s].", + $pc_index, ${$conditions{$pc_condition}}[0], + $pc_chassis, $redundant_map{$pc_redundant}, $pc_redundantgroup + )); + if ($pc_condition != 2) { + $self->{output}->output_add(severity => ${$conditions{$pc_condition}}[1], + short_msg => sprintf("powerconverter %d status is %s", + $pc_index, ${$conditions{$pc_condition}}[0])); + } + } +} + +sub check_fan { + my ($self) = @_; + + # In MIB 'CPQHLTH-MIB.mib' + $self->{output}->output_add(long_msg => "Checking fans"); + return if ($self->check_exclude('fan')); + + my $oid_cpqHeFltTolFanPresent = '.1.3.6.1.4.1.232.6.2.6.7.1.4'; + my $oid_cpqHeFltTolFanChassis = '.1.3.6.1.4.1.232.6.2.6.7.1.1'; + my $oid_cpqHeFltTolFanIndex = '.1.3.6.1.4.1.232.6.2.6.7.1.2'; + my $oid_cpqHeFltTolFanLocale = '.1.3.6.1.4.1.232.6.2.6.7.1.3'; + my $oid_cpqHeFltTolFanCondition = '.1.3.6.1.4.1.232.6.2.6.7.1.9'; + my $oid_cpqHeFltTolFanSpeed = '.1.3.6.1.4.1.232.6.2.6.7.1.6'; + my $oid_cpqHeFltTolFanCurrentSpeed = '.1.3.6.1.4.1.232.6.2.6.7.1.12'; + my $oid_cpqHeFltTolFanRedundant = '.1.3.6.1.4.1.232.6.2.6.7.1.7'; + my $oid_cpqHeFltTolFanRedundantPartner = '.1.3.6.1.4.1.232.6.2.6.7.1.8'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqHeFltTolFanPresent); + return if (scalar(keys %$result) <= 0); + my @get_oids = (); + my @oids_end = (); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($present_map{$result->{$key}} ne 'present'); + $key =~ /\.([0-9]+)$/; + my $oid_end = $1; + + push @oids_end, $oid_end; + push @get_oids, $oid_cpqHeFltTolFanChassis . "." . $oid_end, $oid_cpqHeFltTolFanIndex . "." . $oid_end, + $oid_cpqHeFltTolFanLocale . "." . $oid_end, $oid_cpqHeFltTolFanCondition . "." . $oid_end, + $oid_cpqHeFltTolFanCurrentSpeed . "." . $oid_end, $oid_cpqHeFltTolFanSpeed . "." . $oid_end, + $oid_cpqHeFltTolFanRedundant . "." . $oid_end, $oid_cpqHeFltTolFanRedundantPartner . "." . $oid_end; + } + $result = $self->{snmp}->get_leef(oids => \@get_oids); + my $total_watts = 0; + foreach (@oids_end) { + my $fan_chassis = $result->{$oid_cpqHeTemperatureCelsius . '.' . $_}; + my $fan_index = $result->{$oid_cpqHeFltTolFanIndex . '.' . $_}; + my $fan_locale = $result->{$oid_cpqHeFltTolFanLocale . '.' . $_}; + my $fan_condition = $result->{$oid_cpqHeFltTolFanCondition . '.' . $_}; + my $fan_speed = $result->{$oid_cpqHeFltTolFanSpeed . '.' . $_}; + my $fan_currentspeed = $result->{$oid_cpqHeFltTolFanCurrentSpeed . '.' . $_}; + my $fan_redundant = $result->{$oid_cpqHeFltTolFanRedundant . '.' . $_}; + my $fan_redundantpartner = $result->{$oid_cpqHeFltTolFanRedundantPartner . '.' . $_}; + + $self->{components_fan}++; + $self->{output}->output_add(long_msg => sprintf("fan %d status is %s, speed is %s [chassis: %s, location: %s, redundance: %s, redundant partner: %s].", + $fan_index, ${$conditions{$fan_condition}}[0], $fanspeed{$fan_speed}, + $fan_chassis, $fan_location{$fan_locale}, + $redundant_map{$fan_redundant}, $fan_redundantpartner + )); + if ($fan_condition != 2) { + $self->{output}->output_add(severity => ${$conditions{$fan_condition}}[1], + short_msg => sprintf("fan %d status is %s", + $fan_index, ${$conditions{$fan_condition}}[0])); + } + + $self->{output}->perfdata_add(label => "fan_" . $fan_index . "_speed", unit => 'rpm', + value => $fan_currentspeed); + } +} + +sub check_exclude { + my ($self, $section) = @_; + + if (defined($self->{option_results}->{exclude}) && $self->{option_results}->{exclude} =~ /(^|\s|,)$section(\s|,|$)/) { + $self->{output}->output_add(long_msg => sprintf("Skipping $section section.")); + return 1; + } + return 0; +} + +1; + +__END__ + +=head1 MODE + +Check Hardware (CPUs, Power Supplies, Power converters, Fans). + +=over 8 + +=item B<--exclude> + +Exclude some parts (comma seperated list) (Example: --exclude=psu,pc). + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/hardware/server/hpproliant/plugin.pm b/centreon/lib/perl/plugins/hardware/server/hpproliant/plugin.pm new file mode 100644 index 00000000000..023c4f6807b --- /dev/null +++ b/centreon/lib/perl/plugins/hardware/server/hpproliant/plugin.pm @@ -0,0 +1,64 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package hardware::server::hpproliant::plugin; + +use strict; +use warnings; +use base qw(centreon::plugins::script_snmp); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '1.0'; + %{$self->{modes}} = ( + 'hardware' => 'hardware::server::hpproliant::mode::hardware', + ); + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check HP Proliant servers in SNMP. + +=cut From 7309c573e2906f6f1020cf18a1b662960d3edb27 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Mon, 11 Nov 2013 22:14:52 +0100 Subject: [PATCH 136/458] + Work onhp servers --- centreon/lib/perl/centreon/plugins/misc.pm | 8 + .../server/hpproliant/mode/hardware.pm | 242 ++++++++++++++++-- 2 files changed, 224 insertions(+), 26 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/misc.pm b/centreon/lib/perl/centreon/plugins/misc.pm index a921d1b97ed..598d4bbecd2 100644 --- a/centreon/lib/perl/centreon/plugins/misc.pm +++ b/centreon/lib/perl/centreon/plugins/misc.pm @@ -129,6 +129,14 @@ sub backtick { return (0, join("\n", @output), $return_code); } +sub trim { + # Sometimes there is a null character + $_[0] =~ s/\x00$//; + $_[0] =~ s/^[ \t]+//; + $_[0] =~ s/[ \t]+$//; + return $_[0]; +} + 1; __END__ diff --git a/centreon/lib/perl/plugins/hardware/server/hpproliant/mode/hardware.pm b/centreon/lib/perl/plugins/hardware/server/hpproliant/mode/hardware.pm index 238663d9e90..4e92ee88649 100644 --- a/centreon/lib/perl/plugins/hardware/server/hpproliant/mode/hardware.pm +++ b/centreon/lib/perl/plugins/hardware/server/hpproliant/mode/hardware.pm @@ -39,6 +39,7 @@ use base qw(centreon::plugins::mode); use strict; use warnings; +use centreon::plugins::misc; my %cpustatus = ( 1 => ['unknown', 'UNKNOWN'], @@ -81,7 +82,7 @@ my %psustatus = ( 15 => 'nvramInvalid', 16 => 'calibrationTableInvalid', ); -my %fan_location = ( +my %location_map = ( 1 => "other", 2 => "unknown", 3 => "system", @@ -101,6 +102,43 @@ my %fanspeed = ( 2 => "normal", 3 => "high", ); +my %map_pnic_role = ( + 1 => "unknown", + 2 => "primary", + 3 => "secondary", + 4 => "member", + 5 => "txRx", + 6 => "tx", + 7 => "standby", + 8 => "none", + 255 => "notApplicable", +); +my %map_nic_state = ( + 1 => "unknown", + 2 => "ok", + 3 => "standby", + 4 => "failed", +); +my %map_pnic_status = ( + 1 => "unknown", + 2 => "ok", + 3 => "generalFailure", + 4 => "linkFailure", +); +my %map_lnic_status = ( + 1 => "unknown", + 2 => "ok", + 3 => "primaryFailed", + 4 => "standbyFailed", + 5 => "groupFailed", + 6 => "redundancyReduced", + 7 => "redundancyLost", +); +my %map_nic_duplex = ( + 1 => "unknown", + 2 => "half", + 3 => "full", +); sub new { my ($class, %options) = @_; @@ -113,6 +151,9 @@ sub new { "exclude" => { name => 'exclude' }, }); + $self->{product_name} = undef; + $self->{serial} = undef; + $self->{romversion} = undef; return $self; } @@ -130,16 +171,18 @@ sub run { $self->{components_psu} = 0; $self->{components_pc} = 0; $self->{components_fan} = 0; - - # In 'CPQSINFO-MIB' - # my $cpqSiSysSerialNum = "1.3.6.1.4.1.232.2.2.2.1.0"; - # my $cpqSiProductName = "1.3.6.1.4.1.232.2.2.4.2.0"; - # my $cpqSeSysRomVer = "1.3.6.1.4.1.232.1.2.6.1.0"; - + $self->{components_temperature} = 0; + $self->{components_pnic} = 0; + $self->{components_lnic} = 0; + + $self->get_system_information(); $self->check_cpu(); $self->check_psu(); $self->check_pc(); $self->check_fan(); + $self->check_temperature(); + $self->check_pnic(); + $self->check_lnic(); # $self->{output}->output_add(severity => 'OK', # short_msg => sprintf("All %d components [%d fans, %d blades, %d network connectors, %d psu, %d temperatures, %d fuses] are ok.", @@ -150,6 +193,21 @@ sub run { $self->{output}->exit(); } +sub get_system_information { + my ($self) = @_; + + # In 'CPQSINFO-MIB' + my $oid_cpqSiSysSerialNum = "1.3.6.1.4.1.232.2.2.2.1.0"; + my $oid_cpqSiProductName = "1.3.6.1.4.1.232.2.2.4.2.0"; + my $oid_cpqSeSysRomVer = "1.3.6.1.4.1.232.1.2.6.1.0"; + + my $result = $self->{snmp}->get_leef(oids => [$oid_cpqSiSysSerialNum, $oid_cpqSiProductName, $oid_cpqSeSysRomVer]); + + $self->{product_name} = defined($result->{$oid_cpqSiProductName}) ? centreon::plugins::misc::trim($result->{$oid_cpqSiProductName}) : 'unknown'; + $self->{serial} = defined($result->{$oid_cpqSiSysSerialNum}) ? centreon::plugins::misc::trim($result->{$oid_cpqSiSysSerialNum}) : 'unknown'; + $self->{romversion} = defined($result->{$oid_cpqSeSysRomVer}) ? centreon::plugins::misc::trim($result->{$oid_cpqSeSysRomVer}) : 'unknown'; +} + sub check_cpu { my ($self) = @_; # In MIB 'CPQSTDEQ-MIB.mib' @@ -186,7 +244,7 @@ sub check_cpu { short_msg => sprintf("cpu %d is %s", $result->{$key}, ${$cpustatus{$cpu_status}}[0])); } - } + } } sub check_psu { @@ -213,21 +271,20 @@ sub check_psu { my @oids_end = (); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($present_map{$result->{$key}} ne 'present'); - $key =~ /\.([0-9]+)$/; + # Chassis + Bay + $key =~ /(\d+\.\d+)$/; my $oid_end = $1; push @oids_end, $oid_end; - push @get_oids, $oid_cpqHeFltTolPowerSupplyChassis . "." . $oid_end, $oid_cpqHeFltTolPowerSupplyBay . "." . $oid_end, + push @get_oids, $oid_cpqHeFltTolPowerSupplyCondition . "." . $oid_end, $oid_cpqHeFltTolPowerSupplyStatus . "." . $oid_end, $oid_cpqHeFltTolPowerSupplyRedundant . "." . $oid_end, $oid_cpqHeFltTolPowerSupplyCapacityUsed . "." . $oid_end, $oid_cpqHeFltTolPowerSupplyCapacityMaximum . "." . $oid_end, $oid_cpqHeFltTolPowerSupplyMainVoltage . "." . $oid_end, $oid_cpqHeFltTolPowerSupplyRedundantPartner . "." . $oid_end; } $result = $self->{snmp}->get_leef(oids => \@get_oids); - my $total_watts = 0; foreach (@oids_end) { - my $psu_chassis = $result->{$oid_cpqHeFltTolPowerSupplyChassis . '.' . $_}; - my $psu_bay = $result->{$oid_cpqHeFltTolPowerSupplyBay . '.' . $_}; + my ($psu_chassis, $psu_bay) = split /\./; my $psu_condition = $result->{$oid_cpqHeFltTolPowerSupplyCondition . '.' . $_}; my $psu_status = $result->{$oid_cpqHeFltTolPowerSupplyStatus . '.' . $_}; my $psu_redundant = $result->{$oid_cpqHeFltTolPowerSupplyRedundant . '.' . $_}; @@ -276,23 +333,22 @@ sub check_pc { my @oids_end = (); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($present_map{$result->{$key}} ne 'present'); - $key =~ /\.([0-9]+)$/; + # Chassis + index + $key =~ /(\d+\.\d+)$/; my $oid_end = $1; push @oids_end, $oid_end; - push @get_oids, $oid_cpqHePwrConvIndex . "." . $oid_end, $oid_cpqHePwrConvChassis . "." . $oid_end, - $oid_cpqHePwrConvCondition . "." . $oid_end, $oid_cpqHePwrConvRedundant . "." . $oid_end, + push @get_oids, $oid_cpqHePwrConvCondition . "." . $oid_end, $oid_cpqHePwrConvRedundant . "." . $oid_end, $oid_cpqHePwrConvRedundantGroupId . "." . $oid_end; } $result = $self->{snmp}->get_leef(oids => \@get_oids); foreach (@oids_end) { - my $pc_chassis = $result->{$oid_cpqHePwrConvChassis . '.' . $_}; - my $pc_index = $result->{$oid_cpqHePwrConvIndex . '.' . $_}; + my ($pc_chassis, $pc_index) = split /\./; my $pc_condition = $result->{$oid_cpqHePwrConvIndex . '.' . $_}; my $pc_redundant = $result->{$oid_cpqHePwrConvRedundant . '.' . $_}; my $pc_redundantgroup = $result->{$oid_cpqHePwrConvRedundantGroupId . '.' . $_}; - $self->{components_psu}++; + $self->{components_pc}++; $self->{output}->output_add(long_msg => sprintf("powerconverter %d status is %s [chassis: %s, redundance: %s, redundant group: %s].", $pc_index, ${$conditions{$pc_condition}}[0], $pc_chassis, $redundant_map{$pc_redundant}, $pc_redundantgroup @@ -328,20 +384,18 @@ sub check_fan { my @oids_end = (); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($present_map{$result->{$key}} ne 'present'); - $key =~ /\.([0-9]+)$/; + # Chassis + index + $key =~ /(\d+\.\d+)$/; my $oid_end = $1; push @oids_end, $oid_end; - push @get_oids, $oid_cpqHeFltTolFanChassis . "." . $oid_end, $oid_cpqHeFltTolFanIndex . "." . $oid_end, - $oid_cpqHeFltTolFanLocale . "." . $oid_end, $oid_cpqHeFltTolFanCondition . "." . $oid_end, + push @get_oids, $oid_cpqHeFltTolFanLocale . "." . $oid_end, $oid_cpqHeFltTolFanCondition . "." . $oid_end, $oid_cpqHeFltTolFanCurrentSpeed . "." . $oid_end, $oid_cpqHeFltTolFanSpeed . "." . $oid_end, $oid_cpqHeFltTolFanRedundant . "." . $oid_end, $oid_cpqHeFltTolFanRedundantPartner . "." . $oid_end; } $result = $self->{snmp}->get_leef(oids => \@get_oids); - my $total_watts = 0; foreach (@oids_end) { - my $fan_chassis = $result->{$oid_cpqHeTemperatureCelsius . '.' . $_}; - my $fan_index = $result->{$oid_cpqHeFltTolFanIndex . '.' . $_}; + my ($fan_chassis, $fan_index) = split /\./; my $fan_locale = $result->{$oid_cpqHeFltTolFanLocale . '.' . $_}; my $fan_condition = $result->{$oid_cpqHeFltTolFanCondition . '.' . $_}; my $fan_speed = $result->{$oid_cpqHeFltTolFanSpeed . '.' . $_}; @@ -352,7 +406,7 @@ sub check_fan { $self->{components_fan}++; $self->{output}->output_add(long_msg => sprintf("fan %d status is %s, speed is %s [chassis: %s, location: %s, redundance: %s, redundant partner: %s].", $fan_index, ${$conditions{$fan_condition}}[0], $fanspeed{$fan_speed}, - $fan_chassis, $fan_location{$fan_locale}, + $fan_chassis, $location_map{$fan_locale}, $redundant_map{$fan_redundant}, $fan_redundantpartner )); if ($fan_condition != 2) { @@ -366,6 +420,142 @@ sub check_fan { } } +sub check_temperature { + my ($self) = @_; + # In MIB 'CPQSTDEQ-MIB.mib' + + $self->{output}->output_add(long_msg => "Checking temperatures"); + return if ($self->check_exclude('temperature')); + + my $oid_cpqHeTemperatureEntry = '.1.3.6.1.4.1.232.6.2.6.8.1'; + my $oid_cpqHeTemperatureCondition = '.1.3.6.1.4.1.232.6.2.6.8.1.6'; + my $oid_cpqHeTemperatureLocale = '.1.3.6.1.4.1.232.6.2.6.8.1.3'; + my $oid_cpqHeTemperatureCelsius = '.1.3.6.1.4.1.232.6.2.6.8.1.4'; + my $oid_cpqHeTemperatureThreshold = '.1.3.6.1.4.1.232.6.2.6.8.1.5'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqHeTemperatureEntry); + return if (scalar(keys %$result) <= 0); + + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + # work when we have condition + next if ($key !~ /^$oid_cpqHeTemperatureCondition/); + # Chassis + index + $key =~ /(\d+)\.(\d+)$/; + my $temp_chassis = $1; + my $temp_index = $2; + my $instance = $temp_chassis . "." . $temp_index; + + my $temp_condition = $result->{$key}; + my $temp_current = $result->{$oid_cpqHeTemperatureCelsius . '.' . $instance}; + my $temp_threshold = $result->{$oid_cpqHeTemperatureThreshold . '.' . $instance}; + my $temp_locale = $result->{$oid_cpqHeTemperatureLocale . '.' . $instance}; + + $self->{components_temperature}++; + $self->{output}->output_add(long_msg => sprintf("%s %s temperature is %dC (%d max) (status is %s).", + $temp_index, $location_map{$temp_locale}, $temp_current, + $temp_threshold, + ${$conditions{$temp_condition}}[0])); + if (${$conditions{$temp_condition}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$conditions{$temp_condition}}[1], + short_msg => sprintf("temperature %d %s status is %s", + $temp_index, $location_map{$temp_locale}, ${$conditions{$temp_condition}}[0])); + } + + $self->{output}->perfdata_add(label => "temp_" . $temp_index . "_" . $location_map{$temp_locale}, unit => 'C', + value => $temp_current, + critical => (($temp_threshold != -1) ? $temp_threshold : -1)); + } +} + +sub check_pnic { + my ($self) = @_; + # In MIB 'CPQNIC-MIB.mib' + + $self->{output}->output_add(long_msg => "Checking physical nics"); + return if ($self->check_exclude('pnic')); + + my $oid_cpqNicIfPhysAdapterIndex = '.1.3.6.1.4.1.232.18.2.3.1.1.1'; + my $oid_cpqNicIfPhysAdapterRole = '.1.3.6.1.4.1.232.18.2.3.1.1.3'; + my $oid_cpqNicIfPhysAdapterCondition = '.1.3.6.1.4.1.232.18.2.3.1.1.12'; + my $oid_cpqNicIfPhysAdapterState = '.1.3.6.1.4.1.232.18.2.3.1.1.13'; + my $oid_cpqNicIfPhysAdapterStatus = '.1.3.6.1.4.1.232.18.2.3.1.1.14'; + my $oid_cpqNicIfPhysAdapterDuplexState = '.1.3.6.1.4.1.232.18.2.3.1.1.11'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqNicIfPhysAdapterIndex); + return if (scalar(keys %$result) <= 0); + + $self->{snmp}->load(oids => [$oid_cpqNicIfPhysAdapterRole, $oid_cpqNicIfPhysAdapterCondition, + $oid_cpqNicIfPhysAdapterState, $oid_cpqNicIfPhysAdapterStatus, + $oid_cpqNicIfPhysAdapterDuplexState], + instances => [keys %$result]); + my $result2 = $self->{snmp}->get_leef(); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + $key =~ /(\d+)$/; + my $instance = $1; + + my $nic_index = $result->{$key}; + my $nic_role = $result2->{$oid_cpqNicIfPhysAdapterRole . '.' . $instance}; + my $nic_condition = $result2->{$oid_cpqNicIfPhysAdapterCondition . '.' . $instance}; + my $nic_state = $result2->{$oid_cpqNicIfPhysAdapterState . '.' . $instance}; + my $nic_status = $result2->{$oid_cpqNicIfPhysAdapterStatus . '.' . $instance}; + my $nic_duplex = $result2->{$oid_cpqNicIfPhysAdapterDuplexState . '.' . $instance}; + + $self->{components_pnic}++; + $self->{output}->output_add(long_msg => sprintf("physical nic %s [duplex: %s, role: %s, state: %s, status: %s] condition is %s.", + $nic_index, $map_nic_duplex{$nic_duplex}, $map_pnic_role{$nic_role}, + $map_nic_state{$nic_state}, $map_pnic_status{$nic_status}, + ${$conditions{$nic_condition}}[0])); + if (${$conditions{$nic_condition}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$conditions{$nic_condition}}[1], + short_msg => sprintf("physical nic %d is %s", + $nic_index, ${$conditions{$nic_condition}}[0])); + } + } +} + +sub check_lnic { + my ($self) = @_; + # In MIB 'CPQNIC-MIB.mib' + + $self->{output}->output_add(long_msg => "Checking logical nics"); + return if ($self->check_exclude('pnic')); + + my $oid_cpqNicIfLogMapIndex = '.1.3.6.1.4.1.232.18.2.2.1.1.1'; + my $oid_cpqNicIfLogMapDescription = '.1.3.6.1.4.1.232.18.2.2.1.1.3'; + my $oid_cpqNicIfLogMapAdapterCount = '.1.3.6.1.4.1.232.18.2.2.1.1.5'; + my $oid_cpqNicIfLogMapCondition = '.1.3.6.1.4.1.232.18.2.2.1.1.10'; + my $oid_cpqNicIfLogMapStatus = '.1.3.6.1.4.1.232.18.2.2.1.1.11'; + + my $result = $self->{snmp}->get_table(oid => $oid_cpqNicIfLogMapIndex); + return if (scalar(keys %$result) <= 0); + + $self->{snmp}->load(oids => [$oid_cpqNicIfLogMapDescription, $oid_cpqNicIfLogMapAdapterCount, + $oid_cpqNicIfLogMapCondition, $oid_cpqNicIfLogMapStatus], + instances => [keys %$result]); + my $result2 = $self->{snmp}->get_leef(); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + $key =~ /(\d+)$/; + my $instance = $1; + + my $nic_index = $result->{$key}; + my $nic_description = centreon::plugins::misc::trim($result2->{$oid_cpqNicIfLogMapDescription . '.' . $instance}); + my $nic_count = $result2->{$oid_cpqNicIfLogMapAdapterCount . '.' . $instance}; + my $nic_condition = $result2->{$oid_cpqNicIfLogMapCondition . '.' . $instance}; + my $nic_status = $result2->{$oid_cpqNicIfLogMapStatus . '.' . $instance}; + + $self->{components_lnic}++; + $self->{output}->output_add(long_msg => sprintf("logical nic %s [adapter count: %s, description: %s, status: %s] condition is %s.", + $nic_index, $nic_count, $nic_description, + $map_lnic_status{$nic_status}, + ${$conditions{$nic_condition}}[0])); + if (${$conditions{$nic_condition}}[0] !~ /^other|ok$/i) { + $self->{output}->output_add(severity => ${$conditions{$nic_condition}}[1], + short_msg => sprintf("logical nic %d is %s (%s)", + $nic_index, ${$conditions{$nic_condition}}[0], $map_lnic_status{$nic_status})); + } + } +} + sub check_exclude { my ($self, $section) = @_; From 6601c7db36bca01fb97d5e9bd481ec92b5e03502 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Tue, 12 Nov 2013 21:16:03 +0100 Subject: [PATCH 137/458] + Add plugin HP LeftHand (mode hardware) --- .../storage/hplefthand/mode/hardware.pm | 522 ++++++++++++++++++ .../perl/plugins/storage/hplefthand/plugin.pm | 64 +++ 2 files changed, 586 insertions(+) create mode 100644 centreon/lib/perl/plugins/storage/hplefthand/mode/hardware.pm create mode 100644 centreon/lib/perl/plugins/storage/hplefthand/plugin.pm diff --git a/centreon/lib/perl/plugins/storage/hplefthand/mode/hardware.pm b/centreon/lib/perl/plugins/storage/hplefthand/mode/hardware.pm new file mode 100644 index 00000000000..ac5d3f24332 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/hplefthand/mode/hardware.pm @@ -0,0 +1,522 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::hplefthand::mode::hardware; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::misc; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "exclude" => { name => 'exclude' }, + }); + + $self->{product_name} = undef; + $self->{serial} = undef; + $self->{romversion} = undef; + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->{components_fan} = 0; + $self->{components_rcc} = 0; + $self->{components_temperature} = 0; + $self->{components_psu} = 0; + $self->{components_voltage} = 0; + $self->{components_device} = 0; + $self->{components_rc} = 0; + $self->{components_ro} = 0; + + $self->get_global_information(); + $self->check_fan(); + $self->check_rcc(); + $self->check_temperature(); + $self->check_psu(); + $self->check_voltage(); + $self->check_device(); + $self->check_rc(); + $self->check_ro(); + + $self->{output}->output_add(severity => 'OK', + short_msg => sprintf("All %d components [%d fans, %d power supplies, %d temperatures, %d voltages, %d raid controller caches, %d devices, %d raid controllers, %d raid os] are ok.", + ($self->{components_fan} + $self->{components_rcc} + $self->{components_temperature} + $self->{components_psu} + $self->{components_voltage} + $self->{components_device} + $self->{components_rc} + $self->{components_ro}), + $self->{components_fan}, $self->{components_psu}, $self->{components_temperature}, $self->{components_voltage}, $self->{components_rcc}, $self->{components_device}, $self->{components_rc}, $self->{components_ro})); + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub get_global_information { + my ($self) = @_; + + $self->{global_information} = $self->{snmp}->get_leef(oids => [ + '.1.3.6.1.4.1.9804.3.1.1.2.1.110.0', # fancount + '.1.3.6.1.4.1.9804.3.1.1.2.1.90.0', # raid controlle cache count + '.1.3.6.1.4.1.9804.3.1.1.2.1.120.0', # temperature sensor + '.1.3.6.1.4.1.9804.3.1.1.2.1.130.0', # powersupply + '.1.3.6.1.4.1.9804.3.1.1.2.1.140.0', # voltage sensor + '.1.3.6.1.4.1.9804.3.1.1.2.4.1.0', # storage device + '.1.3.6.1.4.1.9804.3.1.1.2.4.3.0', # raid controller + '.1.3.6.1.4.1.9804.3.1.1.2.4.50.0' # raid internal + ], nothing_quit => 1); +} + +sub check_fan { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking fan"); + return if ($self->check_exclude('fan')); + + my $fan_count_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.110.0"; # 0 means 'none' + my $fan_name_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.111.1.2"; # begin .1 + my $fan_speed_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.111.1.3"; # dont have + my $fan_min_speed_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.111.1.4"; # dont have + my $fan_state_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.111.1.90"; # string explained + my $fan_status_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.111.1.91"; + return if ($self->{global_information}->{$fan_count_oid} == 0); + + $self->{snmp}->load(oids => [$fan_name_oid, $fan_name_oid, + $fan_min_speed_oid, $fan_state_oid, $fan_status_oid], + begin => 1, end => $self->{global_information}->{$fan_count_oid}); + my $result = $self->{snmp}->get_leef(); + return if (scalar(keys %$result) <= 0); + + my $number_fans = $self->{global_information}->{$fan_count_oid}; + for (my $i = 1; $i <= $number_fans; $i++) { + my $fan_name = $result->{$fan_name_oid . "." . $i}; + my $fan_speed = $result->{$fan_speed_oid . "." . $i}; + my $fan_min_speed = $result->{$fan_min_speed_oid . "." . $i}; + my $fan_status = $result->{$fan_status_oid . "." . $i}; + my $fan_state = $result->{$fan_state_oid . "." . $i}; + + $self->{components_fan}++; + + # Check Fan Speed + if (defined($fan_speed)) { + my $low_limit = ''; + if (defined($fan_min_speed)) { + $low_limit = '@:' . $fan_min_speed; + if ($fan_speed <= $fan_min_speed) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Fan '" . $fan_name . "' speed too low"); + } + } + $self->{output}->output_add(long_msg => "Fan '" . $fan_name . "' speed = '" . $fan_speed . "' (<= $fan_min_speed)"); + $self->{output}->perfdata_add(label => $fan_name, unit => 'rpm', + value => $fan_speed, + critical => $low_limit); + } + + if ($fan_status != 1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Fan '" . $fan_name . "' problem '" . $fan_state . "'"); + } + $self->{output}->output_add(long_msg => "Fan '" . $fan_name . "' status = '" . $fan_status . "', state = '" . $fan_state . "'"); + } +} + +sub check_rcc { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking raid controller cache"); + return if ($self->check_exclude('rcc')); + + my $rcc_count_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.90.0"; + my $rcc_name_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.91.1.2"; # begin .1 + my $rcc_state_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.91.1.90"; + my $rcc_status_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.91.1.91"; + my $bbu_enabled_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.91.1.50"; # 1 mean 'enabled' + my $bbu_state_oid = '.1.3.6.1.4.1.9804.3.1.1.2.1.91.1.22'; + my $bbu_status_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.91.1.23"; # 1 mean 'ok' + return if ($self->{global_information}->{$rcc_count_oid} == 0); + + $self->{snmp}->load(oids => [$rcc_name_oid, $rcc_state_oid, + $rcc_status_oid, $bbu_enabled_oid, $bbu_state_oid, $bbu_status_oid], + begin => 1, end => $self->{global_information}->{$rcc_count_oid}); + my $result = $self->{snmp}->get_leef(); + return if (scalar(keys %$result) <= 0); + + my $number_raid = $self->{global_information}->{$rcc_count_oid}; + for (my $i = 1; $i <= $number_raid; $i++) { + my $raid_name = $result->{$rcc_name_oid . "." . $i}; + my $raid_state = $result->{$rcc_state_oid . "." . $i}; + my $raid_status = $result->{$rcc_status_oid . "." . $i}; + my $bbu_enabled = $result->{$bbu_enabled_oid . "." . $i}; + my $bbu_state = $result->{$bbu_state_oid . "." . $i}; + my $bbu_status = $result->{$bbu_status_oid . "." . $i}; + + $self->{components_rcc}++; + + if ($raid_status != 1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Raid Controller Caches '" . $raid_name . "' problem '" . $raid_state . "'"); + } + $self->{output}->output_add(long_msg => "Raid Controller Caches '" . $raid_name . "' status = '" . $raid_status . "', state = '" . $raid_state . "'"); + if ($bbu_enabled == 1) { + if ($bbu_status != 1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "BBU '" . $raid_name . "' problem '" . $bbu_state . "'"); + } + $self->{output}->output_add(long_msg => " BBU status = '" . $bbu_status . "', state = '" . $bbu_state . "'"); + } else { + $self->{output}->output_add(long_msg => " BBU disabled"); + } + } +} + +sub check_temperature { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking temperature sensors"); + return if ($self->check_exclude('temperature')); + + my $temperature_sensor_count_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.120.0"; + my $temperature_sensor_name_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.121.1.2"; + my $temperature_sensor_value_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.121.1.3"; + my $temperature_sensor_critical_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.121.1.4"; + my $temperature_sensor_limit_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.121.1.5"; # warning. lower than critical + my $temperature_sensor_state_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.121.1.90"; + my $temperature_sensor_status_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.121.1.91"; + return if ($self->{global_information}->{$temperature_sensor_count_oid} == 0); + + $self->{snmp}->load(oids => [$temperature_sensor_name_oid, $temperature_sensor_value_oid, + $temperature_sensor_critical_oid, $temperature_sensor_limit_oid, $temperature_sensor_state_oid, $temperature_sensor_status_oid], + begin => 1, end => $self->{global_information}->{$temperature_sensor_count_oid}); + my $result = $self->{snmp}->get_leef(); + return if (scalar(keys %$result) <= 0); + + my $number_temperature = $self->{global_information}->{$temperature_sensor_count_oid}; + for (my $i = 1; $i <= $number_temperature; $i++) { + my $ts_name = $result->{$temperature_sensor_name_oid . "." . $i}; + my $ts_value = $result->{$temperature_sensor_value_oid . "." . $i}; + my $ts_critical = $result->{$temperature_sensor_critical_oid . "." . $i}; + my $ts_limit = $result->{$temperature_sensor_limit_oid . "." . $i}; + my $ts_state = $result->{$temperature_sensor_state_oid . "." . $i}; + my $ts_status = $result->{$temperature_sensor_status_oid . "." . $i}; + + $self->{components_temperature}++; + + if ($ts_value >= $ts_critical) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Temperature sensor '" . $ts_name . "' too high"); + } elsif ($ts_value >= $ts_limit) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Temperature sensor '" . $ts_name . "' over the limit"); + } + $self->{output}->output_add(long_msg => "Temperature sensor '" . $ts_name . "' value = '" . $ts_value . "' (limit >= $ts_limit, critical >= $ts_critical)"); + $self->{output}->perfdata_add(label => $ts_name . "_temp", + value => $ts_value, + warning => $ts_limit, critical => $ts_critical); + + if ($ts_status != 1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Temperature sensor '" . $ts_name . "' problem '" . $ts_state . "'"); + } + $self->{output}->output_add(long_msg => "Temperature sensor '" . $ts_name . "' status = '" . $ts_status . "', state = '" . $ts_state . "'"); + } +} + +sub check_psu { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking power supplies"); + return if ($self->check_exclude('psu')); + + my $power_supply_count_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.130.0"; + my $power_supply_name_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.131.1.2"; + my $power_supply_state_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.131.1.90"; + my $power_supply_status_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.131.1.91"; + return if ($self->{global_information}->{$power_supply_count_oid} == 0); + + $self->{snmp}->load(oids => [$power_supply_name_oid, $power_supply_name_oid, + $power_supply_status_oid], + begin => 1, end => $self->{global_information}->{$power_supply_count_oid}); + my $result = $self->{snmp}->get_leef(); + return if (scalar(keys %$result) <= 0); + + my $number_ps = $self->{global_information}->{$power_supply_count_oid}; + for (my $i = 1; $i <= $number_ps; $i++) { + my $ps_name = $result->{$power_supply_name_oid . "." . $i}; + my $ps_state = $result->{$power_supply_state_oid . "." . $i}; + my $ps_status = $result->{$power_supply_status_oid . "." . $i}; + + $self->{components_psu}++; + + if ($ps_status != 1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Power Supply '" . $ps_name . "' problem '" . $ps_state . "'"); + } + $self->{output}->output_add(long_msg => "Power Supply '" . $ps_name . "' status = '" . $ps_status . "', state = '" . $ps_state . "'"); + } +} + +sub check_voltage { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking voltage sensors"); + return if ($self->check_exclude('voltage')); + + my $vs_count_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.140.0"; + my $vs_name_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.141.1.2"; + my $vs_value_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.141.1.3"; + my $vs_low_limit_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.141.1.4"; + my $vs_high_limit_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.141.1.5"; + my $vs_state_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.141.1.90"; + my $vs_status_oid = ".1.3.6.1.4.1.9804.3.1.1.2.1.141.1.91"; + return if ($self->{global_information}->{$vs_count_oid} == 0); + + $self->{snmp}->load(oids => [$vs_name_oid, $vs_value_oid, + $vs_low_limit_oid, $vs_high_limit_oid, + $vs_state_oid, $vs_status_oid], + begin => 1, end => $self->{global_information}->{$vs_count_oid}); + my $result = $self->{snmp}->get_leef(); + return if (scalar(keys %$result) <= 0); + + my $number_vs = $self->{global_information}->{$vs_count_oid}; + for (my $i = 1; $i <= $number_vs; $i++) { + my $vs_name = $result->{$vs_name_oid . "." . $i}; + my $vs_value = $result->{$vs_value_oid . "." . $i}; + my $vs_low_limit = $result->{$vs_low_limit_oid . "." . $i}; + my $vs_high_limit = $result->{$vs_high_limit_oid . "." . $i}; + my $vs_state = $result->{$vs_state_oid . "." . $i}; + my $vs_status = $result->{$vs_status_oid . "." . $i}; + + $self->{components_voltage}++; + + # Check Voltage limit + if (defined($vs_low_limit) && defined($vs_high_limit)) { + if ($vs_value <= $vs_low_limit) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Voltage sensor '" . $vs_name . "' too low"); + } elsif ($vs_value >= $vs_high_limit) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Voltage sensor '" . $vs_name . "' too high"); + } + $self->{output}->output_add(long_msg => "Voltage sensor '" . $vs_name . "' value = '" . $vs_value . "' (<= $vs_low_limit, >= $vs_high_limit)"); + $self->{output}->perfdata_add(label => $vs_name . "_volt", + value => $vs_value, + warning => '@:' . $vs_low_limit, critical => $vs_high_limit); + } + + if ($vs_status != 1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Voltage sensor '" . $vs_name . "' problem '" . $vs_state . "'"); + } + $self->{output}->output_add(long_msg => "Voltage sensor '" . $vs_name . "' status = '" . $vs_status . "', state = '" . $vs_state . "'"); + } +} + +sub check_device { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking devices"); + return if ($self->check_exclude('device')); + + my $device_count_oid = ".1.3.6.1.4.1.9804.3.1.1.2.4.1.0"; + my $device_name_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.14'; + my $device_serie_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.7'; + my $device_present_state_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.90'; + my $device_present_status_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.91'; + my $device_health_state_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.17'; # normal, marginal, faulty + my $device_health_status_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.18'; + my $device_temperature_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.9'; + my $device_temperature_critical_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.10'; + my $device_temperature_limit_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.11'; + my $device_temperature_status_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.2.1.12'; + return if ($self->{global_information}->{$device_count_oid} == 0); + + $self->{snmp}->load(oids => [$device_name_oid, $device_serie_oid, + $device_present_state_oid, $device_present_status_oid, + $device_health_state_oid, $device_health_status_oid, + $device_temperature_oid, $device_temperature_critical_oid, + $device_temperature_limit_oid, $device_temperature_status_oid], + begin => 1, end => $self->{global_information}->{$device_count_oid}); + my $result = $self->{snmp}->get_leef(); + return if (scalar(keys %$result) <= 0); + + my $number_device = $self->{global_information}->{$device_count_oid}; + for (my $i = 1; $i <= $number_device; $i++) { + my $device_name = $result->{$device_name_oid . "." . $i}; + my $device_serie = $result->{$device_serie_oid . "." . $i}; + my $device_present_state = $result->{$device_present_state_oid . "." . $i}; + my $device_present_status = $result->{$device_present_status_oid . "." . $i}; + my $device_health_state = $result->{$device_health_state_oid . "." . $i}; + my $device_health_status = $result->{$device_health_status_oid . "." . $i}; + my $device_temperature = $result->{$device_temperature_oid . "." . $i}; + my $device_temperature_critical = $result->{$device_temperature_critical_oid . "." . $i}; + my $device_temperature_limit = $result->{$device_temperature_limit_oid . "." . $i}; + my $device_temperature_status = $result->{$device_temperature_status_oid . "." . $i}; + + $self->{components_device}++; + + $self->{output}->output_add(long_msg => "Storage Device '$device_name' and Serial Number '$device_serie', state = '$device_present_state'"); + # Check if present + if ($device_present_state =~ /off_and_secured|off_or_removed/i) { + next; + } + + # Check global health + if ($device_health_status != 1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Storage Device '" . $device_name . "' Smart Health problem '" . $device_health_state . "'"); + } + $self->{output}->output_add(long_msg => " Smart Health status = '" . $device_health_status . "', Smart Health state = '" . $device_health_state . "'"); + + # Check temperature + if ($device_temperature >= $device_temperature_critical) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Device Storage '" . $device_name . "' temperature too high"); + } elsif ($device_temperature >= $device_temperature_limit) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Device Storage '" . $device_name . "' over the limit"); + } + $self->{output}->output_add(long_msg => " Temperature value = '" . $device_temperature . "' (limit >= $device_temperature_limit, critical >= $device_temperature_critical)"); + $self->{output}->perfdata_add(label => $device_name . "_temp", + value => $device_temperature, + warning => $device_temperature_limit, critical => $device_temperature_critical); + } +} + +sub check_rc { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking raid controllers"); + return if ($self->check_exclude('rc')); + + my $rc_count_oid = ".1.3.6.1.4.1.9804.3.1.1.2.4.3.0"; + my $rc_name_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.4.1.2'; + my $rc_state_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.4.1.90'; + my $rc_status_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.4.1.91'; + return if ($self->{global_information}->{$rc_count_oid} == 0); + + $self->{snmp}->load(oids => [$rc_name_oid, $rc_state_oid, + $rc_status_oid], + begin => 1, end => $self->{global_information}->{$rc_count_oid}); + my $result = $self->{snmp}->get_leef(); + return if (scalar(keys %$result) <= 0); + + my $number_rc = $self->{global_information}->{$rc_count_oid}; + for (my $i = 1; $i <= $number_rc; $i++) { + my $rc_name = $result->{$rc_name_oid . "." . $i}; + my $rc_state = $result->{$rc_state_oid . "." . $i}; + my $rc_status = $result->{$rc_status_oid . "." . $i}; + + $self->{components_rc}++; + + if ($rc_status != 1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Raid Device (Controller) '" . $rc_name . "' problem '" . $rc_state . "'"); + } + $self->{output}->output_add(long_msg => "Raid Device (Controller) '" . $rc_name . "' status = '" . $rc_status . "', state = '" . $rc_state . "'"); + } +} + +sub check_ro { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking raid os devices"); + return if ($self->check_exclude('ro')); + + my $raid_os_count_oid = ".1.3.6.1.4.1.9804.3.1.1.2.4.50.0"; + my $raid_os_name_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.51.1.2'; + my $raid_os_state_oid = '.1.3.6.1.4.1.9804.3.1.1.2.4.51.1.90'; # != 'normal' + return if ($self->{global_information}->{$raid_os_count_oid} == 0); + + $self->{snmp}->load(oids => [$raid_os_name_oid, $raid_os_state_oid], + begin => 1, end => $self->{global_information}->{$raid_os_count_oid}); + my $result = $self->{snmp}->get_leef(); + return if (scalar(keys %$result) <= 0); + + my $number_ro = $self->{global_information}->{$raid_os_count_oid}; + for (my $i = 1; $i <= $number_ro; $i++) { + my $ro_name = $arg_result->{values}->{$raid_os_name_oid . "." . $i}; + my $ro_state = $arg_result->{values}->{$raid_os_state_oid . "." . $i}; + + $self->{components_ro}++; + + if ($ro_state !~ /normal/i) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Raid OS Device '" . $ro_name . "' problem '" . $ro_state . "'"); + } + $self->{output}->output_add(long_msg => "Raid OS Device '" . $ro_name . "' state = '" . $ro_state . "'"); + } +} + +sub check_exclude { + my ($self, $section) = @_; + + if (defined($self->{option_results}->{exclude}) && $self->{option_results}->{exclude} =~ /(^|\s|,)$section(\s|,|$)/) { + $self->{output}->output_add(long_msg => sprintf("Skipping $section section.")); + return 1; + } + return 0; +} + +1; + +__END__ + +=head1 MODE + +Check Hardware (fans, power supplies, temperatures, voltages, raid controller caches, devices, raid controllers, raid os). + +=over 8 + +=item B<--exclude> + +Exclude some parts (comma seperated list) (Example: --exclude=psu,rcc). + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/hplefthand/plugin.pm b/centreon/lib/perl/plugins/storage/hplefthand/plugin.pm new file mode 100644 index 00000000000..7435a7fca52 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/hplefthand/plugin.pm @@ -0,0 +1,64 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::hplefthand::plugin; + +use strict; +use warnings; +use base qw(centreon::plugins::script_snmp); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '1.0'; + %{$self->{modes}} = ( + 'hardware' => 'storage::hplefthand::mode::hardware', + ); + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check HP LeftHand storage in SNMP. + +=cut From 0231275945b96ddf1ea7bd7f1b08fdd4b4bac9ab Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sat, 16 Nov 2013 18:12:38 +0100 Subject: [PATCH 138/458] + Fix SNMP issue (split request) --- centreon/lib/perl/centreon/plugins/snmp.pm | 81 ++++++++++++++-------- 1 file changed, 54 insertions(+), 27 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/snmp.pm b/centreon/lib/perl/centreon/plugins/snmp.pm index 5d8c3e46830..6a4f1a3986b 100644 --- a/centreon/lib/perl/centreon/plugins/snmp.pm +++ b/centreon/lib/perl/centreon/plugins/snmp.pm @@ -65,6 +65,7 @@ sub new { "snmp-timeout:s" => { name => 'snmp_timeout', default => 1 }, "snmp-retries:s" => { name => 'snmp_retries', default => 5 }, "maxrepetitions:s" => { name => 'maxrepetitions', default => 50 }, + "subsetleef:s" => { name => 'subsetleef', default => 50 }, "u|username:s" => { name => 'snmp_security_name' }, "authpassphrase:s" => { name => 'snmp_auth_passphrase' }, "authprotocol:s" => { name => 'snmp_auth_protocol' }, @@ -174,13 +175,24 @@ sub get_leef { my $results = {}; my @array_ref_ar = (); + my $subset_current = 0; + my $subset_construct = []; foreach my $oid (@{$options{oids}}) { # Get last value next if ($oid !~ /(.*)\.(\d+)([\.\s]*)$/); my ($oid, $instance) = ($1, $2); $results->{$oid . "." . $instance} = undef; - push @array_ref_ar, [$oid, $instance]; + push @$subset_construct, [$oid, $instance]; + $subset_current++; + if ($subset_current == $self->{subsetleef}) { + push @array_ref_ar, \@$subset_construct; + $subset_construct = []; + $subset_current = 0; + } + } + if ($subset_current) { + push @array_ref_ar, \@$subset_construct; } ############################ @@ -228,33 +240,43 @@ sub get_leef { # ], 'SNMP::Varbind' ) ############################ - my $vb = new SNMP::VarList(@array_ref_ar); - $self->{session}->get($vb); - if ($self->{session}->{ErrorNum}) { - my $msg = 'SNMP GET Request : ' . $self->{session}->{ErrorStr}; - - if ($dont_quit == 0) { - $self->{output}->add_option_msg(short_msg => $msg); - $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); - } - - $self->set_error(error_status => -1, error_msg => $msg); - return undef; - } - my $total = 0; - foreach my $entry (@$vb) { - if ($#$entry < 3) { - # Can be snmpv1 not find - next; + foreach (@array_ref_ar) { + my $vb = new SNMP::VarList(@{$_}); + $self->{session}->get($vb); + if ($self->{session}->{ErrorNum}) { + # 0 noError Pas d'erreurs. + # 1 tooBig Reponse de taille trop grande. + # 2 noSuchName Variable inexistante. + if ($self->{session}->{ErrorNum} == 2) { + # We are at the end with snmpv1. We next. + next; + } + + my $msg = 'SNMP GET Request : ' . $self->{session}->{ErrorStr}; + + if ($dont_quit == 0) { + $self->{output}->add_option_msg(short_msg => $msg); + $self->{output}->option_exit(exit_litteral => $self->{option_results}->{snmp_errors_exit}); + } + + $self->set_error(error_status => -1, error_msg => $msg); + return undef; } - if (${$entry}[2] eq 'NOSUCHOBJECT' || ${$entry}[2] eq 'NOSUCHINSTANCE') { - # Error in snmp > 1 - next; + + foreach my $entry (@$vb) { + if ($#$entry < 3) { + # Can be snmpv1 not find + next; + } + if (${$entry}[2] eq 'NOSUCHOBJECT' || ${$entry}[2] eq 'NOSUCHINSTANCE') { + # Error in snmp > 1 + next; + } + + $total++; + $results->{${$entry}[0] . "." . ${$entry}[1]} = ${$entry}[2]; } - - $total++; - $results->{${$entry}[0] . "." . ${$entry}[1]} = ${$entry}[2]; } if ($nothing_quit == 1 && $total == 0) { @@ -327,8 +349,8 @@ sub get_table { # Error if ($self->{session}->{ErrorNum}) { - # 0 noError Pas d'erreurs. - # 1 tooBig Rénse de taille trop grande. + # 0 noError Pas d'erreurs. + # 1 tooBig Reponse de taille trop grande. # 2 noSuchName Variable inexistante. if ($self->{session}->{ErrorNum} == 2) { # We are at the end with snmpv1. We quit. @@ -423,6 +445,7 @@ sub check_options { } $self->{maxrepetitions} = $options{option_results}->{maxrepetitions}; + $self->{subsetleef} = (defined($options{option_results}->{subsetleef}) && $options{option_results}->{subsetleef} =~ /^[0-9]+$/) ? $options{option_results}->{subsetleef} : 50; $self->{snmp_errors_exit} = $options{option_results}->{snmp_errors_exit}; %{$self->{snmp_params}} = (DestHost => $options{option_results}->{host}, @@ -590,6 +613,10 @@ Set the number of retries (default: 5) before failure. Max repititions value (default: 50) (only for SNMP v2 and v3). +=item B<--subsetleef> + +How many oid values per SNMP request (default: 50) (for get_leef method. Be cautious whe you set it. Prefer to let the default value). + =item B<--username> Security name (only for SNMP v3). From 41c0e8bd5e5f80a88396f9b764d1e4e4a74d1878 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sat, 16 Nov 2013 19:17:35 +0100 Subject: [PATCH 139/458] + function: utf-8 yes, other \x{xxx} --- centreon/lib/perl/centreon/plugins/output.pm | 8 ++++++++ centreon/lib/perl/plugins/snmp_standard/mode/storage.pm | 4 ++-- centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm | 4 ++-- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/output.pm b/centreon/lib/perl/centreon/plugins/output.pm index 7771a5fee10..b557a736d47 100644 --- a/centreon/lib/perl/centreon/plugins/output.pm +++ b/centreon/lib/perl/centreon/plugins/output.pm @@ -34,6 +34,8 @@ #################################################################################### package centreon::plugins::output; +use Encode; +use centreon::plugins::misc; sub new { my ($class, %options) = @_; @@ -531,6 +533,12 @@ sub display_disco_show { } } +sub to_utf8 { + my ($self, $value) = @_; + + return centreon::plugins::misc::trim(Encode::decode('UTF-8', $value, Encode::PERLQQ)); +} + sub add_disco_entry { my ($self, %options) = @_; diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm index b1d0a92ba2b..ba1230e7396 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm @@ -206,7 +206,7 @@ sub reload_cache { my $last_num = 0; foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($key !~ /\.([0-9]+)$/); - $datas->{$self->{option_results}->{oid_filter} . "_" . $1} = $result->{$key}; + $datas->{$self->{option_results}->{oid_filter} . "_" . $1} = $self->{output}->to_utf8($result->{$key}); $last_num = $1; } @@ -219,7 +219,7 @@ sub reload_cache { $result = $self->{snmp}->get_table(oid => $oids_hrStorageTable{$self->{option_results}->{oid_display}}); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($key !~ /\.([0-9]+)$/); - $datas->{$self->{option_results}->{oid_display} . "_" . $1} = $result->{$key}; + $datas->{$self->{option_results}->{oid_display} . "_" . $1} = $self->{output}->to_utf8($result->{$key}); } } diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index 3fde38fdd7c..8078c9316c9 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -292,7 +292,7 @@ sub reload_cache { my $last_num = 0; foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($key !~ /\.([0-9]+)$/); - $datas->{$self->{option_results}->{oid_filter} . "_" . $1} = $result->{$key}; + $datas->{$self->{option_results}->{oid_filter} . "_" . $1} = $self->{output}->to_utf8($result->{$key}); $last_num = $1; } @@ -305,7 +305,7 @@ sub reload_cache { $result = $self->{snmp}->get_table(oid => $oids_iftable{$self->{option_results}->{oid_display}}); foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($key !~ /\.([0-9]+)$/); - $datas->{$self->{option_results}->{oid_display} . "_" . $1} = $result->{$key}; + $datas->{$self->{option_results}->{oid_display} . "_" . $1} = $self->{output}->to_utf8($result->{$key}); } } From 0607159749591e47e8be5fe16007d3bf90d82f38 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sat, 16 Nov 2013 22:37:59 +0100 Subject: [PATCH 140/458] + Use long name --- centreon/lib/perl/centreon/plugins/snmp.pm | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/snmp.pm b/centreon/lib/perl/centreon/plugins/snmp.pm index 6a4f1a3986b..a32358dca01 100644 --- a/centreon/lib/perl/centreon/plugins/snmp.pm +++ b/centreon/lib/perl/centreon/plugins/snmp.pm @@ -58,15 +58,15 @@ sub new { } $options{options}->add_options(arguments => - { "H|hostname|host:s" => { name => 'host' }, - "C|community:s" => { name => 'snmp_community', default => 'public' }, - "v|snmp|snmp-version:s" => { name => 'snmp_version', default => 1 }, - "P|snmpport|snmp-port:i" => { name => 'snmp_port', default => 161 }, + { "hostname|host:s" => { name => 'host' }, + "snmp-community:s" => { name => 'snmp_community', default => 'public' }, + "snmp-version:s" => { name => 'snmp_version', default => 1 }, + "snmp-port:s" => { name => 'snmp_port', default => 161 }, "snmp-timeout:s" => { name => 'snmp_timeout', default => 1 }, "snmp-retries:s" => { name => 'snmp_retries', default => 5 }, "maxrepetitions:s" => { name => 'maxrepetitions', default => 50 }, "subsetleef:s" => { name => 'subsetleef', default => 50 }, - "u|username:s" => { name => 'snmp_security_name' }, + "snmp-username:s" => { name => 'snmp_security_name' }, "authpassphrase:s" => { name => 'snmp_auth_passphrase' }, "authprotocol:s" => { name => 'snmp_auth_protocol' }, "privpassphrase:s" => { name => 'snmp_priv_passphrase' }, @@ -434,7 +434,7 @@ sub check_options { # $options{option_results} = ref to options result if (!defined($options{option_results}->{host})) { - $self->{output}->add_option_msg(short_msg => "Missing parameter -H (--host)."); + $self->{output}->add_option_msg(short_msg => "Missing parameter --hostname."); $self->{output}->option_exit(); } @@ -589,7 +589,7 @@ snmp class Hostname to query (required). -=item B<--community> +=item B<--snmp-community> Read community (defaults to public). @@ -617,7 +617,7 @@ Max repititions value (default: 50) (only for SNMP v2 and v3). How many oid values per SNMP request (default: 50) (for get_leef method. Be cautious whe you set it. Prefer to let the default value). -=item B<--username> +=item B<--snmp-username> Security name (only for SNMP v3). From 24e43c7ab35d2700b5b9f0f1c310263d915073e9 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sun, 17 Nov 2013 21:20:38 +0100 Subject: [PATCH 141/458] + Working on Cisco: mode environment for c3750 --- centreon/lib/perl/plugins/centreon_plugins.pl | 2 + .../perl/plugins/network/cisco/3750/plugin.pm | 65 ++++ .../network/cisco/common/mode/environment.pm | 299 ++++++++++++++++++ 3 files changed, 366 insertions(+) create mode 100644 centreon/lib/perl/plugins/network/cisco/3750/plugin.pm create mode 100644 centreon/lib/perl/plugins/network/cisco/common/mode/environment.pm diff --git a/centreon/lib/perl/plugins/centreon_plugins.pl b/centreon/lib/perl/plugins/centreon_plugins.pl index d420d23b2f2..e638ddf7e65 100644 --- a/centreon/lib/perl/plugins/centreon_plugins.pl +++ b/centreon/lib/perl/plugins/centreon_plugins.pl @@ -37,6 +37,8 @@ use strict; use warnings; use centreon::plugins::script; +use FindBin; +use lib "$FindBin::Bin"; centreon::plugins::script->new()->run(); diff --git a/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm b/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm new file mode 100644 index 00000000000..27162868589 --- /dev/null +++ b/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm @@ -0,0 +1,65 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::cisco::3750::plugin; + +use strict; +use warnings; +use base qw(centreon::plugins::script_snmp); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '1.0'; + %{$self->{modes}} = ( + 'environment' => 'network::cisco::common::mode::environment', + 'traffic' => 'snmp_standard::mode::traffic', + ); + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check Cisco 3750 in SNMP. + +=cut diff --git a/centreon/lib/perl/plugins/network/cisco/common/mode/environment.pm b/centreon/lib/perl/plugins/network/cisco/common/mode/environment.pm new file mode 100644 index 00000000000..0fb57d76081 --- /dev/null +++ b/centreon/lib/perl/plugins/network/cisco/common/mode/environment.pm @@ -0,0 +1,299 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::cisco::common::mode::environment; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %map_type_mon = ( + 1 => 'oldAgs', + 2 => 'ags', + 3 => 'c7000', + 4 => 'ci', + 6 => 'cAccessMon', + 7 => 'cat6000', + 8 => 'ubr7200', + 9 => 'cat4000', + 10 => 'c10000', + 11 => 'osr7600', + 12 => 'c7600', + 13 => 'c37xx', + 14 => 'other' +); +my %states = ( + 1 => ['normal', 'OK'], + 2 => ['warning', 'WARNING'], + 3 => ['critical', 'CRITICAL'], + 4 => ['shutdown', 'OK'], + 5 => ['not present', 'OK'], + 6 => ['not functioning', 'WARNING'], +); +my %map_psu_source = ( + 1 => 'unknown', + 2 => 'ac', + 3 => 'dc', + 4 => 'externalPowerSupply', + 5 => 'internalRedundant' +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "exclude" => { name => 'exclude' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->{components_fans} = 0; + $self->{components_psus} = 0; + $self->{components_temperatures} = 0; + $self->{components_voltages} = 0; + + $self->get_type(); + $self->check_fans(); + $self->check_psus(); + $self->check_temperatures(); + $self->check_voltages(); + + $self->{output}->output_add(severity => 'OK', + short_msg => sprintf("All %d components [%d fans, %d power supplies, %d temperatures, %d voltages] are ok, Environment type: %s", + ($self->{components_fans} + $self->{components_psus} + $self->{components_temperatures} + $self->{components_voltages}), + $self->{components_fans}, $self->{components_psus}, $self->{components_temperatures}, $self->{components_voltages}, $self->{env_type})); + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub get_type { + my ($self) = @_; + + my $oid_ciscoEnvMonPresent = ".1.3.6.1.4.1.9.9.13.1.1.0"; + + my $result = $self->{snmp}->get_leef(oids => [$oid_ciscoEnvMonPresent]); + + $self->{env_type} = defined($result->{$oid_ciscoEnvMonPresent}) ? $map_type_mon{$result->{$oid_ciscoEnvMonPresent}} : 'unknown'; +} + +sub check_fans { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking fans"); + return if ($self->check_exclude('fans')); + + my $oid_ciscoEnvMonFanStatusEntry = '.1.3.6.1.4.1.9.9.13.1.4.1'; + my $oid_ciscoEnvMonFanStatusDescr = '.1.3.6.1.4.1.9.9.13.1.4.1.2'; + my $oid_ciscoEnvMonFanState = '.1.3.6.1.4.1.9.9.13.1.4.1.3'; + + my $result = $self->{snmp}->get_table(oid => $oid_ciscoEnvMonFanStatusEntry); + return if (scalar(keys %$result) <= 0); + + foreach my $oid (keys %$result) { + next if ($oid !~ /^$oid_ciscoEnvMonFanStatusDescr/); + $oid =~ /\.([0-9]+)$/; + my $instance = $1; + + my $fan_descr = $result->{$oid}; + my $fan_state = $result->{$oid_ciscoEnvMonFanState . '.' . $instance}; + + $self->{components_fans}++; + $self->{output}->output_add(long_msg => sprintf("Fan '%s' state is %s.", + $fan_descr, ${$states{$fan_state}}[0])); + if (${$states{$fan_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states{$fan_state}}[1], + short_msg => sprintf("Fan '%s' state is %s.", $fan_descr, ${$states{$fan_state}}[0])); + } + } +} + +sub check_psus { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking power supplies"); + return if ($self->check_exclude('psu')); + + my $oid_ciscoEnvMonSupplyStatusEntry = '.1.3.6.1.4.1.9.9.13.1.5.1'; + my $oid_ciscoEnvMonSupplyStatusDescr = '.1.3.6.1.4.1.9.9.13.1.5.1.2'; + my $oid_ciscoEnvMonSupplyState = '.1.3.6.1.4.1.9.9.13.1.5.1.3'; + my $oid_ciscoEnvMonSupplySource = '.1.3.6.1.4.1.9.9.13.1.5.1.4'; + + my $result = $self->{snmp}->get_table(oid => $oid_ciscoEnvMonSupplyStatusEntry); + return if (scalar(keys %$result) <= 0); + + foreach my $oid (keys %$result) { + next if ($oid !~ /^$oid_ciscoEnvMonSupplyStatusDescr/); + $oid =~ /\.([0-9]+)$/; + my $instance = $1; + + my $psu_descr = $result->{$oid}; + my $psu_state = $result->{$oid_ciscoEnvMonSupplyState . '.' . $instance}; + my $psu_source = $result->{$oid_ciscoEnvMonSupplySource . '.' . $instance}; + + $self->{components_psus}++; + $self->{output}->output_add(long_msg => sprintf("Power Supply '%s' [type: %s] state is %s.", + $psu_descr, $map_psu_source{$psu_source}, ${$states{$psu_state}}[0])); + if (${$states{$psu_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states{$psu_state}}[1], + short_msg => sprintf("Power Supply '%s' state is %s.", $psu_descr, ${$states{$psu_state}}[0])); + } + } +} + +sub check_voltages { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking voltages"); + return if ($self->check_exclude('voltages')); + + my $oid_ciscoEnvMonVoltageStatusEntry = '.1.3.6.1.4.1.9.9.13.1.2.1'; + my $oid_ciscoEnvMonVoltageStatusDescr = '.1.3.6.1.4.1.9.9.13.1.2.1.2'; + my $oid_ciscoEnvMonVoltageStatusValue = '.1.3.6.1.4.1.9.9.13.1.2.1.3'; + my $oid_ciscoEnvMonVoltageThresholdLow = '.1.3.6.1.4.1.9.9.13.1.2.1.4'; + my $oid_ciscoEnvMonVoltageThresholdHigh = '.1.3.6.1.4.1.9.9.13.1.2.1.5'; + my $oid_ciscoEnvMonVoltageState = '.1.3.6.1.4.1.9.9.13.1.2.1.7'; + + my $result = $self->{snmp}->get_table(oid => $oid_ciscoEnvMonVoltageStatusEntry); + return if (scalar(keys %$result) <= 0); + + foreach my $oid (keys %$result) { + next if ($oid !~ /^$oid_ciscoEnvMonVoltageStatusDescr/); + $oid =~ /\.([0-9]+)$/; + my $instance = $1; + + my $voltage_descr = $result->{$oid}; + my $voltage_state = $result->{$oid_ciscoEnvMonVoltageState . '.' . $instance}; + my $voltage_value = $result->{$oid_ciscoEnvMonVoltageStatusValue . '.' . $instance}; + my $voltage_low = $result->{$oid_ciscoEnvMonVoltageThresholdLow . '.' . $instance}; + my $voltage_high = $result->{$oid_ciscoEnvMonVoltageThresholdHigh . '.' . $instance}; + + $self->{components_voltages}++; + $self->{output}->output_add(long_msg => sprintf("Voltage '%s' state is %s.", + $voltage_descr, ${$states{$voltage_state}}[0])); + if (${$states{$voltage_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states{$voltage_state}}[1], + short_msg => sprintf("Power Supply '%s' state is %s.", $voltage_descr, ${$states{$voltage_state}}[0])); + } + + $self->{output}->perfdata_add(label => 'voltage_' . $voltage_descr, unit => 'V', + value => $voltage_value, + critical => $voltage_low . ":" . $voltage_high); + } +} + +sub check_temperatures { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking temperatures"); + return if ($self->check_exclude('temperatures')); + + my $oid_ciscoEnvMonTemperatureStatusEntry = '.1.3.6.1.4.1.9.9.13.1.3.1'; + my $oid_ciscoEnvMonTemperatureStatusDescr = '.1.3.6.1.4.1.9.9.13.1.3.1.2'; + my $oid_ciscoEnvMonTemperatureStatusValue = '.1.3.6.1.4.1.9.9.13.1.3.1.3'; + my $oid_ciscoEnvMonTemperatureThreshold = '.1.3.6.1.4.1.9.9.13.1.3.1.4'; + my $oid_ciscoEnvMonTemperatureState = '.1.3.6.1.4.1.9.9.13.1.3.1.6'; + + my $result = $self->{snmp}->get_table(oid => $oid_ciscoEnvMonTemperatureStatusEntry); + return if (scalar(keys %$result) <= 0); + + foreach my $oid (keys %$result) { + next if ($oid !~ /^$oid_ciscoEnvMonTemperatureStatusDescr/); + $oid =~ /\.([0-9]+)$/; + my $instance = $1; + + my $temp_descr = $result->{$oid}; + my $temp_state = $result->{$oid_ciscoEnvMonTemperatureState . '.' . $instance}; + my $temp_value = $result->{$oid_ciscoEnvMonTemperatureStatusValue . '.' . $instance}; + my $temp_threshold = $result->{$oid_ciscoEnvMonTemperatureThreshold . '.' . $instance}; + + $self->{components_temperatures}++; + $self->{output}->output_add(long_msg => sprintf("Temperature '%s' state is %s.", + $temp_descr, ${$states{$temp_state}}[0])); + if (${$states{$temp_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states{$temp_state}}[1], + short_msg => sprintf("Temperature '%s' state is %s.", $temp_descr, ${$states{$temp_state}}[0])); + } + + $self->{output}->perfdata_add(label => 'temp_' . $temp_descr, unit => 'C', + value => $temp_value, + critical => "~:" . $temp_threshold); + } +} + +sub check_exclude { + my ($self, $section) = @_; + + if (defined($self->{option_results}->{exclude}) && $self->{option_results}->{exclude} =~ /(^|\s|,)$section(\s|,|$)/) { + $self->{output}->output_add(long_msg => sprintf("Skipping $section section.")); + return 1; + } + return 0; +} + +1; + +__END__ + +=head1 MODE + +Check Environment monitor (CISCO-ENVMON-MIB) (Fans, Power Supplies, Temperatures, Voltages). + +=over 8 + +=item B<--exclude> + +Exclude some parts (comma seperated list) (Example: --exclude=temperatures,psu). + +=back + +=cut + \ No newline at end of file From df1226992d69639f1664965e4fe39cd2ec0ddcb1 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 20 Nov 2013 10:57:58 +0100 Subject: [PATCH 142/458] + Fix poller mode submit result --- .../lib/perl/centreon/script/centreontrapd.pm | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 36cecc342c8..523a3bc308b 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -571,14 +571,18 @@ sub forceCheck { my $submit; my $str = "SCHEDULE_FORCED_SVC_CHECK;$self->{current_hostname};$self->{current_service_desc};$datetime"; + my $prefix = ""; + if ($self->{centreontrapd_config}->{mode} == 0) { + $prefix = "EXTERNALCMD:$self->{current_server_id}:"; + } if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { $str =~ s/"/\\"/g; - $submit = "/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{cmdFile}; + $submit = "/bin/echo \"$prefix[$datetime] $str\" >> " . $self->{cmdFile}; } else { $str =~ s/'/'\\''/g; $str =~ s/"/\\"/g; - $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; + $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"$prefix[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; } my ($lerror, $stdout) = centreon::common::misc::backtick(command => $submit, @@ -602,13 +606,18 @@ sub submitResult_do { my $datetime = time(); my $submit; + my $prefix = ""; + if ($self->{centreontrapd_config}->{mode} == 0) { + $prefix = "EXTERNALCMD:$self->{current_server_id}:"; + } + if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { $str =~ s/"/\\"/g; - $submit = "/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{cmdFile}; + $submit = "/bin/echo \"$prefix[$datetime] $str\" >> " . $self->{cmdFile}; } else { $str =~ s/'/'\\''/g; $str =~ s/"/\\"/g; - $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"EXTERNALCMD:$self->{current_server_id}:[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; + $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"$prefix[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; } my ($lerror, $stdout) = centreon::common::misc::backtick(command => $submit, logger => $self->{logger}, From 70bd866d765723e2fc9d619a3418db7e596f024a Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Wed, 20 Nov 2013 14:29:30 +0100 Subject: [PATCH 143/458] + Fix error --- centreon/lib/perl/centreon/script/centreontrapd.pm | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index 523a3bc308b..a9c3e3c353d 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -578,11 +578,11 @@ sub forceCheck { if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { $str =~ s/"/\\"/g; - $submit = "/bin/echo \"$prefix[$datetime] $str\" >> " . $self->{cmdFile}; + $submit = '/bin/echo "' . $prefix . "[$datetime] $str\" >> " . $self->{cmdFile}; } else { $str =~ s/'/'\\''/g; $str =~ s/"/\\"/g; - $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"$prefix[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; + $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"" . $prefix . "[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; } my ($lerror, $stdout) = centreon::common::misc::backtick(command => $submit, @@ -613,11 +613,11 @@ sub submitResult_do { if ($self->{whoami} eq $self->{centreontrapd_config}->{centreon_user}) { $str =~ s/"/\\"/g; - $submit = "/bin/echo \"$prefix[$datetime] $str\" >> " . $self->{cmdFile}; + $submit = '/bin/echo "' . $prefix . "[$datetime] $str\" >> " . $self->{cmdFile}; } else { $str =~ s/'/'\\''/g; $str =~ s/"/\\"/g; - $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"$prefix[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; + $submit = "su -l " . $self->{centreontrapd_config}->{centreon_user} . " -c '/bin/echo \"" . $prefix . "[$datetime] $str\" >> " . $self->{cmdFile} . "' 2>&1"; } my ($lerror, $stdout) = centreon::common::misc::backtick(command => $submit, logger => $self->{logger}, From 58abeaa3a421cd8d9f10eb154962787c308eb829 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 21 Nov 2013 15:09:37 +0100 Subject: [PATCH 144/458] + Fix traffic unit --- centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index 8078c9316c9..731b59a2bae 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -130,7 +130,7 @@ sub run { my $oid_speed32 = '.1.3.6.1.2.1.2.2.1.5'; # in b/s my $oid_in32 = '.1.3.6.1.2.1.2.2.1.10'; # in B my $oid_out32 = '.1.3.6.1.2.1.2.2.1.16'; # in B - my $oid_speed64 = '.1.3.6.1.2.1.31.1.1.1.15'; # in b/s + my $oid_speed64 = '.1.3.6.1.2.1.31.1.1.1.15'; # need multiple by '1000000' my $oid_in64 = '.1.3.6.1.2.1.31.1.1.1.6'; # in B my $oid_out64 = '.1.3.6.1.2.1.31.1.1.1.10'; # in B @@ -163,7 +163,7 @@ sub run { my $interface_speed; if (defined($self->{option_results}->{speed}) && $self->{option_results}->{speed} ne '') { - $interface_speed = $self->{option_results}->{speed} * 1024 * 1024; + $interface_speed = $self->{option_results}->{speed} * 1000000; } else { if ((!defined($result->{$oid_speed32 . "." . $_}) || $result->{$oid_speed32 . "." . $_} !~ /^[0-9]+$/) && (!defined($result->{$oid_speed64 . "." . $_}) || $result->{$oid_speed64 . "." . $_} !~ /^[0-9]+$/)) { @@ -171,7 +171,7 @@ sub run { short_msg => "Interface '" . $display_value . "' Speed is null or incorrect. You should force the value with --speed option"); next; } - $interface_speed = (defined($result->{$oid_speed64 . "." . $_}) && $result->{$oid_speed64 . "." . $_} ne '' ? ($result->{$oid_speed64 . "." . $_}) : ($result->{$oid_speed32 . "." . $_})); + $interface_speed = (defined($result->{$oid_speed64 . "." . $_}) && $result->{$oid_speed64 . "." . $_} ne '' ? ($result->{$oid_speed64 . "." . $_} * 1000000) : ($result->{$oid_speed32 . "." . $_})); if ($interface_speed == 0) { next; } From b65250508e7d482eeed6e33b64b933012a08c0ae Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 21 Nov 2013 15:58:42 +0100 Subject: [PATCH 145/458] + Add mode Cisco cpu and memory --- .../perl/plugins/network/cisco/3750/plugin.pm | 2 + .../plugins/network/cisco/common/mode/cpu.pm | 171 ++++++++++++++++++ .../network/cisco/common/mode/memory.pm | 147 +++++++++++++++ 3 files changed, 320 insertions(+) create mode 100644 centreon/lib/perl/plugins/network/cisco/common/mode/cpu.pm create mode 100644 centreon/lib/perl/plugins/network/cisco/common/mode/memory.pm diff --git a/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm b/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm index 27162868589..9be1d18f63c 100644 --- a/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm +++ b/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm @@ -47,7 +47,9 @@ sub new { $self->{version} = '1.0'; %{$self->{modes}} = ( + 'cpu' => 'network::cisco::common::mode::cpu', 'environment' => 'network::cisco::common::mode::environment', + 'memory' => 'network::cisco::common::mode::memory', 'traffic' => 'snmp_standard::mode::traffic', ); diff --git a/centreon/lib/perl/plugins/network/cisco/common/mode/cpu.pm b/centreon/lib/perl/plugins/network/cisco/common/mode/cpu.pm new file mode 100644 index 00000000000..e527d2a651a --- /dev/null +++ b/centreon/lib/perl/plugins/network/cisco/common/mode/cpu.pm @@ -0,0 +1,171 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::cisco::common::mode::cpu; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', default => '' }, + "critical:s" => { name => 'critical', default => '' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + ($self->{warn5s}, $self->{warn1m}, $self->{warn5m}) = split /,/, $self->{option_results}->{warning}; + ($self->{crit5s}, $self->{crit1m}, $self->{crit5m}) = split /,/, $self->{option_results}->{critical}; + + if (($self->{perfdata}->threshold_validate(label => 'warn5s', value => $self->{warn5s})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning (5sec) threshold '" . $self->{warn5s} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warn1m', value => $self->{warn1m})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning (1min) threshold '" . $self->{warn1m} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warn5m', value => $self->{warn5m})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning (5min) threshold '" . $self->{warn5m} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'crit5s', value => $self->{crit5s})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical (5sec) threshold '" . $self->{crit5s} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'crit1m', value => $self->{crit1m})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical (1min) threshold '" . $self->{crit1m} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'crit5m', value => $self->{crit5})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical (5min) threshold '" . $self->{crit5m} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_cpmCPUTotalEntry = '.1.3.6.1.4.1.9.9.109.1.1.1.1'; + my $oid_cpmCPUTotal5sec = '.1.3.6.1.4.1.9.9.109.1.1.1.1.3'; + my $oid_cpmCPUTotal1min = '.1.3.6.1.4.1.9.9.109.1.1.1.1.4'; + my $oid_cpmCPUTotal5min = '.1.3.6.1.4.1.9.9.109.1.1.1.1.5'; + my $result = $self->{snmp}->get_table(oid => $oid_cpmCPUTotalEntry, nothing_quit => 1); + + $self->{output}->output_add(severity => 'OK', + short_msg => 'All CPUs are ok.'); + + foreach my $oid (keys %$result) { + next if ($oid !~ /^$oid_cpmCPUTotal5sec/); + $oid =~ /\.([0-9]+)$/; + my $instance = $1; + my $cpu5sec = $result->{$oid}; + my $cpu1min = $result->{$oid_cpmCPUTotal1min . '.' . $instance}; + my $cpu5min =$result->{$oid_cpmCPUTotal5min . '.' . $instance}; + + my $exit1 = $self->{perfdata}->threshold_check(value => $cpu5sec, + threshold => [ { label => 'crit5s', 'exit_litteral' => 'critical' }, { label => 'warn5s', exit_litteral => 'warning' } ]); + my $exit2 = $self->{perfdata}->threshold_check(value => $cpu1min, + threshold => [ { label => 'crit1m', 'exit_litteral' => 'critical' }, { label => 'warn1m', exit_litteral => 'warning' } ]); + my $exit3 = $self->{perfdata}->threshold_check(value => $cpu5min, + threshold => [ { label => 'crit5m', 'exit_litteral' => 'critical' }, { label => 'warn5m', exit_litteral => 'warning' } ]); + my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2, $exit3 ]); + + $self->{output}->output_add(long_msg => sprintf("CPU '%s': %.2f%% (5sec), %.2f%% (1min), %.2f%% (5min)", $instance, + $cpu5sec, $cpu1min, $cpu5min)); + if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("CPU '%s': %.2f%% (5sec), %.2f%% (1min), %.2f%% (5min)", $instance, + $cpu5sec, $cpu1min, $cpu5min)); + } + + $self->{output}->perfdata_add(label => "cpu_" . $instance . "_5s", + value => $cpu5sec, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warn5s'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'crit5s'), + min => 0, max => 100); + $self->{output}->perfdata_add(label => "cpu_" . $instance . "_1m", + value => $cpu1min, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warn1m'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'crit1m'), + min => 0, max => 100); + $self->{output}->perfdata_add(label => "cpu_" . $instance . "_5m", + value => $cpu5min, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warn5m'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'crit5m'), + min => 0, max => 100); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check cpu usage (CISCO-PROCESS-MIB). + +=over 8 + +=item B<--warning> + +Threshold warning in percent (5s,1min,5min). + +=item B<--critical> + +Threshold critical in percent (5s,1min,5min). + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/network/cisco/common/mode/memory.pm b/centreon/lib/perl/plugins/network/cisco/common/mode/memory.pm new file mode 100644 index 00000000000..ed344f9eede --- /dev/null +++ b/centreon/lib/perl/plugins/network/cisco/common/mode/memory.pm @@ -0,0 +1,147 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::cisco::common::mode::memory; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_ciscoMemoryPoolEntry = '.1.3.6.1.4.1.9.9.48.1.1.1'; + my $oid_ciscoMemoryPoolName = '.1.3.6.1.4.1.9.9.48.1.1.1.2'; + my $oid_ciscoMemoryPoolUsed = '.1.3.6.1.4.1.9.9.48.1.1.1.5'; # in B + my $oid_ciscoMemoryPoolFree = '.1.3.6.1.4.1.9.9.48.1.1.1.6'; # in B + my $result = $self->{snmp}->get_table(oid => $oid_ciscoMemoryPoolEntry, nothing_quit => 1); + + $self->{output}->output_add(severity => 'OK', + short_msg => 'All pool memories are ok.'); + + foreach my $oid (keys %$result) { + next if ($oid !~ /^$oid_ciscoMemoryPoolName/); + $oid =~ /\.([0-9]+)$/; + my $instance = $1; + my $memory_name = $result->{$oid}; + my $memory_used = $result->{$oid_ciscoMemoryPoolUsed . '.' . $instance}; + my $memory_free =$result->{$oid_ciscoMemoryPoolFree . '.' . $instance}; + + my $total_size = $memory_used + $memory_free; + my $prct_used = $memory_used * 100 / $total_size; + my $prct_free = 100 - $prct_used; + + my $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $total_size); + my ($used_value, $used_unit) = $self->{perfdata}->change_bytes(value => $memory_used); + my ($free_value, $free_unit) = $self->{perfdata}->change_bytes(value => $memory_free); + + $self->{output}->output_add(long_msg => sprintf("Memory '%s' Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", $memory_name, + $total_value . " " . $total_unit, + $used_value . " " . $used_unit, $prct_used, + $free_value . " " . $free_unit, $prct_free)); + if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Memory '%s' Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", $memory_name, + $total_value . " " . $total_unit, + $used_value . " " . $used_unit, $prct_used, + $free_value . " " . $free_unit, $prct_free)); + } + + $self->{output}->perfdata_add(label => "used_" . $memory_name, + value => $memory_used, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $total_size), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $total_size), + min => 0, max => $total_size); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check memory usage (CISCO-MEMORY-POOL-MIB). + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut + \ No newline at end of file From 6ac7e7d3d6875f800a7f9a411cb219a6df5945ce Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 21 Nov 2013 18:27:05 +0100 Subject: [PATCH 146/458] + Add alteon 5224 check --- .../plugins/network/alteon/5224/plugin.pm | 64 ++++++ .../network/alteon/common/mode/hardware.pm | 195 ++++++++++++++++++ 2 files changed, 259 insertions(+) create mode 100644 centreon/lib/perl/plugins/network/alteon/5224/plugin.pm create mode 100644 centreon/lib/perl/plugins/network/alteon/common/mode/hardware.pm diff --git a/centreon/lib/perl/plugins/network/alteon/5224/plugin.pm b/centreon/lib/perl/plugins/network/alteon/5224/plugin.pm new file mode 100644 index 00000000000..65673d22329 --- /dev/null +++ b/centreon/lib/perl/plugins/network/alteon/5224/plugin.pm @@ -0,0 +1,64 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::alteon::5224::plugin; + +use strict; +use warnings; +use base qw(centreon::plugins::script_snmp); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '1.0'; + %{$self->{modes}} = ( + 'hardware' => 'network::alteon::common::mode::hardware', + ); + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check Alteon 5224 in SNMP. + +=cut diff --git a/centreon/lib/perl/plugins/network/alteon/common/mode/hardware.pm b/centreon/lib/perl/plugins/network/alteon/common/mode/hardware.pm new file mode 100644 index 00000000000..0908ca5cf01 --- /dev/null +++ b/centreon/lib/perl/plugins/network/alteon/common/mode/hardware.pm @@ -0,0 +1,195 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::alteon::common::mode::hardware; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %states_temp_cpu = ( + 1 => ['normal', 'OK'], + 2 => ['warning', 'WARNING'], + 3 => ['critical', 'CRITICAL'], +); +my %states_temp = ( + 1 => ['ok', 'OK'], + 2 => ['exceed', 'WARNING'], +); +my %states_psu = ( + 1 => ['single power supply ok', 'WARNING'], + 2 => ['first powerSupply failed', 'CRITICAL'], + 3 => ['second power supply failed', 'CRITICAL'], + 4 => ['double power supply ok', 'OK'], + 5 => ['unknown power supply failed', 'UNKNOWN'], +); +my %states_fan = ( + 1 => ['ok', 'OK'], + 2 => ['fail', 'CRITICAL'], +); +my $oid_hwTemperatureStatus = '.1.3.6.1.4.1.1872.2.5.1.3.1.3.0'; +my $oid_hwFanStatus = '.1.3.6.1.4.1.1872.2.5.1.3.1.4.0'; +my $oid_hwTemperatureThresholdStatusCPU1Get = '.1.3.6.1.4.1.1872.2.5.1.3.1.28.3.0'; +my $oid_hwTemperatureThresholdStatusCPU2Get = '.1.3.6.1.4.1.1872.2.5.1.3.1.28.4.0'; +my $oid_hwPowerSupplyStatus = '.1.3.6.1.4.1.1872.2.5.1.3.1.29.2.0'; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->{components_fans} = 0; + $self->{components_psus} = 0; + $self->{components_temperatures} = 0; + + $self->{global_result} = $self->{snmp}->get_leef(oids => [$oid_hwTemperatureStatus, $oid_hwFanStatus, + $oid_hwTemperatureThresholdStatusCPU1Get, $oid_hwTemperatureThresholdStatusCPU2Get, + $oid_hwPowerSupplyStatus], + nothing_quit => 1); + + $self->check_fans(); + $self->check_psus(); + $self->check_temperatures(); + + $self->{output}->output_add(severity => 'OK', + short_msg => sprintf("All %d components [%d fans, %d power supplies, %d temperatures] are ok", + ($self->{components_fans} + $self->{components_psus} + $self->{components_temperatures}), + $self->{components_fans}, $self->{components_psus}, $self->{components_temperatures})); + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub check_fans { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking fans"); + return if (!defined($self->{global_result}->{$oid_hwFanStatus})); + + $self->{components_fans}++; + my $fan_state = $self->{global_result}->{$oid_hwFanStatus}; + + $self->{output}->output_add(long_msg => sprintf("Fan status is %s.", ${$states_fan{$fan_state}}[0])); + if (${$states_fan{$fan_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states_fan{$fan_state}}[1], + short_msg => sprintf("Fan status is %s.", ${$states_fan{$fan_state}}[0])); + } +} + +sub check_psus { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking power supplies"); + return if (!defined($self->{global_result}->{$oid_hwPowerSupplyStatus})); + + $self->{components_psus}++; + my $psu_state = $self->{global_result}->{$oid_hwPowerSupplyStatus}; + + $self->{output}->output_add(long_msg => sprintf("Power supplies status is %s.", ${$states_psu{$psu_state}}[0])); + if (${$states_psu{$psu_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states_psu{$psu_state}}[1], + short_msg => sprintf("Power supplies status is %s.", ${$states_psu{$psu_state}}[0])); + } +} + +sub check_temperatures { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking temperatures global"); + return if (!defined($self->{global_result}->{$oid_hwTemperatureStatus})); + + $self->{components_temperatures}++; + my $temp_state = $self->{global_result}->{$oid_hwTemperatureStatus}; + + $self->{output}->output_add(long_msg => sprintf("Global temperature sensor status is %s.", ${$states_temp{$temp_state}}[0])); + if (${$states_temp{$temp_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states_temp{$temp_state}}[1], + short_msg => sprintf("Global temperature sensor status is %s.", ${$states_temp{$temp_state}}[0])); + } + + $self->{output}->output_add(long_msg => "Checking temperatures cpus"); + return if (!defined($self->{global_result}->{$oid_hwTemperatureThresholdStatusCPU1Get}) && + !defined($self->{global_result}->{$oid_hwTemperatureThresholdStatusCPU2Get})); + + $self->{components_temperatures} += 2; + my $temp_cpu1_state = $self->{global_result}->{$oid_hwTemperatureThresholdStatusCPU1Get}; + my $temp_cpu2_state = $self->{global_result}->{$oid_hwTemperatureThresholdStatusCPU2Get}; + + $self->{output}->output_add(long_msg => sprintf("Temperature cpu 1 status is %s.", ${$states_temp_cpu{$temp_cpu1_state}}[0])); + if (${$states_temp_cpu{$temp_cpu1_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states_temp_cpu{$temp_cpu1_state}}[1], + short_msg => sprintf("Temperature cpu 1 status is %s.", ${$states_temp_cpu{$temp_cpu1_state}}[0])); + } + + $self->{output}->output_add(long_msg => sprintf("Temperature cpu 2 status is %s.", ${$states_temp_cpu{$temp_cpu2_state}}[0])); + if (${$states_temp_cpu{$temp_cpu2_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states_temp_cpu{$temp_cpu2_state}}[1], + short_msg => sprintf("Temperature cpu 2 status is %s.", ${$states_temp_cpu{$temp_cpu2_state}}[0])); + } +} + +1; + +__END__ + +=head1 MODE + +Check Hardware (ALTEON-CHEETAH-SWITCH-MIB) (Fans, Power Supplies, Temperatures). + +=over 8 + +=back + +=cut + \ No newline at end of file From 0ffc32bdefb55ee0cad7a030d6cf07417d12f598 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Thu, 21 Nov 2013 22:37:14 +0100 Subject: [PATCH 147/458] + Work on mod_perl compatibity --- centreon/lib/perl/centreon/plugins/output.pm | 27 ++++++++++++++++++++ centreon/lib/perl/centreon/plugins/script.pm | 4 ++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/plugins/output.pm b/centreon/lib/perl/centreon/plugins/output.pm index b557a736d47..59c3c24a4c4 100644 --- a/centreon/lib/perl/centreon/plugins/output.pm +++ b/centreon/lib/perl/centreon/plugins/output.pm @@ -342,6 +342,33 @@ sub display { $self->output_txt(exit_litteral => $self->get_litteral_status()); } +sub die_exit { + my ($self, %options) = @_; + # $options{exit_litteral} = string litteral exit + # $options{nolabel} = interger label display + my $exit_litteral = defined($options{exit_litteral}) ? $options{exit_litteral} : $self->{option_results}->{opt_exit}; + my $nolabel = defined($options{nolabel}) ? 1 : 0; + # ignore long output in the following case + $self->{option_results}->{verbose} = undef; + + if (defined($self->{option_results}->{output_xml})) { + $self->create_xml_document(); + if ($self->{is_output_xml}) { + $self->output_xml(exit_litteral => $exit_litteral, nolabel => $nolabel, force_ignore_perfdata => 1); + $self->exit(exit_litteral => $exit_litteral); + } + } elsif (defined($self->{option_results}->{output_json})) { + $self->create_json_document(); + if ($self->{is_output_json}) { + $self->output_json(exit_litteral => $exit_litteral, nolabel => $nolabel, force_ignore_perfdata => 1); + $self->exit(exit_litteral => $exit_litteral); + } + } + + $self->output_txt(exit_litteral => $exit_litteral, nolabel => $nolabel, force_ignore_perfdata => 1); + $self->exit(exit_litteral => $exit_litteral); +} + sub option_exit { my ($self, %options) = @_; # $options{exit_litteral} = string litteral exit diff --git a/centreon/lib/perl/centreon/plugins/script.pm b/centreon/lib/perl/centreon/plugins/script.pm index a0a7c109778..184275719da 100644 --- a/centreon/lib/perl/centreon/plugins/script.pm +++ b/centreon/lib/perl/centreon/plugins/script.pm @@ -76,8 +76,10 @@ sub class_handle_DIE { sub handle_DIE { my ($self, $msg) = @_; + # For 'mod_perl' + die $msg if $^S; $self->{output}->add_option_msg(short_msg => $msg); - $self->{output}->option_exit(); + $self->{output}->die_exit(); } sub get_plugin { From db76dfe8f1cac11a895446b7b5d27c9ed2f78c12 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Fri, 22 Nov 2013 00:29:26 +0100 Subject: [PATCH 148/458] + workaround centengine connector perl bug --- centreon/lib/perl/centreon/plugins/script.pm | 39 +++++++++++++++- centreon/lib/perl/plugins/centreon_plugins.pl | 46 +------------------ 2 files changed, 39 insertions(+), 46 deletions(-) diff --git a/centreon/lib/perl/centreon/plugins/script.pm b/centreon/lib/perl/centreon/plugins/script.pm index 184275719da..2b435358d8c 100644 --- a/centreon/lib/perl/centreon/plugins/script.pm +++ b/centreon/lib/perl/centreon/plugins/script.pm @@ -42,6 +42,7 @@ use centreon::plugins::output; use centreon::plugins::misc; use FindBin; use Pod::Usage; +use Pod::Find qw(pod_where); my %handlers = ('DIE' => {}); @@ -122,7 +123,7 @@ sub display_local_help { if ($self->{help}) { local *STDOUT; open STDOUT, '>', \$stdout; - pod2usage(-exitval => "NOEXIT", -input => $FindBin::Bin . "/" . $FindBin::Script); + pod2usage(-exitval => "NOEXIT", -input => pod_where({-inc => 1}, __PACKAGE__)); } $self->{output}->add_option_msg(long_msg => $stdout) if (defined($stdout)); @@ -220,6 +221,40 @@ __END__ =head1 NAME -Class global script. +centreon_plugins.pl - main program to call Merethis plugins. + +=head1 SYNOPSIS + +centreon_plugins.pl [options] + +=head1 OPTIONS + +=over 8 + +=item B<--plugin> + +Specify the path to the plugin. + +=item B<--version> + +Print plugin version. + +=item B<--help> + +Print a brief help message and exits. + +=item B<--runas> + +Run the script as a different user (prefer to use directly the good user). + +=item B<--environment> + +Set environment variables for the script (prefer to set it before running it for better performance). + +=back + +=head1 DESCRIPTION + +B . =cut diff --git a/centreon/lib/perl/plugins/centreon_plugins.pl b/centreon/lib/perl/plugins/centreon_plugins.pl index e638ddf7e65..9b6fb19d12c 100644 --- a/centreon/lib/perl/plugins/centreon_plugins.pl +++ b/centreon/lib/perl/plugins/centreon_plugins.pl @@ -37,51 +37,9 @@ use strict; use warnings; use centreon::plugins::script; +# Not perl embedded compliant at all use FindBin; use lib "$FindBin::Bin"; +# use lib '/usr/lib/nagios/plugins/'; centreon::plugins::script->new()->run(); - -__END__ - -=head1 NAME - -centreon_plugins.pl - main program to call Merethis plugins. - -=head1 SYNOPSIS - -centreon_plugins.pl [options] - -=head1 OPTIONS - -=over 8 - -=item B<--plugin> - -Specify the path to the plugin. - -=item B<--version> - -Print plugin version. - -=item B<--help> - -Print a brief help message and exits. - -=item B<--runas> - -Run the script as a different user (prefer to use directly the good user). - -=item B<--environment> - -Set environment variables for the script (prefer to set it before running it for better performance). - -=back - -=head1 DESCRIPTION - -B . - -=cut - - From 57b1c67e2699e5b01fec7c5734c00ddb818f94a3 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 22 Nov 2013 10:24:06 +0100 Subject: [PATCH 149/458] + Add mode for alteon chassis --- .../plugins/network/alteon/5224/plugin.pm | 2 + .../plugins/network/alteon/common/mode/cpu.pm | 159 ++++++++++++++++++ .../network/alteon/common/mode/memory.pm | 130 ++++++++++++++ 3 files changed, 291 insertions(+) create mode 100644 centreon/lib/perl/plugins/network/alteon/common/mode/cpu.pm create mode 100644 centreon/lib/perl/plugins/network/alteon/common/mode/memory.pm diff --git a/centreon/lib/perl/plugins/network/alteon/5224/plugin.pm b/centreon/lib/perl/plugins/network/alteon/5224/plugin.pm index 65673d22329..ce44064d418 100644 --- a/centreon/lib/perl/plugins/network/alteon/5224/plugin.pm +++ b/centreon/lib/perl/plugins/network/alteon/5224/plugin.pm @@ -47,7 +47,9 @@ sub new { $self->{version} = '1.0'; %{$self->{modes}} = ( + 'cpu' => 'network::alteon::common::mode::cpu', 'hardware' => 'network::alteon::common::mode::hardware', + 'memory' => 'network::alteon::common::mode::memory', ); return $self; diff --git a/centreon/lib/perl/plugins/network/alteon/common/mode/cpu.pm b/centreon/lib/perl/plugins/network/alteon/common/mode/cpu.pm new file mode 100644 index 00000000000..3e87f66c6c4 --- /dev/null +++ b/centreon/lib/perl/plugins/network/alteon/common/mode/cpu.pm @@ -0,0 +1,159 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::alteon::common::mode::cpu; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', default => '' }, + "critical:s" => { name => 'critical', default => '' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + ($self->{warn1s}, $self->{warn4s}, $self->{warn64s}) = split /,/, $self->{option_results}->{warning}; + ($self->{crit1s}, $self->{crit4s}, $self->{crit64s}) = split /,/, $self->{option_results}->{critical}; + + if (($self->{perfdata}->threshold_validate(label => 'warn1s', value => $self->{warn1s})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning (1sec) threshold '" . $self->{warn1s} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warn4s', value => $self->{warn4s})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning (4sec) threshold '" . $self->{warn4s} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warn64s', value => $self->{warn64s})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning (64sec) threshold '" . $self->{warn64s} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'crit1s', value => $self->{crit1s})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical (1sec) threshold '" . $self->{crit1s} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'crit4s', value => $self->{crit4s})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical (4sec) threshold '" . $self->{crit4s} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'crit64s', value => $self->{crit64s})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical (64sec) threshold '" . $self->{crit64s} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_mpCpuStatsUtil1Second = '.1.3.6.1.4.1.1872.2.5.1.2.2.1.0'; + my $oid_mpCpuStatsUtil4Seconds = '.1.3.6.1.4.1.1872.2.5.1.2.2.2.0'; + my $oid_mpCpuStatsUtil64Seconds = '.1.3.6.1.4.1.1872.2.5.1.2.2.3.0'; + my $result = $self->{snmp}->get_leef(oids => [$oid_mpCpuStatsUtil1Second, $oid_mpCpuStatsUtil4Seconds, + $oid_mpCpuStatsUtil64Seconds], nothing_quit => 1); + + my $cpu1sec = $result->{$oid_mpCpuStatsUtil1Second}; + my $cpu4sec = $result->{$oid_mpCpuStatsUtil4Seconds}; + my $cpu64sec = $result->{$oid_mpCpuStatsUtil64Seconds}; + + my $exit1 = $self->{perfdata}->threshold_check(value => $cpu1sec, + threshold => [ { label => 'crit1s', 'exit_litteral' => 'critical' }, { label => 'warn1s', exit_litteral => 'warning' } ]); + my $exit2 = $self->{perfdata}->threshold_check(value => $cpu4sec, + threshold => [ { label => 'crit4s', 'exit_litteral' => 'critical' }, { label => 'warn4s', exit_litteral => 'warning' } ]); + my $exit3 = $self->{perfdata}->threshold_check(value => $cpu64sec, + threshold => [ { label => 'crit64s', 'exit_litteral' => 'critical' }, { label => 'warn64s', exit_litteral => 'warning' } ]); + my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2, $exit3 ]); + + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("MP CPU Usage: %.2f%% (1sec), %.2f%% (4sec), %.2f%% (64sec)", + $cpu1sec, $cpu4sec, $cpu64sec)); + + $self->{output}->perfdata_add(label => "cpu_1s", + value => $cpu1sec, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warn1s'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'crit1s'), + min => 0, max => 100); + $self->{output}->perfdata_add(label => "cpu_4s", + value => $cpu4sec, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warn4s'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'crit4s'), + min => 0, max => 100); + $self->{output}->perfdata_add(label => "cpu_64s", + value => $cpu64sec, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warn64s'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'crit64s'), + min => 0, max => 100); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check MP cpu usage (ALTEON-CHEETAH-SWITCH-MIB). + +=over 8 + +=item B<--warning> + +Threshold warning in percent (1s,4s,64s). + +=item B<--critical> + +Threshold critical in percent (1s,4s,64s). + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/network/alteon/common/mode/memory.pm b/centreon/lib/perl/plugins/network/alteon/common/mode/memory.pm new file mode 100644 index 00000000000..9452a05d54d --- /dev/null +++ b/centreon/lib/perl/plugins/network/alteon/common/mode/memory.pm @@ -0,0 +1,130 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::alteon::common::mode::memory; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_mpMemStatsTotal = '.1.3.6.1.4.1.1872.2.5.1.2.8.1.0'; + my $oid_mpMemStatsFree = '.1.3.6.1.4.1.1872.2.5.1.2.8.3.0'; + my $result = $self->{snmp}->get_leef(oids => [$oid_mpMemStatsTotal, $oid_mpMemStatsFree], nothing_quit => 1); + + my $total_size = $result->{$oid_mpMemStatsTotal}; + my $memory_free = $result->{$oid_mpMemStatsFree}; + my $memory_used = $total_size - $memory_free; + + my $prct_used = $memory_used * 100 / $total_size; + my $prct_free = 100 - $prct_used; + + my $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $total_size); + my ($used_value, $used_unit) = $self->{perfdata}->change_bytes(value => $memory_used); + my ($free_value, $free_unit) = $self->{perfdata}->change_bytes(value => $memory_free); + + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("MP Memory Usage Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", + $total_value . " " . $total_unit, + $used_value . " " . $used_unit, $prct_used, + $free_value . " " . $free_unit, $prct_free)); + + $self->{output}->perfdata_add(label => "used", + value => $memory_used, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $total_size), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $total_size), + min => 0, max => $total_size); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check MP memory usage (ALTEON-CHEETAH-SWITCH-MIB). + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut + \ No newline at end of file From 17be81a27e5151cef1e12f942bede57b2f6ca85d Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Fri, 22 Nov 2013 16:15:38 +0100 Subject: [PATCH 150/458] refs #4661; centfilltrapdb will now output the number of inserted/updated entries --- centreon/lib/perl/centreon/script/centFillTrapDB.pm | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script/centFillTrapDB.pm b/centreon/lib/perl/centreon/script/centFillTrapDB.pm index 0ec2baf076f..c84b72bbc56 100644 --- a/centreon/lib/perl/centreon/script/centFillTrapDB.pm +++ b/centreon/lib/perl/centreon/script/centFillTrapDB.pm @@ -73,6 +73,9 @@ sub main { exit(1); } my $last_oid = ""; + my $nb_inserted = 0; + my $nb_updated = 0; + while () { if ($_ =~ /^EVENT\ ([a-zA-Z0-9\_\-]+)\ ([0-9\.]+)\ (\"[A-Za-z\ \_\-]+\")\ ([a-zA-Z]+)/) { my ($name,$oid,$type,$val) = ($1, $2, $3, $4); @@ -83,9 +86,11 @@ sub main { $val = getStatus($val,$name); my ($status, $sth) = $self->{centreon_dbc}->query("INSERT INTO `traps` (`traps_name`, `traps_oid`, `traps_status`, `manufacturer_id`, `traps_submit_result_enable`) VALUES (" . $self->{centreon_dbc}->quote($name) . ", " . $self->{centreon_dbc}->quote($oid) . ", " . $self->{centreon_dbc}->quote($val) . ", " . $self->{centreon_dbc}->quote($manuf) . ", '1')"); $last_oid = $oid; + $nb_inserted++; } } elsif ($_ =~/^FORMAT\ (.*)/ && $last_oid ne "") { my ($status, $sth) = $self->{centreon_dbc}->query("UPDATE `traps` set `traps_args` = '$1' WHERE `traps_oid` = " . $self->{centreon_dbc}->quote($last_oid)); + $nb_updated++; } elsif ($_ =~ /^SDESC(.*)/ && $last_oid ne "") { my $temp_val = $1; my $desc = ""; @@ -107,9 +112,11 @@ sub main { } if ($desc ne "") { my ($status, $sth) = $self->{centreon_dbc}->query("UPDATE `traps` SET `traps_comments` = '$desc' WHERE `traps_oid` = " . $self->{centreon_dbc}->quote($last_oid)); + $nb_updated++; } } } + $self->{logger}->writeLogInfo("$nb_inserted entries inserted, $nb_updated entries updated"); } sub run { @@ -132,4 +139,4 @@ sub run { exit(0); } -1; \ No newline at end of file +1; From 11262a1c1bc7c55f5f3416992162c7478e489a5f Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 22 Nov 2013 17:48:45 +0100 Subject: [PATCH 151/458] + Add postgres plugin with some modes --- .../plugins/database/mysql/mode/queries.pm | 4 +- .../database/postgres/mode/backends.pm | 170 ++++++++++++++++ .../database/postgres/mode/connectiontime.pm | 123 ++++++++++++ .../database/postgres/mode/hitratio.pm | 189 ++++++++++++++++++ .../plugins/database/postgres/mode/locks.pm | 172 ++++++++++++++++ .../database/postgres/mode/querytime.pm | 162 +++++++++++++++ .../database/postgres/mode/timesync.pm | 127 ++++++++++++ .../perl/plugins/database/postgres/plugin.pm | 120 +++++++++++ .../snmp_standard/mode/processcount.pm | 4 +- 9 files changed, 1067 insertions(+), 4 deletions(-) create mode 100644 centreon/lib/perl/plugins/database/postgres/mode/backends.pm create mode 100644 centreon/lib/perl/plugins/database/postgres/mode/connectiontime.pm create mode 100644 centreon/lib/perl/plugins/database/postgres/mode/hitratio.pm create mode 100644 centreon/lib/perl/plugins/database/postgres/mode/locks.pm create mode 100644 centreon/lib/perl/plugins/database/postgres/mode/querytime.pm create mode 100644 centreon/lib/perl/plugins/database/postgres/mode/timesync.pm create mode 100644 centreon/lib/perl/plugins/database/postgres/plugin.pm diff --git a/centreon/lib/perl/plugins/database/mysql/mode/queries.pm b/centreon/lib/perl/plugins/database/mysql/mode/queries.pm index 8c141761d5a..15f3dccef70 100644 --- a/centreon/lib/perl/plugins/database/mysql/mode/queries.pm +++ b/centreon/lib/perl/plugins/database/mysql/mode/queries.pm @@ -146,11 +146,11 @@ Check average number of queries executed. =item B<--warning> -Threshold warning in bytes. +Threshold warning. =item B<--critical> -Threshold critical in bytes. +Threshold critical. =back diff --git a/centreon/lib/perl/plugins/database/postgres/mode/backends.pm b/centreon/lib/perl/plugins/database/postgres/mode/backends.pm new file mode 100644 index 00000000000..edfe644cbe8 --- /dev/null +++ b/centreon/lib/perl/plugins/database/postgres/mode/backends.pm @@ -0,0 +1,170 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package database::postgres::mode::backends; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + "exclude:s" => { name => 'exclude', }, + "noidle" => { name => 'noidle', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } + +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + my $noidle = ''; + if (defined($self->{option_results}->{noidle})) { + if ($self->{sql}->is_version_minimum(version => '9.2')) { + $noidle = " AND state <> 'idle'"; + } else { + $noidle = " AND current_query <> ''"; + } + } + + my $query = "SELECT COUNT(datid) AS current, + (SELECT setting AS mc FROM pg_settings WHERE name = 'max_connections') AS mc, + d.datname +FROM pg_database d +LEFT JOIN pg_stat_activity s ON (s.datid = d.oid $noidle) +GROUP BY d.datname +ORDER BY d.datname"; + $self->{sql}->query(query => $query); + + $self->{output}->output_add(severity => 'OK', + short_msg => "All client database connections are ok."); + + my $database_check = 0; + my $result = $self->{sql}->fetchall_arrayref(); + + foreach my $row (@{$result}) { + if (defined($self->{option_results}->{exclude}) && $$row[2] !~ /$self->{option_results}->{exclude}/) { + $self->{output}->output_add(long_msg => "Skipping database '" . $$row[2] . '"'); + next; + } + + $database_check++; + my $used = $$row[0]; + my $max_connections = $$row[1]; + my $database_name = $$row[2]; + + my $prct_used = ($used * 100) / $max_connections; + my $exit_code = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(long_msg => sprintf("Database '%s': %.2f%% client connections limit reached (%d of max. %d)", + $database_name, $prct_used, $used, $max_connections)); + if (!$self->{output}->is_status(value => $exit_code, compare => 'ok', litteral => 1)) { + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("Database '%s': %.2f%% client connections limit reached (%d of max. %d)", + $database_name, $prct_used, $used, $max_connections)); + } + + $self->{output}->perfdata_add(label => 'connections_' . $database_name, + value => $used, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0, max => $max_connections); + } + if ($database_check == 0) { + $self->{output}->output_add(severity => 'UNKNOWN', + short_msg => 'No database checked. (permission or a wrong exclude filter)'); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check the current number of connections for one or more databases + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=item B<--exclude> + +Filter databases. + +=item B<--noidle> + +Idle connections are not counted. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/postgres/mode/connectiontime.pm b/centreon/lib/perl/plugins/database/postgres/mode/connectiontime.pm new file mode 100644 index 00000000000..9ea4d56df43 --- /dev/null +++ b/centreon/lib/perl/plugins/database/postgres/mode/connectiontime.pm @@ -0,0 +1,123 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package database::postgres::mode::connectiontime; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use Time::HiRes; +use POSIX; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + my $now = Time::HiRes::time(); + my ($exit, $msg_error) = $self->{sql}->connect(dontquit => 1); + my $now2 = Time::HiRes::time(); + + if ($exit == -1) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => $msg_error); + } else { + my $milliseconds = $now2 - $now; + $milliseconds = floor($milliseconds * 1000); + my $exit_code = $self->{perfdata}->threshold_check(value => $milliseconds, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("Connection established in %.3fs.", $milliseconds / 1000)); + $self->{output}->perfdata_add(label => 'connection_time', unit => 'ms', + value => $milliseconds, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check Postgres connection time. + +=over 8 + +=item B<--warning> + +Threshold warning in milliseconds. + +=item B<--critical> + +Threshold critical in milliseconds. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/postgres/mode/hitratio.pm b/centreon/lib/perl/plugins/database/postgres/mode/hitratio.pm new file mode 100644 index 00000000000..1846ab40995 --- /dev/null +++ b/centreon/lib/perl/plugins/database/postgres/mode/hitratio.pm @@ -0,0 +1,189 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package database::postgres::mode::hitratio; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + "lookback" => { name => 'lookback', }, + "exclude:s" => { name => 'exclude', }, + }); + $self->{statefile_cache} = centreon::plugins::statefile->new(%options); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } + + $self->{statefile_cache}->check_options(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + $self->{sql}->query(query => q{ +SELECT sd.blks_hit, sd.blks_read, d.datname +FROM pg_stat_database sd, pg_database d +WHERE d.oid=sd.datid + }); + + $self->{statefile_cache}->read(statefile => 'postgres_' . $self->{mode} . '_' . $self->{sql}->get_unique_id4save()); + my $old_timestamp = $self->{statefile_cache}->get(name => 'last_timestamp'); + + my $database_check = 0; + my $new_datas = {}; + $new_datas->{last_timestamp} = time(); + my $result = $self->{sql}->fetchall_arrayref(); + + $self->{output}->output_add(severity => 'OK', + short_msg => "All databases hitratio are ok."); + + + foreach my $row (@{$result}) { + $new_datas->{$$row[2] . '_blks_hit'} = $$row[0]; + $new_datas->{$$row[2] . '_blks_read'} = $$row[1]; + + if (defined($self->{option_results}->{exclude}) && $$row[2] !~ /$self->{option_results}->{exclude}/) { + $self->{output}->output_add(long_msg => "Skipping database '" . $$row[2] . '"'); + next; + } + + my $old_blks_hit = $self->{statefile_cache}->get(name => $$row[2] . '_blks_hit'); + my $old_blks_read = $self->{statefile_cache}->get(name => $$row[2] . '_blks_read'); + + next if (!defined($old_blks_hit) || !defined($old_blks_read)); + $old_blks_hit = 0 if ($$row[0] <= $old_blks_hit); + $old_blks_read = 0 if ($$row[1] <= $old_blks_read); + + $database_check++; + my %prcts = (); + my $total_read_requests = $new_datas->{$$row[2] . '_blks_hit'} - $old_blks_hit; + my $total_read_disk = $new_datas->{$$row[2] . '_blks_read'} - $old_blks_read; + $prcts{hitratio_now} = ($total_read_requests == 0) ? 100 : ($total_read_requests - $total_read_disk) * 100 / $total_read_requests; + $prcts{hitratio} = ($new_datas->{$$row[2] . '_blks_hit'} == 0) ? 100 : ($new_datas->{$$row[2] . '_blks_hit'} - $new_datas->{$$row[2] . '_blks_read'}) * 100 / $new_datas->{$$row[2] . '_blks_hit'}; + + my $exit_code = $self->{perfdata}->threshold_check(value => $prcts{'hitratio' . ((defined($self->{option_results}->{lookback})) ? '_now' : '' )}, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(long_msg => sprintf("Database '%s' hitratio at %.2f%%", + $$row[2], $prcts{'hitratio' . ((defined($self->{option_results}->{lookback})) ? '' : '_now')}) + ); + + if (!$self->{output}->is_status(value => $exit_code, compare => 'ok', litteral => 1)) { + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("Database '%s' hitratio at %.2f%%", + $$row[2], $prcts{'hitratio' . ((defined($self->{option_results}->{lookback})) ? '' : '_now')}) + ); + } + $self->{output}->perfdata_add(label => $$row[2] . '_hitratio' . ((defined($self->{option_results}->{lookback})) ? '' : '_now'), unit => '%', + value => sprintf("%.2f", $prcts{'hitratio' . ((defined($self->{option_results}->{lookback})) ? '_now' : '')}), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0, max => 100); + $self->{output}->perfdata_add(label => $$row[2] . '_hitratio' . ((defined($self->{option_results}->{lookback})) ? '_now' : ''), unit => '%', + value => sprintf("%.2f", $prcts{'hitratio' . ((defined($self->{option_results}->{lookback})) ? '_now' : '')}), + min => 0, max => 100); + } + + $self->{statefile_cache}->write(data => $new_datas); + if (!defined($old_timestamp)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + } + if (defined($old_timestamp) && $database_check == 0) { + $self->{output}->output_add(severity => 'UNKNOWN', + short_msg => 'No database checked. (permission or a wrong exclude filter)'); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check hitratio (in buffer cache) for databases. + +=over 8 + +=item B<--warning> + +Threshold warning. + +=item B<--critical> + +Threshold critical. + +=item B<--lookback> + +Threshold isn't on the percent calculated from the difference ('xxx_hitratio_now'). + +=item B<--exclude> + +Filter databases. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/postgres/mode/locks.pm b/centreon/lib/perl/plugins/database/postgres/mode/locks.pm new file mode 100644 index 00000000000..bca88341e0b --- /dev/null +++ b/centreon/lib/perl/plugins/database/postgres/mode/locks.pm @@ -0,0 +1,172 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package database::postgres::mode::locks; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', default => ''}, + "critical:s" => { name => 'critical', default => ''}, + "exclude:s" => { name => 'exclude', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + my @warns = split /,/, $self->{option_results}->{warning}; + my @crits = split /,/, $self->{option_results}->{critical}; + + foreach my $val (@warns) { + next if (!defined($val)); + my ($label, $value) = split /=/, $val; + next if (!defined($label) || !defined($value)); + + if (($self->{perfdata}->threshold_validate(label => 'warn-' . $label, value => $value)) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning ('$label' locks) threshold '" . $value . "'."); + $self->{output}->option_exit(); + } + } + + foreach my $val (@crits) { + next if (!defined($val)); + my ($label, $value) = split /=/, $val; + next if (!defined($label) || !defined($value)); + + if (($self->{perfdata}->threshold_validate(label => 'crit-' . $label, value => $value)) == 0) { + $self->{output}->add_option_msg(short_msg => "Critical warning ('$label' locks) threshold '" . $value . "'."); + $self->{output}->option_exit(); + } + } +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + $self->{sql}->query(query => q{ +SELECT granted, mode, datname FROM pg_database d LEFT JOIN pg_locks l ON (d.oid=l.database) WHERE d.datallowconn +}); + + $self->{output}->output_add(severity => 'OK', + short_msg => "All databases locks are ok."); + + my $result = $self->{sql}->fetchall_arrayref(); + my $dblocks = {}; + foreach my $row (@{$result}) { + my ($granted, $mode, $dbname) = ($$row[0], $$row[1], $$row[2]); + if (defined($self->{option_results}->{exclude}) && $dbname !~ /$self->{option_results}->{exclude}/) { + next; + } + + if (!defined($dblocks->{$dbname})) { + $dblocks->{$dbname} = {total => 0, waiting => 0}; + # Empty. no lock (left join) + next if (!defined($mode) || $mode eq ''); + } + $dblocks->{$dbname}->{total}++; + $mode =~ s{lock$}{}; + $dblocks->{$dbname}->{lc($mode)}++; + $dblocks->{$dbname}->{waiting}++ if (!$granted); + } + + foreach my $dbname (keys %$dblocks) { + foreach my $locktype (keys %{$dblocks->{$dbname}}) { + $self->{output}->output_add(long_msg => sprintf("Database '%s' lock '%s': %d", + $dbname, $locktype, $dblocks->{$dbname}->{$locktype})); + my $exit_code = $self->{perfdata}->threshold_check(value => $dblocks->{$dbname}->{$locktype}, threshold => [ { label => 'crit-' . $locktype, 'exit_litteral' => 'critical' }, { label => 'warn-' . $locktype, exit_litteral => 'warning' } ]); + + if (!$self->{output}->is_status(value => $exit_code, compare => 'ok', litteral => 1)) { + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("Database '%s' lock '%s': %d", + $dbname, $locktype, $dblocks->{$dbname}->{$locktype})); + } + + $self->{output}->perfdata_add(label => $dbname . '_' . $locktype, + value => $dblocks->{$dbname}->{$locktype}, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warn-' . $locktype), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'crit-' . $locktype), + min => 0); + } + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check locks for one or more databases + +=over 8 + +=item B<--warning> + +Threshold warning. (example: "total=250,waiting=5,exclusive=20") +'total', 'waiting', or the name of a lock type used by Postgres. + +=item B<--critical> + +Threshold critical. (example: "total=250,waiting=5,exclusive=20") +'total', 'waiting', or the name of a lock type used by Postgres. + +=item B<--exclude> + +Filter databases. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/postgres/mode/querytime.pm b/centreon/lib/perl/plugins/database/postgres/mode/querytime.pm new file mode 100644 index 00000000000..d2eb2af253c --- /dev/null +++ b/centreon/lib/perl/plugins/database/postgres/mode/querytime.pm @@ -0,0 +1,162 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package database::postgres::mode::querytime; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + "exclude:s" => { name => 'exclude', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + my $query; + if ($self->{sql}->is_version_minimum(version => '9.2')) { + $query = q{ +SELECT datname, datid, pid, usename, client_addr, query AS current_query, state AS state, + CASE WHEN client_port < 0 THEN 0 ELSE client_port END AS client_port, + COALESCE(ROUND(EXTRACT(epoch FROM now()-query_start)),0) AS seconds +FROM pg_stat_activity WHERE (query_start IS NOT NULL AND (state NOT LIKE 'idle%' OR state IS NULL)) +ORDER BY query_start, pid DESC +}; + } else { + $query = q{ +SELECT datname, datid, procpid AS pid, usename, client_addr, current_query AS current_query, '' AS state, + CASE WHEN client_port < 0 THEN 0 ELSE client_port END AS client_port, + COALESCE(ROUND(EXTRACT(epoch FROM now()-query_start)),0) AS seconds +FROM pg_stat_activity WHERE (query_start IS NOT NULL AND current_query NOT LIKE '%') +ORDER BY query_start, procpid DESC +}; + } + + $self->{sql}->query(query => $query); + + $self->{output}->output_add(severity => 'OK', + short_msg => "All databases queries time are ok."); + my $dbquery = {}; + while ((my $row = $self->{sql}->fetchrow_hashref())) { + if (defined($self->{option_results}->{exclude}) && $row->{datname} !~ /$self->{option_results}->{exclude}/) { + next; + } + + use Data::Dumper; + print Data::Dumper::Dumper($row); + + my $exit_code = $self->{perfdata}->threshold_check(value => $row->{seconds}, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + if ($self->{output}->is_status(value => $exit_code, compare => 'ok', litteral => 1)) { + $self->{output}->output_add(long_msg => sprintf("Request from client '%s' too long (%d sec) on database '%s': %s", + $row->{client_addr}, $row->{seconds}, $row->{datname}, $row->{current_query})); + $dbquery->{$row->{datname}}->{total}++; + $dbquery->{$row->{datname}}->{code}->{$exit_code}++; + } + } + + foreach my $dbname (keys %$dbquery) { + $self->{output}->perfdata_add(label => $dbname . '_qtime_num', + value => $dbquery->{$dbname}->{total}, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + foreach my $exit_code (keys %{$dbquery->{$dbname}->{code}}) { + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("%d request exceed " . lc($exit_code) . " threshold on database '%s'", + $dbquery->{$dbname}->{code}->{$exit_code}, $dbname)); + } + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Checks the time of running queries for one or more databases + +=over 8 + +=item B<--warning> + +Threshold warning in seconds. + +=item B<--critical> + +Threshold critical in seconds. + +=item B<--exclude> + +Filter databases. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/postgres/mode/timesync.pm b/centreon/lib/perl/plugins/database/postgres/mode/timesync.pm new file mode 100644 index 00000000000..7df50f48075 --- /dev/null +++ b/centreon/lib/perl/plugins/database/postgres/mode/timesync.pm @@ -0,0 +1,127 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package database::postgres::mode::timesync; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use Time::HiRes; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + "exclude:s" => { name => 'exclude', }, + "noidle" => { name => 'noidle', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{warn1} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->{sql}->connect(); + + $self->{sql}->query(query => q{ +SELECT extract(epoch FROM now()) AS epok +}); + + my ($result) = $self->{sql}->fetchrow_array(); + my $ltime = Time::HiRes::time(); + if (!defined($result)) { + $self->{output}->add_option_msg(short_msg => "Cannot get server time."); + $self->{output}->option_exit(); + } + + my $diff = $result - $ltime; + my $exit_code = $self->{perfdata}->threshold_check(value => $result, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("%.3fs time diff between servers", $diff)); + $self->{output}->perfdata_add(label => 'timediff', unit => 's', + value => sprintf("%.3f", $diff), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical')); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Compares the local system time with the time reported by Postgres + +=over 8 + +=item B<--warning> + +Threshold warning in seconds. (use a range. it can be -0.3s or +0.3s.) + +=item B<--critical> + +Threshold critical in seconds. (use a range. it can be -0.3s or +0.3s.) + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/postgres/plugin.pm b/centreon/lib/perl/plugins/database/postgres/plugin.pm new file mode 100644 index 00000000000..0e1dc1de0bc --- /dev/null +++ b/centreon/lib/perl/plugins/database/postgres/plugin.pm @@ -0,0 +1,120 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package database::postgres::plugin; + +use strict; +use warnings; +use base qw(centreon::plugins::script_sql); + +sub new { + my ($class, %options) = @_; + + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '0.1'; + %{$self->{modes}} = ( + 'backends' => 'database::postgres::mode::backends', + 'connection-time' => 'database::postgres::mode::connectiontime', + 'hitratio' => 'database::postgres::mode::hitratio', + 'locks' => 'database::postgres::mode::locks', + 'query-time' => 'database::postgres::mode::querytime', + 'timesync' => 'database::postgres::mode::timesync', + ); + return $self; +} + +sub init { + my ($self, %options) = @_; + + $self->{options}->add_options( + arguments => { + 'host:s@' => { name => 'db_host' }, + 'port:s@' => { name => 'db_port' }, + 'database:s@' => { name => 'db_name', default => 'postgres' }, + } + ); + $self->{options}->parse_options(); + my $options_result = $self->{options}->get_options(); + $self->{options}->clean(); + + if (defined($options_result->{db_host})) { + @{$self->{sqldefault}->{dbi}} = (); + for (my $i = 0; $i < scalar(@{$options_result->{db_host}}); $i++) { + $self->{sqldefault}->{dbi}[$i] = { data_source => 'Pg:host=' . $options_result->{db_host}[$i] }; + if (defined($options_result->{db_port}[$i])) { + $self->{sqldefault}->{dbi}[$i]->{data_source} .= ';port=' . $options_result->{db_port}[$i]; + } + if (defined($options_result->{db_name}[$i])) { + $self->{sqldefault}->{dbi}[$i]->{data_source} .= ';database=' . $options_result->{db_name}[$i]; + } + } + } + + # If we want a command line: password with variable "PGPASSWORD". + # psql -d template1 -A -R '-====-' -F '#====#' -c "select code from films" + + $self->SUPER::init(%options); +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check Postgres Server. + +=over 8 + +You can use following options or options from 'sqlmode' directly. + +=item B<--host> + +Hostname to query. + +=item B<--port> + +Database Server Port. + +=item B<--database> + +Database Name. (default: postgres) + +=back + +=cut diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm b/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm index cfbe3003c03..07f90e000ca 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/processcount.pm @@ -182,11 +182,11 @@ Check system number of processes. =item B<--warning> -Threshold warning in percent. +Threshold warning. =item B<--critical> -Threshold critical in percent. +Threshold critical. =item B<--process-name> From 517ad9f62a1c4e046d60f8c1986c83b1408a3ca7 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Fri, 22 Nov 2013 21:54:33 +0100 Subject: [PATCH 152/458] + Add 'psqlcmd' sqlmode for postgres --- .../perl/plugins/database/mysql/mysqlcmd.pm | 10 +- .../perl/plugins/database/postgres/plugin.pm | 15 +- .../perl/plugins/database/postgres/psqlcmd.pm | 360 ++++++++++++++++++ 3 files changed, 374 insertions(+), 11 deletions(-) create mode 100644 centreon/lib/perl/plugins/database/postgres/psqlcmd.pm diff --git a/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm index 98734f126b6..6b7c90131c7 100644 --- a/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm +++ b/centreon/lib/perl/plugins/database/mysql/mysqlcmd.pm @@ -73,6 +73,7 @@ sub new { $self->{mode} = $options{mode}; $self->{args} = undef; $self->{stdout} = undef; + $self->{columns} = undef; $self->{version} = undef; $self->{host} = undef; @@ -216,16 +217,17 @@ sub connect { my ($self, %options) = @_; my $dontquit = (defined($options{dontquit}) && $options{dontquit} == 1) ? 1 : 0; - my ($exit_code, $stdout) = $self->command_execution(request => "SHOW VARIABLES LIKE 'version'"); + (my $exit_code, $self->{stdout}) = $self->command_execution(request => "SHOW VARIABLES LIKE 'version'"); if ($exit_code != 0) { if ($dontquit == 0) { - $self->{output}->add_option_msg(short_msg => "Cannot connect: " . $stdout); + $self->{output}->add_option_msg(short_msg => "Cannot connect: " . $self->{stdout}); $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); } - return (-1, "Cannot connect: " . $stdout); + return (-1, "Cannot connect: " . $self->{stdout}); } - (my $name, $self->{version}) = split(/\t/, $stdout); + my $row = $self->fetchrow_hashref(); + $self->{version} = $row->{Value}; return 0; } diff --git a/centreon/lib/perl/plugins/database/postgres/plugin.pm b/centreon/lib/perl/plugins/database/postgres/plugin.pm index 0e1dc1de0bc..e027f905a6b 100644 --- a/centreon/lib/perl/plugins/database/postgres/plugin.pm +++ b/centreon/lib/perl/plugins/database/postgres/plugin.pm @@ -55,6 +55,7 @@ sub new { 'query-time' => 'database::postgres::mode::querytime', 'timesync' => 'database::postgres::mode::timesync', ); + $self->{sql_modes}{psqlcmd} = 'database::postgres::psqlcmd'; return $self; } @@ -65,7 +66,7 @@ sub init { arguments => { 'host:s@' => { name => 'db_host' }, 'port:s@' => { name => 'db_port' }, - 'database:s@' => { name => 'db_name', default => 'postgres' }, + 'database:s@' => { name => 'db_name' }, } ); $self->{options}->parse_options(); @@ -74,19 +75,19 @@ sub init { if (defined($options_result->{db_host})) { @{$self->{sqldefault}->{dbi}} = (); + @{$self->{sqldefault}->{psqlcmd}} = (); for (my $i = 0; $i < scalar(@{$options_result->{db_host}}); $i++) { $self->{sqldefault}->{dbi}[$i] = { data_source => 'Pg:host=' . $options_result->{db_host}[$i] }; + $self->{sqldefault}->{psqlcmd}[$i] = { host => $options_result->{db_host}[$i] }; if (defined($options_result->{db_port}[$i])) { $self->{sqldefault}->{dbi}[$i]->{data_source} .= ';port=' . $options_result->{db_port}[$i]; + $self->{sqldefault}->{psqlcmd}[$i]->{port} = $options_result->{db_port}[$i]; } - if (defined($options_result->{db_name}[$i])) { - $self->{sqldefault}->{dbi}[$i]->{data_source} .= ';database=' . $options_result->{db_name}[$i]; - } + $options_result->{db_name}[$i] = (defined($options_result->{db_name}[$i])) ? $options_result->{db_name}[$i] : 'postgres'; + $self->{sqldefault}->{dbi}[$i]->{data_source} .= ';database=' . $options_result->{db_name}[$i]; + $self->{sqldefault}->{psqlcmd}[$i]->{dbname} = $options_result->{db_name}[$i]; } } - - # If we want a command line: password with variable "PGPASSWORD". - # psql -d template1 -A -R '-====-' -F '#====#' -c "select code from films" $self->SUPER::init(%options); } diff --git a/centreon/lib/perl/plugins/database/postgres/psqlcmd.pm b/centreon/lib/perl/plugins/database/postgres/psqlcmd.pm new file mode 100644 index 00000000000..1783109956c --- /dev/null +++ b/centreon/lib/perl/plugins/database/postgres/psqlcmd.pm @@ -0,0 +1,360 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package database::postgres::psqlcmd; + +use strict; +use warnings; +use centreon::plugins::misc; +use Digest::MD5 qw(md5_hex); + +sub new { + my ($class, %options) = @_; + my $self = {}; + bless $self, $class; + # $options{options} = options object + # $options{output} = output object + # $options{exit_value} = integer + # $options{noptions} = integer + + if (!defined($options{output})) { + print "Class psqlcmd: Need to specify 'output' argument.\n"; + exit 3; + } + if (!defined($options{options})) { + $options{output}->add_option_msg(short_msg => "Class psqlcmd: Need to specify 'options' argument."); + $options{output}->option_exit(); + } + if (!defined($options{noptions})) { + $options{options}->add_options(arguments => + { "psql-cmd:s" => { name => 'psql_cmd', default => '/usr/bin/psql' }, + "host:s@" => { name => 'host' }, + "port:s@" => { name => 'port' }, + "username:s@" => { name => 'username' }, + "password:s@" => { name => 'password' }, + "dbname:s@" => { name => 'dbname' }, + "sql-errors-exit:s" => { name => 'sql_errors_exit', default => 'unknown' }, + }); + } + $options{options}->add_help(package => __PACKAGE__, sections => 'PSQLCMD OPTIONS', once => 1); + + $self->{output} = $options{output}; + $self->{mode} = $options{mode}; + $self->{args} = undef; + $self->{stdout} = undef; + $self->{columns} = undef; + $self->{version} = undef; + + $self->{host} = undef; + $self->{port} = undef; + $self->{username} = undef; + $self->{password} = undef; + $self->{dbname} = undef; + + $self->{record_separator} = '-====-'; + $self->{field_separator} = '#====#'; + + return $self; +} + +# Method to manage multiples +sub set_options { + my ($self, %options) = @_; + # options{options_result} + + $self->{option_results} = $options{option_results}; +} + +# Method to manage multiples +sub set_defaults { + my ($self, %options) = @_; + # options{default} + + # Manage default value + foreach (keys %{$options{default}}) { + if ($_ eq $self->{mode}) { + for (my $i = 0; $i < scalar(@{$options{default}->{$_}}); $i++) { + foreach my $opt (keys %{$options{default}->{$_}[$i]}) { + if (!defined($self->{option_results}->{$opt}[$i])) { + $self->{option_results}->{$opt}[$i] = $options{default}->{$_}[$i]->{$opt}; + } + } + } + } + } +} + +sub check_options { + my ($self, %options) = @_; + # return 1 = ok still data_source + # return 0 = no data_source left + + $self->{host} = (defined($self->{option_results}->{host})) ? shift(@{$self->{option_results}->{host}}) : undef; + $self->{port} = (defined($self->{option_results}->{port})) ? shift(@{$self->{option_results}->{port}}) : undef; + $self->{username} = (defined($self->{option_results}->{username})) ? shift(@{$self->{option_results}->{username}}) : undef; + $self->{password} = (defined($self->{option_results}->{password})) ? shift(@{$self->{option_results}->{password}}) : undef; + $self->{dbname} = (defined($self->{option_results}->{dbname})) ? shift(@{$self->{option_results}->{dbname}}) : undef; + $self->{sql_errors_exit} = $self->{option_results}->{sql_errors_exit}; + $self->{psql_cmd} = $self->{option_results}->{psql_cmd}; + + # If we want a command line: password with variable "PGPASSWORD". + # psql -d template1 -A -R '-====-' -F '#====#' -c "select code from films" + + if (!defined($self->{host}) || $self->{host} eq '') { + $self->{output}->add_option_msg(short_msg => "Need to specify host argument."); + $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); + } + + $self->{args} = ['-A', '-R', $self->{record_separator}, '-F', $self->{field_separator}, '--pset', 'footer=off', '-h', $self->{host}]; + if (defined($self->{port})) { + push @{$self->{args}}, "-p", $self->{port}; + } + if (defined($self->{username})) { + push @{$self->{args}}, "-U", $self->{username}; + } + if (defined($self->{password}) && $self->{password} ne '') { + $ENV{PGPASSWORD} = $self->{password}; + } + if (defined($self->{dbname}) && $self->{dbname} ne '') { + push @{$self->{args}}, "-d", $self->{dbname}; + } + + if (scalar(@{$self->{option_results}->{host}}) == 0) { + return 0; + } + return 1; +} + +sub is_version_minimum { + my ($self, %options) = @_; + # $options{version} = string version to check + + my @version_src = split /\./, $self->{version}; + my @versions = split /\./, $options{version}; + for (my $i = 0; $i < scalar(@versions); $i++) { + return 1 if ($versions[$i] eq 'x'); + return 1 if (!defined($version_src[$i])); + $version_src[$i] =~ /^([0-9]*)/; + next if ($versions[$i] == int($1)); + return 0 if ($versions[$i] > int($1)); + return 1 if ($versions[$i] < int($1)); + } + + return 1; +} + +sub get_id { + my ($self, %options) = @_; + + my $msg = $self->{host}; + if (defined($self->{port})) { + $msg .= ":" . $self->{port}; + } + return $msg; +} + + +sub get_unique_id4save { + my ($self, %options) = @_; + + my $msg = $self->{host}; + if (defined($self->{port})) { + $msg .= ":" . $self->{port}; + } + return md5_hex($msg); +} + +sub quote { + my $self = shift; + + return undef; +} + +sub command_execution { + my ($self, %options) = @_; + + my ($lerror, $stdout, $exit_code) = centreon::plugins::misc::backtick( + command => $self->{psql_cmd}, + arguments => [@{$self->{args}}, '-c', $options{request}], + timeout => 30, + wait_exit => 1, + redirect_stderr => 1 + ); + if ($exit_code <= -1000) { + if ($exit_code == -1000) { + $self->{output}->output_add(severity => 'UNKNOWN', + short_msg => $stdout); + } + $self->{output}->display(); + $self->{output}->exit(); + } + + return ($exit_code, $stdout); +} + +# Connection initializer +sub connect { + my ($self, %options) = @_; + my $dontquit = (defined($options{dontquit}) && $options{dontquit} == 1) ? 1 : 0; + + (my $exit_code, $self->{stdout}) = $self->command_execution(request => "SELECT current_setting('server_version') as version"); + if ($exit_code != 0) { + if ($dontquit == 0) { + $self->{output}->add_option_msg(short_msg => "Cannot connect: " . $self->{stdout}); + $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); + } + return (-1, "Cannot connect: " . $self->{stdout}); + } + + my $row = $self->fetchrow_hashref(); + $self->{version} = $row->{version}; + + return 0; +} + +sub fetchall_arrayref { + my ($self, %options) = @_; + my $array_ref = []; + + if (!defined($self->{columns})) { + $self->{stdout} =~ s/^(.*?)\Q$self->{record_separator}\E//ms; + @{$self->{columns}} = split(/\Q$self->{field_separator}\E/, $1); + } + foreach (split /\Q$self->{record_separator}\E/, $self->{stdout}) { + push @$array_ref, [split(/\Q$self->{field_separator}\E/, $_)]; + } + + return $array_ref; +} + +sub fetchrow_array { + my ($self, %options) = @_; + my @array_result = (); + + if (!defined($self->{columns})) { + $self->{stdout} =~ s/^(.*?)\Q$self->{record_separator}\E//ms; + @{$self->{columns}} = split(/\Q$self->{field_separator}\E/, $1); + } + if (($self->{stdout} =~ s/^(.*?)\Q$self->{record_separator}\E//ms)) { + push @array_result, split(/\Q$self->{field_separator}\E/, $1); + } + + return @array_result; +} + +sub fetchrow_hashref { + my ($self, %options) = @_; + my $array_result = undef; + + if (!defined($self->{columns})) { + $self->{stdout} =~ s/^(.*?)\Q$self->{record_separator}\E//ms; + @{$self->{columns}} = split(/\Q$self->{field_separator}\E/, $1); + } + if ($self->{stdout} ne '' && $self->{stdout} =~ s/^(.*?)\Q$self->{record_separator}\E//ms) { + $array_result = {}; + my @values = split(/\Q$self->{field_separator}\E/, $1); + for (my $i = 0; $i < scalar(@values); $i++) { + my $value = $values[$i]; + $array_result->{$self->{columns}[$i]} = $value; + } + } + + return $array_result; +} + +sub query { + my ($self, %options) = @_; + + $self->{columns} = undef; + (my $exit_code, $self->{stdout}) = $self->command_execution(request => $options{query}); + + if ($exit_code != 0) { + $self->{output}->add_option_msg(short_msg => "Cannot execute query: " . $self->{stdout}); + $self->{output}->option_exit(exit_litteral => $self->{sql_errors_exit}); + } + +} + +1; + +__END__ + +=head1 NAME + +psqlcmd global + +=head1 SYNOPSIS + +psqlcmd class + +=head1 PSQLCMD OPTIONS + +=over 8 + +=item B<--psql-cmd> + +postgres command (Default: '/usr/bin/psql'). + +=item B<--host> + +Database hostname. + +=item B<--port> + +Database port. + +=item B<--dbname> + +Database name to connect (default: postgres). + +=item B<--username> + +Database username. + +=item B<--password> + +Database password. + +=item B<--sql-errors-exit> + +Exit code for DB Errors (default: unknown) + +=back + +=head1 DESCRIPTION + +B<>. + +=cut From 0b27ba3db9f967415e56ab36a23af3f4fbfd7111 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sun, 24 Nov 2013 12:37:56 +0100 Subject: [PATCH 153/458] + Add mode 'list-databases' --- .../database/postgres/mode/listdatabases.pm | 127 ++++++++++++++++++ .../database/postgres/mode/querytime.pm | 3 - .../database/postgres/mode/timesync.pm | 2 - .../perl/plugins/database/postgres/plugin.pm | 1 + .../plugins/snmp_standard/mode/traffic.pm | 23 ++-- 5 files changed, 142 insertions(+), 14 deletions(-) create mode 100644 centreon/lib/perl/plugins/database/postgres/mode/listdatabases.pm diff --git a/centreon/lib/perl/plugins/database/postgres/mode/listdatabases.pm b/centreon/lib/perl/plugins/database/postgres/mode/listdatabases.pm new file mode 100644 index 00000000000..709b8fee5e5 --- /dev/null +++ b/centreon/lib/perl/plugins/database/postgres/mode/listdatabases.pm @@ -0,0 +1,127 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package database::postgres::mode::listdatabases; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use Time::HiRes; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "exclude:s" => { name => 'exclude', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub manage_selection { + my ($self, %options) = @_; + + $self->{sql}->connect(); + + $self->{sql}->query(query => q{ +SELECT datname FROM pg_database +}); + $self->{list_db} = []; + while ((my $row = $self->{sql}->fetchrow_hashref())) { + if (defined($self->{option_results}->{exclude}) && $row->{datname} !~ /$self->{option_results}->{exclude}/) { + next; + } + push @{$self->{list_db}}, $row->{datname}; + } +} + +sub run { + my ($self, %options) = @_; + # $options{sql} = sqlmode object + $self->{sql} = $options{sql}; + + $self->manage_selection(); + + $self->{output}->output_add(severity => 'OK', + short_msg => "List of databases: " . join(', ', @{$self->{list_db}})); + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub disco_format { + my ($self, %options) = @_; + + $self->{output}->add_disco_format(elements => ['name']); +} + +sub disco_show { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{sql} = $options{sql}; + + $self->manage_selection(); + foreach (sort @{$self->{list_db}}) { + $self->{output}->add_disco_entry(name => $_); + } +} + +1; + +__END__ + +=head1 MODE + +Display databases + +=over 8 + +=item B<--exclude> + +Filter databases. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/database/postgres/mode/querytime.pm b/centreon/lib/perl/plugins/database/postgres/mode/querytime.pm index d2eb2af253c..ae91eb5d9c3 100644 --- a/centreon/lib/perl/plugins/database/postgres/mode/querytime.pm +++ b/centreon/lib/perl/plugins/database/postgres/mode/querytime.pm @@ -106,9 +106,6 @@ ORDER BY query_start, procpid DESC next; } - use Data::Dumper; - print Data::Dumper::Dumper($row); - my $exit_code = $self->{perfdata}->threshold_check(value => $row->{seconds}, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); if ($self->{output}->is_status(value => $exit_code, compare => 'ok', litteral => 1)) { $self->{output}->output_add(long_msg => sprintf("Request from client '%s' too long (%d sec) on database '%s': %s", diff --git a/centreon/lib/perl/plugins/database/postgres/mode/timesync.pm b/centreon/lib/perl/plugins/database/postgres/mode/timesync.pm index 7df50f48075..11e77e6242a 100644 --- a/centreon/lib/perl/plugins/database/postgres/mode/timesync.pm +++ b/centreon/lib/perl/plugins/database/postgres/mode/timesync.pm @@ -51,8 +51,6 @@ sub new { { "warning:s" => { name => 'warning', }, "critical:s" => { name => 'critical', }, - "exclude:s" => { name => 'exclude', }, - "noidle" => { name => 'noidle', }, }); return $self; diff --git a/centreon/lib/perl/plugins/database/postgres/plugin.pm b/centreon/lib/perl/plugins/database/postgres/plugin.pm index e027f905a6b..5f51df5a3dd 100644 --- a/centreon/lib/perl/plugins/database/postgres/plugin.pm +++ b/centreon/lib/perl/plugins/database/postgres/plugin.pm @@ -52,6 +52,7 @@ sub new { 'connection-time' => 'database::postgres::mode::connectiontime', 'hitratio' => 'database::postgres::mode::hitratio', 'locks' => 'database::postgres::mode::locks', + 'list-databases' => 'database::postgres::mode::listdatabases', 'query-time' => 'database::postgres::mode::querytime', 'timesync' => 'database::postgres::mode::timesync', ); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index 731b59a2bae..73da4dbc84e 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -161,6 +161,7 @@ sub run { foreach (sort @{$self->{interface_id_selected}}) { my $display_value = $self->get_display_value(id => $_); + # Manage interface speed my $interface_speed; if (defined($self->{option_results}->{speed}) && $self->{option_results}->{speed} ne '') { $interface_speed = $self->{option_results}->{speed} * 1000000; @@ -176,6 +177,8 @@ sub run { next; } } + + if ($operstatus[$result->{$oid_operstatus . "." . $_} - 1] ne "up") { if (!defined($self->{option_results}->{skip}) && (!defined($result->{$oid_adminstatus . "." . $_}) || $operstatus[$result->{$oid_adminstatus . "." . $_} - 1] eq 'up') ) { $self->{output}->output_add(severity => 'CRITICAL', @@ -185,21 +188,23 @@ sub run { } next; } - my $old_mode = $self->{statefile_value}->get(name => 'mode'); - $new_datas->{mode} = '32'; + + my $old_mode = $self->{statefile_value}->get(name => 'mode_' . $_); + $new_datas->{'mode_' . $_} = '32'; $new_datas->{'in_' . $_} = $result->{$oid_in32 . "." . $_} * 8; - if (defined($result->{$oid_in64 . "." . $_}) && $result->{$oid_in64 . "." . $_} ne '') { + if (defined($result->{$oid_in64 . "." . $_}) && $result->{$oid_in64 . "." . $_} ne '' && $result->{$oid_in64 . "." . $_} != 0) { $new_datas->{'in_' . $_} = $result->{$oid_in64 . "." . $_} * 8; - $new_datas->{mode} = '64'; + $new_datas->{'mode_' . $_} = '64'; } $new_datas->{'out_' . $_} = $result->{$oid_out32 . "." . $_} * 8; - if (defined($result->{$oid_out64 . "." . $_}) && $result->{$oid_out64 . "." . $_} ne '') { + if (defined($result->{$oid_out64 . "." . $_}) && $result->{$oid_out64 . "." . $_} ne '' && $result->{$oid_out64 . "." . $_} != 0) { $new_datas->{'out_' . $_} = $result->{$oid_out64 . "." . $_} * 8; - $new_datas->{mode} = '64'; + $new_datas->{'mode_' . $_} = '64'; } + # We change mode. need to recreate a buffer - if (!defined($old_mode) || $new_datas->{mode} ne $old_mode) { + if (!defined($old_mode) || $new_datas->{'mode_' . $_} ne $old_mode) { next; } @@ -220,8 +225,8 @@ sub run { my $time_delta = $new_datas->{last_timestamp} - $old_timestamp; if ($time_delta <= 0) { - # At least one second. two fast calls ;) - $time_delta = 1; + # At least one second. two fast calls ;) + $time_delta = 1; } my $in_absolute_per_sec = ($new_datas->{'in_' . $_} - $old_in) / $time_delta; my $out_absolute_per_sec = ($new_datas->{'out_' . $_} - $old_out) / $time_delta; From e03399d815c335ea25550b9a593774a039b947c4 Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sun, 24 Nov 2013 15:18:42 +0100 Subject: [PATCH 154/458] + Add mode 'packet-errors' snmp_standard --- centreon/lib/perl/centreon/plugins/output.pm | 7 +- .../perl/plugins/network/cisco/3750/plugin.pm | 2 + centreon/lib/perl/plugins/os/linux/plugin.pm | 2 + .../lib/perl/plugins/os/windows/plugin.pm | 2 + .../snmp_standard/mode/listinterfaces.pm | 282 ++++++++++ .../snmp_standard/mode/packeterrors.pm | 528 ++++++++++++++++++ .../plugins/snmp_standard/mode/traffic.pm | 32 -- 7 files changed, 820 insertions(+), 35 deletions(-) create mode 100644 centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm create mode 100644 centreon/lib/perl/plugins/snmp_standard/mode/packeterrors.pm diff --git a/centreon/lib/perl/centreon/plugins/output.pm b/centreon/lib/perl/centreon/plugins/output.pm index 59c3c24a4c4..7efc4011ee3 100644 --- a/centreon/lib/perl/centreon/plugins/output.pm +++ b/centreon/lib/perl/centreon/plugins/output.pm @@ -324,22 +324,23 @@ sub output_txt { sub display { my ($self, %options) = @_; + my $nolabel = defined($options{nolabel}) ? 1 : 0; if (defined($self->{option_results}->{output_xml})) { $self->create_xml_document(); if ($self->{is_output_xml}) { - $self->output_xml(exit_litteral => $self->get_litteral_status()); + $self->output_xml(exit_litteral => $self->get_litteral_status(), nolabel => $nolabel); return ; } } elsif (defined($self->{option_results}->{output_json})) { $self->create_json_document(); if ($self->{is_output_json}) { - $self->output_json(exit_litteral => $self->get_litteral_status()); + $self->output_json(exit_litteral => $self->get_litteral_status(), nolabel => $nolabel); return ; } } - $self->output_txt(exit_litteral => $self->get_litteral_status()); + $self->output_txt(exit_litteral => $self->get_litteral_status(), nolabel => $nolabel); } sub die_exit { diff --git a/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm b/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm index 9be1d18f63c..84575ed01c6 100644 --- a/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm +++ b/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm @@ -49,7 +49,9 @@ sub new { %{$self->{modes}} = ( 'cpu' => 'network::cisco::common::mode::cpu', 'environment' => 'network::cisco::common::mode::environment', + 'list-interfaces' => 'snmp_standard::mode::listinterfaces', 'memory' => 'network::cisco::common::mode::memory', + 'packet-errors' => 'snmp_standard::mode::packeterrors', 'traffic' => 'snmp_standard::mode::traffic', ); diff --git a/centreon/lib/perl/plugins/os/linux/plugin.pm b/centreon/lib/perl/plugins/os/linux/plugin.pm index c87e6677936..652476a7b19 100644 --- a/centreon/lib/perl/plugins/os/linux/plugin.pm +++ b/centreon/lib/perl/plugins/os/linux/plugin.pm @@ -50,7 +50,9 @@ sub new { 'cpu' => 'snmp_standard::mode::cpu', 'diskio' => 'snmp_standard::mode::diskio', 'load' => 'snmp_standard::mode::loadaverage', + 'list-interfaces' => 'snmp_standard::mode::list-interfaces', 'memory' => 'os::linux::mode::memory', + 'packet-errors' => 'snmp_standard::mode::packeterrors', 'processcount' => 'snmp_standard::mode::processcount', 'storage' => 'snmp_standard::mode::storage', 'swap' => 'os::linux::mode::swap', diff --git a/centreon/lib/perl/plugins/os/windows/plugin.pm b/centreon/lib/perl/plugins/os/windows/plugin.pm index 07182d33e5f..1d97a129c05 100644 --- a/centreon/lib/perl/plugins/os/windows/plugin.pm +++ b/centreon/lib/perl/plugins/os/windows/plugin.pm @@ -49,7 +49,9 @@ sub new { %{$self->{modes}} = ( 'cpu' => 'snmp_standard::mode::cpu', 'load' => 'snmp_standard::mode::loadaverage', + 'list-interfaces' => 'snmp_standard::mode::listinterfaces', 'memory' => 'os::windows::mode::memory', + 'packet-errors' => 'snmp_standard::mode::packeterrors', 'processcount' => 'snmp_standard::mode::processcount', 'storage' => 'snmp_standard::mode::storage', 'swap' => 'os::windows::mode::swap', diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm b/centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm new file mode 100644 index 00000000000..a14af1f31e3 --- /dev/null +++ b/centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm @@ -0,0 +1,282 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package snmp_standard::mode::listinterfaces; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; +use Digest::MD5 qw(md5_hex); + +my @operstatus = ("up", "down", "testing", "unknown", "dormant", "notPresent", "lowerLayerDown"); +my %oids_iftable = ( + 'ifdesc' => '.1.3.6.1.2.1.2.2.1.2', + 'ifalias' => '.1.3.6.1.2.1.31.1.1.1.18', + 'ifname' => '.1.3.6.1.2.1.31.1.1.1.1' +); + +my $oid_operstatus = '.1.3.6.1.2.1.2.2.1.8'; +my $oid_speed32 = '.1.3.6.1.2.1.2.2.1.5'; # in b/s +my $oid_speed64 = '.1.3.6.1.2.1.31.1.1.1.15'; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "name" => { name => 'use_name' }, + "interface:s" => { name => 'interface' }, + "speed:s" => { name => 'speed' }, + "regexp" => { name => 'use_regexp' }, + "regexp-isensitive" => { name => 'use_regexpi' }, + "oid-filter:s" => { name => 'oid_filter', default => 'ifname'}, + "oid-display:s" => { name => 'oid_display', default => 'ifname'}, + "display-transform-src:s" => { name => 'display_transform_src' }, + "display-transform-dst:s" => { name => 'display_transform_dst' }, + }); + + $self->{interface_id_selected} = []; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + $self->{option_results}->{oid_filter} = lc($self->{option_results}->{oid_filter}); + if ($self->{option_results}->{oid_filter} !~ /^(ifdesc|ifalias|ifname)$/) { + $self->{output}->add_option_msg(short_msg => "Unsupported --oid-filter option."); + $self->{output}->option_exit(); + } + $self->{option_results}->{oid_display} = lc($self->{option_results}->{oid_display}); + if ($self->{option_results}->{oid_display} !~ /^(ifdesc|ifalias|ifname)$/) { + $self->{output}->add_option_msg(short_msg => "Unsupported --oid-display option."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->manage_selection(); + my $result = $self->get_additional_information(); + + my $interfaces_display = ''; + my $interfaces_display_append = ''; + foreach (sort @{$self->{interface_id_selected}}) { + my $display_value = $self->get_display_value(id => $_); + + my $interface_speed = (defined($result->{$oid_speed64 . "." . $_}) && $result->{$oid_speed64 . "." . $_} ne '' ? ($result->{$oid_speed64 . "." . $_}) : (int($result->{$oid_speed32 . "." . $_} / 1000 / 1000))); + if (defined($self->{option_results}->{speed}) && $self->{option_results}->{speed} ne '') { + $interface_speed = $self->{option_results}->{speed}; + } + + $interfaces_display .= $interfaces_display_append . "name = $display_value [speed = $interface_speed, status = " . $operstatus[$result->{$oid_operstatus . "." . $_} - 1] . ", id = $_]"; + $interfaces_display_append = ', '; + } + + $self->{output}->output_add(severity => 'OK', + short_msg => 'List interfaces: ' . $interfaces_display); + $self->{output}->display(nolabel => 1); + $self->{output}->exit(); +} + +sub get_additional_information { + my ($self, %options) = @_; + + my $oids = [$oid_operstatus, $oid_speed32]; + if (!$self->{snmp}->is_snmpv1()) { + push @$oids, $oid_speed64; + } + + $self->{snmp}->load(oids => $oids, instances => $self->{interface_id_selected}); + return $self->{snmp}->get_leef(); +} + +sub get_display_value { + my ($self, %options) = @_; + my $value = $self->{datas}->{$self->{option_results}->{oid_display} . "_" . $options{id}}; + + if (defined($self->{option_results}->{display_transform_src})) { + $self->{option_results}->{display_transform_dst} = '' if (!defined($self->{option_results}->{display_transform_dst})); + eval "\$value =~ s{$self->{option_results}->{display_transform_src}}{$self->{option_results}->{display_transform_dst}}"; + } + return $value; +} + +sub manage_selection { + my ($self, %options) = @_; + + $self->{datas} = {}; + $self->{datas}->{oid_filter} = $self->{option_results}->{oid_filter}; + $self->{datas}->{oid_display} = $self->{option_results}->{oid_display}; + my $result = $self->{snmp}->get_table(oid => $oids_iftable{$self->{option_results}->{oid_filter}}); + my $total_interface = 0; + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($key !~ /\.([0-9]+)$/); + $self->{datas}->{$self->{option_results}->{oid_filter} . "_" . $1} = $self->{output}->to_utf8($result->{$key}); + $total_interface = $1; + } + + if (scalar(keys %{$self->{datas}}) <= 0) { + $self->{output}->add_option_msg(short_msg => "Can't get interfaces..."); + $self->{output}->option_exit(); + } + + if ($self->{option_results}->{oid_filter} ne $self->{option_results}->{oid_display}) { + $result = $self->{snmp}->get_table(oid => $oids_iftable{$self->{option_results}->{oid_display}}); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($key !~ /\.([0-9]+)$/); + $self->{datas}->{$self->{option_results}->{oid_display} . "_" . $1} = $self->{output}->to_utf8($result->{$key}); + } + } + + if (!defined($self->{option_results}->{use_name}) && defined($self->{option_results}->{interface})) { + # get by ID + push @{$self->{interface_id_selected}}, $self->{option_results}->{interface}; + my $name = $self->{datas}->{$self->{option_results}->{oid_display} . "_" . $self->{option_results}->{interface}}; + if (!defined($name)) { + $self->{output}->add_option_msg(short_msg => "No interface found for id '" . $self->{option_results}->{interface} . "'."); + $self->{output}->option_exit(); + } + } else { + for (my $i = 0; $i <= $total_interface; $i++) { + my $filter_name = $self->{datas}->{$self->{option_results}->{oid_filter} . "_" . $i}; + next if (!defined($filter_name)); + if (!defined($self->{option_results}->{interface})) { + push @{$self->{interface_id_selected}}, $i; + next; + } + if (defined($self->{option_results}->{use_regexp}) && defined($self->{option_results}->{use_regexpi}) && $filter_name =~ /$self->{option_results}->{interface}/i) { + push @{$self->{interface_id_selected}}, $i; + } + if (defined($self->{option_results}->{use_regexp}) && !defined($self->{option_results}->{use_regexpi}) && $filter_name =~ /$self->{option_results}->{interface}/) { + push @{$self->{interface_id_selected}}, $i; + } + if (!defined($self->{option_results}->{use_regexp}) && !defined($self->{option_results}->{use_regexpi}) && $filter_name eq $self->{option_results}->{interface}) { + push @{$self->{interface_id_selected}}, $i; + } + } + + if (scalar(@{$self->{interface_id_selected}}) <= 0) { + $self->{output}->add_option_msg(short_msg => "No interface found for name '" . $self->{option_results}->{interface} . "'."); + $self->{output}->option_exit(); + } + } +} + +sub disco_format { + my ($self, %options) = @_; + + $self->{output}->add_disco_format(elements => ['name', 'total', 'status', 'interfaceid']); +} + +sub disco_show { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->manage_selection(); + my $result = $self->get_additional_information(); + foreach (sort @{$self->{interface_id_selected}}) { + my $display_value = $self->get_display_value(id => $_); + + my $interface_speed = (defined($result->{$oid_speed64 . "." . $_}) && $result->{$oid_speed64 . "." . $_} ne '' ? ($result->{$oid_speed64 . "." . $_}) : (int($result->{$oid_speed32 . "." . $_} / 1000 / 1000))); + if (defined($self->{option_results}->{speed}) && $self->{option_results}->{speed} ne '') { + $interface_speed = $self->{option_results}->{speed}; + } + + $self->{output}->add_disco_entry(name => $display_value, + total => $interface_speed, + status => $result->{$oid_operstatus . "." . $_}, + interfaceid => $_); + } +} + +1; + +__END__ + +=head1 MODE + +=over 8 + +=item B<--interface> + +Set the interface (number expected) ex: 1, 2,... (empty means 'check all interface'). + +=item B<--name> + +Allows to use interface name with option --interface instead of interface oid index. + +=item B<--regexp> + +Allows to use regexp to filter interfaces (with option --name). + +=item B<--regexp-isensitive> + +Allows to use regexp non case-sensitive (with --regexp). + +=item B<--speed> + +Set interface speed (in Mb). + +=item B<--oid-filter> + +Choose OID used to filter interface (default: ifName) (values: ifDesc, ifAlias, ifName). + +=item B<--oid-display> + +Choose OID used to display interface (default: ifName) (values: ifDesc, ifAlias, ifName). + +=item B<--display-transform-src> + +Regexp src to transform display value. (security risk!!!) + +=item B<--display-transform-dst> + +Regexp dst to transform display value. (security risk!!!) + +=back + +=cut diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/packeterrors.pm b/centreon/lib/perl/plugins/snmp_standard/mode/packeterrors.pm new file mode 100644 index 00000000000..a19d78f90d8 --- /dev/null +++ b/centreon/lib/perl/plugins/snmp_standard/mode/packeterrors.pm @@ -0,0 +1,528 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package snmp_standard::mode::packeterrors; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::statefile; +use Digest::MD5 qw(md5_hex); + +my @operstatus = ("up", "down", "testing", "unknown", "dormant", "notPresent", "lowerLayerDown"); +my %oids_iftable = ( + 'ifdesc' => '.1.3.6.1.2.1.2.2.1.2', + 'ifalias' => '.1.3.6.1.2.1.31.1.1.1.18', + 'ifname' => '.1.3.6.1.2.1.31.1.1.1.1' +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning-in-discard:s" => { name => 'warning_in_discard' }, + "critical-in-discard:s" => { name => 'critical_in_discard' }, + "warning-out-discard:s" => { name => 'warning_out_discard' }, + "critical-out-discard:s" => { name => 'critical_out_discard' }, + "warning-in-error:s" => { name => 'warning_in_error' }, + "critical-in-error:s" => { name => 'critical_in_error' }, + "warning-out-error:s" => { name => 'warning_out_error' }, + "critical-out-error:s" => { name => 'critical_out_error' }, + "reload-cache-time:s" => { name => 'reload_cache_time' }, + "name" => { name => 'use_name' }, + "interface:s" => { name => 'interface' }, + "skip" => { name => 'skip' }, + "regexp" => { name => 'use_regexp' }, + "regexp-isensitive" => { name => 'use_regexpi' }, + "oid-filter:s" => { name => 'oid_filter', default => 'ifname'}, + "oid-display:s" => { name => 'oid_display', default => 'ifname'}, + "display-transform-src:s" => { name => 'display_transform_src' }, + "display-transform-dst:s" => { name => 'display_transform_dst' }, + "show-cache" => { name => 'show_cache' }, + }); + + $self->{interface_id_selected} = []; + $self->{statefile_cache} = centreon::plugins::statefile->new(%options); + $self->{statefile_value} = centreon::plugins::statefile->new(%options); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + # 'discard' treshold + if (($self->{perfdata}->threshold_validate(label => 'warning-in-discard', value => $self->{option_results}->{warning_in_discard})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'in discard' threshold '" . $self->{option_results}->{warning_in_discard} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical-in-discard', value => $self->{option_results}->{critical_in_discard})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'in discard' threshold '" . $self->{option_results}->{critical_in_discard} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warning-out-discard', value => $self->{option_results}->{warning_out_discard})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'out discard' threshold '" . $self->{option_results}->{warning_out_disard} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical-out-discard', value => $self->{option_results}->{critical_out_discard})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'out discard' threshold '" . $self->{option_results}->{critical_out_discard} . "'."); + $self->{output}->option_exit(); + } + + # 'errror' treshold + if (($self->{perfdata}->threshold_validate(label => 'warning-in-error', value => $self->{option_results}->{warning_in_error})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'in error' threshold '" . $self->{option_results}->{warning_in_error} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical-in-error', value => $self->{option_results}->{critical_in_error})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'in error' threshold '" . $self->{option_results}->{critical_in_error} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'warning-out-error', value => $self->{option_results}->{warning_out_error})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning 'out error' threshold '" . $self->{option_results}->{warning_out_disard} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical-out-error', value => $self->{option_results}->{critical_out_error})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical 'out error' threshold '" . $self->{option_results}->{critical_out_error} . "'."); + $self->{output}->option_exit(); + } + + $self->{option_results}->{oid_filter} = lc($self->{option_results}->{oid_filter}); + if ($self->{option_results}->{oid_filter} !~ /^(ifdesc|ifalias|ifname)$/) { + $self->{output}->add_option_msg(short_msg => "Unsupported --oid-filter option."); + $self->{output}->option_exit(); + } + $self->{option_results}->{oid_display} = lc($self->{option_results}->{oid_display}); + if ($self->{option_results}->{oid_display} !~ /^(ifdesc|ifalias|ifname)$/) { + $self->{output}->add_option_msg(short_msg => "Unsupported --oid-display option."); + $self->{output}->option_exit(); + } + + $self->{statefile_cache}->check_options(%options); + $self->{statefile_value}->check_options(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + $self->{hostname} = $self->{snmp}->get_hostname(); + + $self->manage_selection(); + + my $oid_adminstatus = '.1.3.6.1.2.1.2.2.1.7'; + my $oid_operstatus = '.1.3.6.1.2.1.2.2.1.8'; + + # 32bits + my $oid_ifInUcastPkts = '.1.3.6.1.2.1.2.2.1.11'; + my $oid_ifInBroadcastPkts = '.1.3.6.1.2.1.31.1.1.1.3'; + my $oid_ifInMulticastPkts = '.1.3.6.1.2.1.31.1.1.1.2'; + my $oid_ifOutUcastPkts = '.1.3.6.1.2.1.2.2.1.17'; + my $oid_ifOutMulticastPkts = '.1.3.6.1.2.1.31.1.1.1.4'; + my $oid_ifOutBroadcastPkts = '.1.3.6.1.2.1.31.1.1.1.5'; + + # 64 bits + my $oid_ifHCInUcastPkts = '.1.3.6.1.2.1.31.1.1.1.7'; + my $oid_ifHCInMulticastPkts = '.1.3.6.1.2.1.31.1.1.1.8'; + my $oid_ifHCInBroadcastPkts = '.1.3.6.1.2.1.31.1.1.1.9'; + my $oid_ifHCOutUcastPkts = '.1.3.6.1.2.1.31.1.1.1.11'; + my $oid_ifHCOutMulticastPkts = '.1.3.6.1.2.1.31.1.1.1.12'; + my $oid_ifHCOutBroadcastPkts = '.1.3.6.1.2.1.31.1.1.1.13'; + + # 'discard' 'error' only 32 bits + my $oid_ifInDiscards = '.1.3.6.1.2.1.2.2.1.13'; + my $oid_ifInErrors = '.1.3.6.1.2.1.2.2.1.14'; + my $oid_ifOutDiscards = '.1.3.6.1.2.1.2.2.1.19'; + my $oid_ifOutErrors = '.1.3.6.1.2.1.2.2.1.20'; + + my $new_datas = {}; + $self->{statefile_value}->read(statefile => "snmpstandard_" . $self->{hostname} . '_' . $self->{mode} . '_' . (defined($self->{option_results}->{interface}) ? md5_hex($self->{option_results}->{interface}) : md5_hex('all'))); + + foreach (@{$self->{interface_id_selected}}) { + $self->{snmp}->load(oids => [$oid_adminstatus . "." . $_, $oid_operstatus . "." . $_, + $oid_ifInUcastPkts . "." . $_, $oid_ifInBroadcastPkts . "." . $_, $oid_ifInMulticastPkts . "." . $_, + $oid_ifOutUcastPkts . "." . $_, $oid_ifOutMulticastPkts . "." . $_, $oid_ifOutBroadcastPkts . "." . $_, + $oid_ifInDiscards . "." . $_, $oid_ifInErrors . "." . $_, + $oid_ifOutDiscards . "." . $_, $oid_ifOutErrors . "." . $_]); + if (!$self->{snmp}->is_snmpv1()) { + $self->{snmp}->load(oids => [$oid_ifHCInUcastPkts . "." . $_, $oid_ifHCInMulticastPkts . "." . $_, $oid_ifHCInMulticastPkts . "." . $_, + $oid_ifHCOutUcastPkts . "." . $_, $oid_ifHCOutMulticastPkts . "." . $_, $oid_ifHCOutBroadcastPkts . "." . $_]); + } + } + + my $result = $self->{snmp}->get_leef(); + $new_datas->{last_timestamp} = time(); + my $old_timestamp; + if (!defined($self->{option_results}->{interface}) || defined($self->{option_results}->{use_regexp})) { + $self->{output}->output_add(severity => 'OK', + short_msg => 'All interfaces are ok.'); + } + + foreach (sort @{$self->{interface_id_selected}}) { + my $display_value = $self->get_display_value(id => $_); + + if ($operstatus[$result->{$oid_operstatus . "." . $_} - 1] ne "up") { + if (!defined($self->{option_results}->{skip}) && (!defined($result->{$oid_adminstatus . "." . $_}) || $operstatus[$result->{$oid_adminstatus . "." . $_} - 1] eq 'up') ) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => "Interface '" . $display_value . "' is not ready: " . $operstatus[$result->{$oid_operstatus . "." . $_} - 1]); + } else { + $self->{output}->output_add(long_msg => "Skip interface '" . $display_value . "'."); + } + next; + } + + ################# + # New values + ################# + my $old_mode = $self->{statefile_value}->get(name => 'mode_' . $_); + $new_datas->{'mode_' . $_} = '32'; + $new_datas->{'in_discard_' . $_} = $result->{$oid_ifInDiscards . "." . $_}; + $new_datas->{'in_error_' . $_} = $result->{$oid_ifInErrors . "." . $_}; + $new_datas->{'out_discard_' . $_} = $result->{$oid_ifOutDiscards . "." . $_}; + $new_datas->{'out_error_' . $_} = $result->{$oid_ifOutErrors . "." . $_}; + + $new_datas->{'in_ucast_' . $_} = $result->{$oid_ifInUcastPkts . "." . $_}; + $new_datas->{'in_bcast_' . $_} = defined($result->{$oid_ifInBroadcastPkts . "." . $_}) ? $result->{$oid_ifInBroadcastPkts . "." . $_} : 0; + $new_datas->{'in_mcast_' . $_} = defined($result->{$oid_ifInMulticastPkts . "." . $_}) ? $result->{$oid_ifInMulticastPkts . "." . $_} : 0; + $new_datas->{'out_ucast_' . $_} = $result->{$oid_ifOutUcastPkts . "." . $_}; + $new_datas->{'out_bcast_' . $_} = defined($result->{$oid_ifOutMulticastPkts . "." . $_}) ? $result->{$oid_ifOutMulticastPkts . "." . $_} : 0; + $new_datas->{'out_mcast_' . $_} = defined($result->{$oid_ifOutBroadcastPkts . "." . $_}) ? $result->{$oid_ifOutBroadcastPkts . "." . $_} : 0; + + if (defined($result->{$oid_ifHCInUcastPkts . "." . $_}) && $result->{$oid_ifHCInUcastPkts . "." . $_} ne '' && $result->{$oid_ifHCInUcastPkts . "." . $_} != 0) { + $new_datas->{'in_ucast_' . $_} = $result->{$oid_ifHCInUcastPkts . "." . $_}; + $new_datas->{'in_mcast_' . $_} = defined($result->{$oid_ifHCInMulticastPkts . "." . $_}) ? $result->{$oid_ifHCInMulticastPkts . "." . $_} : 0; + $new_datas->{'in_bcast_' . $_} = defined($result->{$oid_ifHCInBroadcastPkts . "." . $_}) ? $result->{$oid_ifHCInBroadcastPkts . "." . $_} : 0; + $new_datas->{'out_ucast_' . $_} = $result->{$oid_ifHCOutUcastPkts . "." . $_}; + $new_datas->{'out_mcast_' . $_} = defined($result->{$oid_ifHCOutMulticastPkts . "." . $_}) ? $result->{$oid_ifHCOutMulticastPkts . "." . $_} : 0; + $new_datas->{'out_bcast_' . $_} = defined($result->{$oid_ifHCOutBroadcastPkts . "." . $_}) ? $result->{$oid_ifHCOutBroadcastPkts . "." . $_} : 0; + $new_datas->{'mode_' . $_} = '64'; + } + + # We change mode. need to recreate a buffer + if (!defined($old_mode) || $new_datas->{'mode_' . $_} ne $old_mode) { + next; + } + + ################# + # Old values + ################# + my @getting = ('in_ucast', 'in_bcast', 'in_mcast', 'out_ucast', 'out_bcast', 'out_mcast', + 'in_discard', 'in_error', 'out_discard', 'out_error'); + my $old_datas = {}; + $old_timestamp = $self->{statefile_value}->get(name => 'last_timestamp'); + foreach my $key (@getting) { + $old_datas->{$key} = $self->{statefile_value}->get(name => $key . '_' . $_); + if (!defined($old_datas->{$key}) || $new_datas->{$key . '_' . $_} < $old_datas->{$key}) { + # We set 0. Has reboot. + $old_datas->{$key} = 0; + } + } + + if (!defined($old_timestamp)) { + next; + } + my $time_delta = $new_datas->{last_timestamp} - $old_timestamp; + if ($time_delta <= 0) { + # At least one second. two fast calls ;) + $time_delta = 1; + } + + ############ + + my $total_in_packets = ($new_datas->{'in_ucast_' . $_} - $old_datas->{in_ucast}) + ($new_datas->{'in_bcast_' . $_} - $old_datas->{in_bcast}) + ($new_datas->{'in_mcast_' . $_} - $old_datas->{in_mcast}); + my $total_out_packets = ($new_datas->{'out_ucast_' . $_} - $old_datas->{out_ucast}) + ($new_datas->{'out_bcast_' . $_} - $old_datas->{out_bcast}) + ($new_datas->{'out_mcast_' . $_} - $old_datas->{out_mcast}); + + my $in_discard_absolute_per_sec = ($new_datas->{'in_discard_' . $_} - $old_datas->{in_discard}) / $time_delta; + my $in_error_absolute_per_sec = ($new_datas->{'in_error_' . $_} - $old_datas->{in_error}) / $time_delta; + my $out_discard_absolute_per_sec = ($new_datas->{'out_discard_' . $_} - $old_datas->{out_discard}) / $time_delta; + my $out_error_absolute_per_sec = ($new_datas->{'out_error_' . $_} - $old_datas->{out_error}) / $time_delta; + my $in_discard_prct = ($total_in_packets == 0) ? 0 : ($new_datas->{'in_discard_' . $_} - $old_datas->{in_discard}) * 100 / $total_in_packets; + my $in_error_prct = ($total_in_packets == 0) ? 0 : ($new_datas->{'in_error_' . $_} - $old_datas->{in_error}) * 100 / $total_in_packets; + my $out_discard_prct = ($total_out_packets == 0) ? 0 : ($new_datas->{'out_discard_' . $_} - $old_datas->{out_discard}) * 100 / $total_out_packets; + my $out_error_prct = ($total_out_packets == 0) ? 0 : ($new_datas->{'out_error_' . $_} - $old_datas->{out_error}) * 100 / $total_out_packets; + + ########### + # Manage Output + ########### + my $exit1 = $self->{perfdata}->threshold_check(value => $in_discard_prct, threshold => [ { label => 'critical-in-discard', 'exit_litteral' => 'critical' }, { label => 'warning-in-discard', exit_litteral => 'warning' } ]); + my $exit2 = $self->{perfdata}->threshold_check(value => $in_error_prct, threshold => [ { label => 'critical-in-error', 'exit_litteral' => 'critical' }, { label => 'warning-in-error', exit_litteral => 'warning' } ]); + my $exit3 = $self->{perfdata}->threshold_check(value => $out_discard_prct, threshold => [ { label => 'critical-out-discard', 'exit_litteral' => 'critical' }, { label => 'warning-out-discard', exit_litteral => 'warning' } ]); + my $exit4 = $self->{perfdata}->threshold_check(value => $out_error_prct, threshold => [ { label => 'critical-out-error', 'exit_litteral' => 'critical' }, { label => 'warning-out-error', exit_litteral => 'warning' } ]); + + my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2, $exit3, $exit4 ]); + $self->{output}->output_add(long_msg => sprintf("Interface '%s' Packets In Discard : %.2f %% (%d), In Error : %.2f %% (%d), Out Discard: %.2f %% (%d), Out Error: %.2f %% (%d)", $display_value, + $in_discard_prct, $new_datas->{'in_discard_' . $_} - $old_datas->{in_discard}, + $in_error_prct, $new_datas->{'in_error_' . $_} - $old_datas->{in_error}, + $out_discard_prct, $new_datas->{'out_discard_' . $_} - $old_datas->{out_discard}, + $out_error_prct, $new_datas->{'out_error_' . $_} - $old_datas->{out_error} + )); + if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1) || (defined($self->{option_results}->{interface}) && !defined($self->{option_results}->{use_regexp}))) { + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Interface '%s' Packets In Discard : %.2f %% (%d), In Error : %.2f %% (%d), Out Discard: %.2f %% (%d), Out Error: %.2f %% (%d)", $display_value, + $in_discard_prct, $new_datas->{'in_discard_' . $_} - $old_datas->{in_discard}, + $in_error_prct, $new_datas->{'in_error_' . $_} - $old_datas->{in_error}, + $out_discard_prct, $new_datas->{'out_discard_' . $_} - $old_datas->{out_discard}, + $out_error_prct, $new_datas->{'out_error_' . $_} - $old_datas->{out_error} + )); + } + + my $extra_label = ''; + $extra_label = '_' . $display_value if (!defined($self->{option_results}->{interface}) || defined($self->{option_results}->{use_regexp})); + $self->{output}->perfdata_add(label => 'packets_discard_in' . $extra_label, unit => '%', + value => sprintf("%.2f", $in_discard_prct), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-in-discard'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-in-discard'), + min => 0, max => 100); + $self->{output}->perfdata_add(label => 'packets_error_in' . $extra_label, unit => '%', + value => sprintf("%.2f", $in_error_prct), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-in-error'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-in-error'), + min => 0, max => 100); + $self->{output}->perfdata_add(label => 'packets_discard_out' . $extra_label, unit => '%', + value => sprintf("%.2f", $out_discard_prct), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-out-discard'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-out-discard'), + min => 0, max => 100); + $self->{output}->perfdata_add(label => 'packets_error_out' . $extra_label, unit => '%', + value => sprintf("%.2f", $out_error_prct), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-out-error'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-out-error'), + min => 0, max => 100); + } + + $self->{statefile_value}->write(data => $new_datas); + if (!defined($old_timestamp)) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Buffer creation..."); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub get_display_value { + my ($self, %options) = @_; + my $value = $self->{statefile_cache}->get(name => $self->{option_results}->{oid_display} . "_" . $options{id}); + + if (defined($self->{option_results}->{display_transform_src})) { + $self->{option_results}->{display_transform_dst} = '' if (!defined($self->{option_results}->{display_transform_dst})); + eval "\$value =~ s{$self->{option_results}->{display_transform_src}}{$self->{option_results}->{display_transform_dst}}"; + } + return $value; +} + +sub reload_cache { + my ($self) = @_; + my $datas = {}; + + $datas->{oid_filter} = $self->{option_results}->{oid_filter}; + $datas->{oid_display} = $self->{option_results}->{oid_display}; + my $result = $self->{snmp}->get_table(oid => $oids_iftable{$self->{option_results}->{oid_filter}}); + my $last_num = 0; + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($key !~ /\.([0-9]+)$/); + $datas->{$self->{option_results}->{oid_filter} . "_" . $1} = $self->{output}->to_utf8($result->{$key}); + $last_num = $1; + } + + if (scalar(keys %$datas) <= 0) { + $self->{output}->add_option_msg(short_msg => "Can't construct cache..."); + $self->{output}->option_exit(); + } + + if ($self->{option_results}->{oid_filter} ne $self->{option_results}->{oid_display}) { + $result = $self->{snmp}->get_table(oid => $oids_iftable{$self->{option_results}->{oid_display}}); + foreach my $key ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($key !~ /\.([0-9]+)$/); + $datas->{$self->{option_results}->{oid_display} . "_" . $1} = $self->{output}->to_utf8($result->{$key}); + } + } + + $datas->{total_interface} = $last_num; + $self->{statefile_cache}->write(data => $datas); +} + +sub manage_selection { + my ($self, %options) = @_; + + # init cache file + my $has_cache_file = $self->{statefile_cache}->read(statefile => 'cache_snmpstandard_' . $self->{hostname} . '_' . $self->{mode}); + if (defined($self->{option_results}->{show_cache})) { + $self->{output}->add_option_msg(long_msg => $self->{statefile_cache}->get_string_content()); + $self->{output}->option_exit(); + } + + my $timestamp_cache = $self->{statefile_cache}->get(name => 'last_timestamp'); + my $oid_display = $self->{statefile_cache}->get(name => 'oid_display'); + my $oid_filter = $self->{statefile_cache}->get(name => 'oid_filter'); + if ($has_cache_file == 0 || + ($self->{option_results}->{oid_display} !~ /^($oid_display|$oid_filter)$/i || $self->{option_results}->{oid_filter} !~ /^($oid_display|$oid_filter)$/i) || + (defined($timestamp_cache) && (time() - $timestamp_cache) > (($self->{option_results}->{reload_cache_time}) * 60))) { + $self->reload_cache(); + $self->{statefile_cache}->read(); + } + + my $total_interface = $self->{statefile_cache}->get(name => 'total_interface'); + if (!defined($self->{option_results}->{use_name}) && defined($self->{option_results}->{interface})) { + # get by ID + push @{$self->{interface_id_selected}}, $self->{option_results}->{interface}; + my $name = $self->{statefile_cache}->get(name => $self->{option_results}->{oid_display} . "_" . $self->{option_results}->{interface}); + if (!defined($name)) { + $self->{output}->add_option_msg(short_msg => "No interface found for id '" . $self->{option_results}->{interface} . "'."); + $self->{output}->option_exit(); + } + } else { + for (my $i = 0; $i <= $total_interface; $i++) { + my $filter_name = $self->{statefile_cache}->get(name => $self->{option_results}->{oid_filter} . "_" . $i); + next if (!defined($filter_name)); + if (!defined($self->{option_results}->{interface})) { + push @{$self->{interface_id_selected}}, $i; + next; + } + if (defined($self->{option_results}->{use_regexp}) && defined($self->{option_results}->{use_regexpi}) && $filter_name =~ /$self->{option_results}->{interface}/i) { + push @{$self->{interface_id_selected}}, $i; + } + if (defined($self->{option_results}->{use_regexp}) && !defined($self->{option_results}->{use_regexpi}) && $filter_name =~ /$self->{option_results}->{interface}/) { + push @{$self->{interface_id_selected}}, $i; + } + if (!defined($self->{option_results}->{use_regexp}) && !defined($self->{option_results}->{use_regexpi}) && $filter_name eq $self->{option_results}->{interface}) { + push @{$self->{interface_id_selected}}, $i; + } + } + + if (scalar(@{$self->{interface_id_selected}}) <= 0) { + $self->{output}->add_option_msg(short_msg => "No interface found for name '" . $self->{option_results}->{interface} . "' (maybe you should reload cache file)."); + $self->{output}->option_exit(); + } + } +} + +1; + +__END__ + +=head1 MODE + +=over 8 + +=item B<--warning-in-discard> + +Threshold warning in percent for 'in' discard packets. + +=item B<--critical-in-discard> + +Threshold critical in percent for 'in' discard packets. + +=item B<--warning-out-discard> + +Threshold warning in percent for 'out' discard packets. + +=item B<--critical-out-discard> + +Threshold critical in percent for 'out' discard packets. + +=item B<--warning-in-error> + +Threshold warning in percent for 'in' error packets. + +=item B<--critical-in-error> + +Threshold critical in percent for 'in' error packets. + +=item B<--warning-out-error> + +Threshold warning in percent for 'out' error packets. + +=item B<--critical-out-error> + +Threshold critical in percent for 'out' error packets. + +=item B<--interface> + +Set the interface (number expected) ex: 1, 2,... (empty means 'check all interface'). + +=item B<--name> + +Allows to use interface name with option --interface instead of interface oid index. + +=item B<--regexp> + +Allows to use regexp to filter interfaces (with option --name). + +=item B<--regexp-isensitive> + +Allows to use regexp non case-sensitive (with --regexp). + +=item B<--speed> + +Set interface speed (in Mb). + +=item B<--skip> + +Skip errors on interface status. + +=item B<--reload-cache-time> + +Time in seconds before reloading cache file (default: 180). + +=item B<--oid-filter> + +Choose OID used to filter interface (default: ifName) (values: ifDesc, ifAlias, ifName). + +=item B<--oid-display> + +Choose OID used to display interface (default: ifName) (values: ifDesc, ifAlias, ifName). + +=item B<--display-transform-src> + +Regexp src to transform display value. (security risk!!!) + +=item B<--display-transform-dst> + +Regexp dst to transform display value. (security risk!!!) + +=item B<--show-cache> + +Display cache interface datas. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index 73da4dbc84e..65c743d52f3 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -373,38 +373,6 @@ sub manage_selection { } } -sub disco_format { - my ($self, %options) = @_; - - $self->{output}->add_disco_format(elements => ['name', 'total', 'status', 'interfaceid']); -} - -sub disco_show { - my ($self, %options) = @_; - # $options{snmp} = snmp object - $self->{snmp} = $options{snmp}; - $self->{hostname} = $self->{snmp}->get_hostname(); - - my $oid_operstatus = '.1.3.6.1.2.1.2.2.1.8'; - my $oid_speed32 = '.1.3.6.1.2.1.2.2.1.5'; # in b/s - - $self->manage_selection(); - $self->{snmp}->load(oids => [$oid_operstatus, $oid_speed32], instances => $self->{interface_id_selected}); - my $result = $self->{snmp}->get_leef(); - foreach (sort @{$self->{interface_id_selected}}) { - my $display_value = $self->get_display_value(id => $_); - my $interface_speed = int($result->{$oid_speed32 . "." . $_} / 1000 / 1000); - if (defined($self->{option_results}->{speed}) && $self->{option_results}->{speed} ne '') { - $interface_speed = $self->{option_results}->{speed}; - } - - $self->{output}->add_disco_entry(name => $display_value, - total => $interface_speed, - status => $result->{$oid_operstatus . "." . $_}, - interfaceid => $_); - } -} - 1; __END__ From 95cfd15a12e5de09919da0c4fb15ee2412a4723e Mon Sep 17 00:00:00 2001 From: qgarnier Date: Sun, 24 Nov 2013 20:04:13 +0100 Subject: [PATCH 155/458] + Add filter status --- .../perl/plugins/snmp_standard/mode/listinterfaces.pm | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm b/centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm index a14af1f31e3..b46fa88bc30 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm @@ -64,6 +64,7 @@ sub new { "name" => { name => 'use_name' }, "interface:s" => { name => 'interface' }, "speed:s" => { name => 'speed' }, + "filter-status:s" => { name => 'filter_status' }, "regexp" => { name => 'use_regexp' }, "regexp-isensitive" => { name => 'use_regexpi' }, "oid-filter:s" => { name => 'oid_filter', default => 'ifname'}, @@ -110,6 +111,9 @@ sub run { if (defined($self->{option_results}->{speed}) && $self->{option_results}->{speed} ne '') { $interface_speed = $self->{option_results}->{speed}; } + if (defined($self->{option_results}->{filter_status}) && $operstatus[$result->{$oid_operstatus . "." . $_} - 1] !~ /$self->{option_results}->{filter_status}/i) { + next; + } $interfaces_display .= $interfaces_display_append . "name = $display_value [speed = $interface_speed, status = " . $operstatus[$result->{$oid_operstatus . "." . $_} - 1] . ", id = $_]"; $interfaces_display_append = ', '; @@ -225,6 +229,9 @@ sub disco_show { if (defined($self->{option_results}->{speed}) && $self->{option_results}->{speed} ne '') { $interface_speed = $self->{option_results}->{speed}; } + if (defined($self->{option_results}->{filter_status}) && $operstatus[$result->{$oid_operstatus . "." . $_} - 1] !~ /$self->{option_results}->{filter_status}/i) { + next; + } $self->{output}->add_disco_entry(name => $display_value, total => $interface_speed, @@ -261,6 +268,10 @@ Allows to use regexp non case-sensitive (with --regexp). Set interface speed (in Mb). +=item B<--filter-status> + +Display interfaces matching the filter (example: 'up'). + =item B<--oid-filter> Choose OID used to filter interface (default: ifName) (values: ifDesc, ifAlias, ifName). From 138a4ac7cb55559eef2a5eefa17592b0ebe7a844 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 25 Nov 2013 10:29:16 +0100 Subject: [PATCH 156/458] + Add mode 'stack' for Cisco --- .../perl/plugins/network/cisco/3750/plugin.pm | 1 + .../network/cisco/common/mode/stack.pm | 135 ++++++++++++++++++ 2 files changed, 136 insertions(+) create mode 100644 centreon/lib/perl/plugins/network/cisco/common/mode/stack.pm diff --git a/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm b/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm index 84575ed01c6..8e08577fb41 100644 --- a/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm +++ b/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm @@ -52,6 +52,7 @@ sub new { 'list-interfaces' => 'snmp_standard::mode::listinterfaces', 'memory' => 'network::cisco::common::mode::memory', 'packet-errors' => 'snmp_standard::mode::packeterrors', + 'stack' => 'network::cisco::common::mode::stack', 'traffic' => 'snmp_standard::mode::traffic', ); diff --git a/centreon/lib/perl/plugins/network/cisco/common/mode/stack.pm b/centreon/lib/perl/plugins/network/cisco/common/mode/stack.pm new file mode 100644 index 00000000000..3410645fb01 --- /dev/null +++ b/centreon/lib/perl/plugins/network/cisco/common/mode/stack.pm @@ -0,0 +1,135 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::cisco::common::mode::stack; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %map_role = ( + 1 => 'master', + 2 => 'member', + 3 => 'notMember', + 4 => 'standby' +); +my %states = ( + 1 => ['waiting', 'WARNING'], + 2 => ['progressing', 'WARNING'], + 3 => ['added', 'WARNING'], + 4 => ['ready', 'OK'], + 5 => ['sdmMismatch', 'CRITICAL'], + 6 => ['verMismatch', 'CRITICAL'], + 7 => ['featureMismatch', 'CRITICAL'], + 8 => ['newMasterInit', 'WARNING'], + 9 => ['provisioned', 'OK'], + 10 => ['invalid', 'WARNING'], + 11 => ['removed', 'WARNING'], +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_cswRingRedundant = '.1.3.6.1.4.1.9.9.500.1.1.3.0'; + my $oid_cswSwitchRole = '.1.3.6.1.4.1.9.9.500.1.2.1.1.3'; + my $oid_cswSwitchState = '.1.3.6.1.4.1.9.9.500.1.2.1.1.6'; + my $result = $self->{snmp}->get_leef(oids => [$oid_cswRingRedundant], nothing_quit => 1); + my $result_state = $self->{snmp}->get_table(oid => $oid_cswSwitchState, nothing_quit => 1); + my $result_role = $self->{snmp}->get_table(oid => $oid_cswSwitchRole); + + $self->{output}->output_add(severity => 'OK', + short_msg => 'Stack ring is redundant'); + if ($result->{$oid_cswRingRedundant} != 1) { + $self->{output}->output_add(severity => 'WARNING', + short_msg => 'Stack ring is not redundant'); + } + + foreach my $oid (keys %$result_state) { + $oid =~ /\.([0-9]+)$/; + my $instance = $1; + + my $state = $result_state->{$oid}; + my $role = defined($result_role->{$oid_cswSwitchRole . '.' . $instance}) ? $result_role->{$oid_cswSwitchRole . '.' . $instance} : 'unknown'; + # .1001, .2001 the instance. + my $number = int(($instance - 1) / 1000); + + $self->{output}->output_add(long_msg => sprintf("Member '%s' state is %s [Role is '%s']", $number, + ${$states{$state}}[0], $map_role{$role})); + if (${$states{$state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states{$state}}[1], + short_msg => sprintf("Member '%s' state is %s", $number, + ${$states{$state}}[0])); + } + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check Cisco Stack (CISCO-STACKWISE-MIB). + +=over 8 + +=back + +=cut + \ No newline at end of file From 5d42e80edcabe6d018b2f06804e6d641cbe1f2a2 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 25 Nov 2013 10:38:42 +0100 Subject: [PATCH 157/458] + Remove a wrong mode --- centreon/lib/perl/plugins/os/windows/plugin.pm | 1 - 1 file changed, 1 deletion(-) diff --git a/centreon/lib/perl/plugins/os/windows/plugin.pm b/centreon/lib/perl/plugins/os/windows/plugin.pm index 1d97a129c05..3f65a0001d6 100644 --- a/centreon/lib/perl/plugins/os/windows/plugin.pm +++ b/centreon/lib/perl/plugins/os/windows/plugin.pm @@ -48,7 +48,6 @@ sub new { $self->{version} = '0.1'; %{$self->{modes}} = ( 'cpu' => 'snmp_standard::mode::cpu', - 'load' => 'snmp_standard::mode::loadaverage', 'list-interfaces' => 'snmp_standard::mode::listinterfaces', 'memory' => 'os::windows::mode::memory', 'packet-errors' => 'snmp_standard::mode::packeterrors', From 03d50e0c8fb5f3c72109a30ebae3bfa01dd2728e Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Mon, 25 Nov 2013 10:47:03 +0100 Subject: [PATCH 158/458] fixes #4235; displays date on log messages --- .../lib/perl/centreon/script/logAnalyser.pm | 38 ++++++++++++------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/centreon/lib/perl/centreon/script/logAnalyser.pm b/centreon/lib/perl/centreon/script/logAnalyser.pm index a6278e28687..90336a17262 100644 --- a/centreon/lib/perl/centreon/script/logAnalyser.pm +++ b/centreon/lib/perl/centreon/script/logAnalyser.pm @@ -7,6 +7,18 @@ use centreon::script; use base qw(centreon::script); +=head2 $self->log_and_exit($msg) + +Logs a message and exits script. + +=cut +sub log_and_exit($$) { + my ($self, $msg) = @_; + + $self->{logger}->writeLogError($msg); + exit 1; +} + sub new { my $class = shift; my $self = $class->SUPER::new("logAnalyser", @@ -33,18 +45,18 @@ sub read_config { goto error if $status == -1; if ($sth->fetchrow_hashref()->{value} eq "broker") { - die "This script is only suitable for NDO"; + $self->log_and_exit("This script is only suitable for NDO"); } ($status, $sth) = $self->{csdb}->query(<<"EOQ"); SELECT archive_log, archive_retention FROM config EOQ goto error if $status == -1; $self->{config} = $sth->fetchrow_hashref(); - die "No configuration found in database" if !defined $self->{config}->{archive_log}; + $self->log_and_exit("No configuration found in database") if !defined $self->{config}->{archive_log}; return; error: - die "Failed to read configuration from database" + $self->log_and_exit("Failed to read configuration from database") } =head2 date_to_time($date) @@ -76,7 +88,7 @@ sub reset_position_flag { my $status = $self->{csdb}->do(<<"EOQ"); UPDATE instance SET log_flag = '0' WHERE instance_id = '$instance' EOQ - die "Failed to reset the position flag into database" if $status == -1; + $self->log_and_exit("Failed to reset the position flag into database") if $status == -1; } sub commit_to_log { @@ -109,7 +121,7 @@ sub parse_file($$$) { my ($status, $sth) = $self->{csdb}->query(<<"EOQ"); SELECT `log_flag`,`last_ctime` FROM `instance` WHERE `instance_id`='$instance' EOQ - die "Cannot read previous run information from database" if $status == -1; + $self->log_and_exit("Cannot read previous run information from database") if $status == -1; my $prev_run_info = $sth->fetchrow_hashref(); # Get History Flag @@ -225,7 +237,7 @@ EOQ close FILE; if ($@) { $self->{csdb}->rollback; - die "Database error: $@"; + $self->log_and_exit("Database error: $@"); } $self->{csdb}->transaction_mode(0); } @@ -248,7 +260,7 @@ AND `nagios_server`.`id` = `cfg_nagios`.`nagios_server_id` AND `nagios_server`.`ns_activate` = '1' AND `cfg_nagios`.`nagios_activate` = '1' EOQ - die "Failed to read instance configuration" if $status == -1; + $self->log_and_exit("Failed to read instance configuration") if $status == -1; $archives = $sth->fetchrow_hashref()->{log_archive_path}; } else { $archives = "$self->{centreon_config}->{VarLib}/log/$instance/archives/"; @@ -304,12 +316,12 @@ AND `nagios_server`.`id` = `cfg_nagios`.`nagios_server_id` AND `nagios_server`.`ns_activate` = '1' AND `cfg_nagios`.`nagios_activate` = '1' EOQ - die "Cannot read logfile from database" if $status == -1; + $self->log_and_exit("Cannot read logfile from database") if $status == -1; my $data = $sth->fetchrow_hashref(); $logfile = $data->{log_file}; $archivepath = $data->{log_archive_path}; $archivepath .= "/" if ($archivepath !~ /\/$/); - die "Failed to open $logfile" if !-r $logfile; + $self->log_and_exit("Failed to open $logfile") if !-r $logfile; my @now = localtime(); my $archname = "$archivepath/nagios-" . $self->time_to_date($self->{launch_time}) . "-$now[2].log"; @@ -371,27 +383,27 @@ sub run { my ($status, $list_sth) = $self->{cdb}->query(<<"EOQ"); SELECT `id`, `name`, `localhost` FROM `nagios_server` WHERE `ns_activate`=1 EOQ - die "Cannot read pollers list from database" if $status == -1; + $self->log_and_exit("Cannot read pollers list from database") if $status == -1; while (my $ns_server = $list_sth->fetchrow_hashref()) { my $sth; ($status, $sth) = $self->{csdb}->query(<<"EOQ"); SELECT `instance_name` FROM `instance` WHERE `instance_id` = '$ns_server->{id}' LIMIT 1 EOQ - die "Cannot read instance name from database" if $status == -1; + $self->log_and_exit("Cannot read instance name from database") if $status == -1; if (!$sth->rows()) { $status = $self->{csdb}->do(<<"EOQ"); INSERT INTO `instance` (`instance_id`, `instance_name`, `log_flag`) VALUES ('$ns_server->{id}', '$ns_server->{name}', '0') EOQ - die "Cannot save instance to database" if $status == -1; + $self->log_and_exit("Cannot save instance to database") if $status == -1; } else { $status = $self->{csdb}->do(<<"EOQ"); UPDATE `instance` SET `instance_name` = '$ns_server->{name}' WHERE `instance_id` = '$ns_server->{id}' LIMIT 1 EOQ - die "Cannot update instance from database" if $status == -1; + $self->log_and_exit("Cannot update instance from database") if $status == -1; } $self->{logger}->writeLogInfo("Poller: $ns_server->{name}"); if ($self->{opt_a}) { From 9963a0912ccf12d6de88cb58f94ddd9919ef6fcb Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 25 Nov 2013 11:20:33 +0100 Subject: [PATCH 159/458] + Add exclude user for postgres --- .../lib/perl/plugins/database/postgres/mode/querytime.pm | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/centreon/lib/perl/plugins/database/postgres/mode/querytime.pm b/centreon/lib/perl/plugins/database/postgres/mode/querytime.pm index ae91eb5d9c3..4d4513979cc 100644 --- a/centreon/lib/perl/plugins/database/postgres/mode/querytime.pm +++ b/centreon/lib/perl/plugins/database/postgres/mode/querytime.pm @@ -51,6 +51,7 @@ sub new { "warning:s" => { name => 'warning', }, "critical:s" => { name => 'critical', }, "exclude:s" => { name => 'exclude', }, + "exclude-user:s" => { name => 'exclude_user', }, }); return $self; @@ -105,6 +106,9 @@ ORDER BY query_start, procpid DESC if (defined($self->{option_results}->{exclude}) && $row->{datname} !~ /$self->{option_results}->{exclude}/) { next; } + if (defined($self->{option_results}->{exclude_user}) && $row->{usename} !~ /$self->{option_results}->{exclude_user}/) { + next; + } my $exit_code = $self->{perfdata}->threshold_check(value => $row->{seconds}, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); if ($self->{output}->is_status(value => $exit_code, compare => 'ok', litteral => 1)) { @@ -154,6 +158,10 @@ Threshold critical in seconds. Filter databases. +=item B<--exclude-user> + +Filter users. + =back =cut From 1c4147c6d01893ac691d062582654bc91e740e53 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 25 Nov 2013 14:03:20 +0100 Subject: [PATCH 160/458] + Fix an output for snmp traffic standard --- centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index 65c743d52f3..b36c3951a47 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -155,7 +155,7 @@ sub run { my $old_timestamp; if (!defined($self->{option_results}->{interface}) || defined($self->{option_results}->{use_regexp})) { $self->{output}->output_add(severity => 'OK', - short_msg => 'All traffic are ok.'); + short_msg => 'All traffic are ok'); } foreach (sort @{$self->{interface_id_selected}}) { @@ -184,6 +184,11 @@ sub run { $self->{output}->output_add(severity => 'CRITICAL', short_msg => "Interface '" . $display_value . "' is not ready: " . $operstatus[$result->{$oid_operstatus . "." . $_} - 1]); } else { + # Avoid getting "buffer creation..." alone + if (defined($self->{option_results}->{interface}) && !defined($self->{option_results}->{use_regexp})) { + $self->{output}->output_add(severity => 'OK', + short_msg => "Interface '" . $display_value . "' is not up (normal state)"); + } $self->{output}->output_add(long_msg => "Skip interface '" . $display_value . "'."); } next; From 224c6bb94934266eaf07d76ba3f17fa07d565153 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 25 Nov 2013 14:21:14 +0100 Subject: [PATCH 161/458] + Add adminstatus in interface list --- .../plugins/snmp_standard/mode/listinterfaces.pm | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm b/centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm index b46fa88bc30..535bca562bb 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/listinterfaces.pm @@ -49,6 +49,7 @@ my %oids_iftable = ( 'ifname' => '.1.3.6.1.2.1.31.1.1.1.1' ); +my $oid_adminstatus = '.1.3.6.1.2.1.2.2.1.7'; my $oid_operstatus = '.1.3.6.1.2.1.2.2.1.8'; my $oid_speed32 = '.1.3.6.1.2.1.2.2.1.5'; # in b/s my $oid_speed64 = '.1.3.6.1.2.1.31.1.1.1.15'; @@ -65,6 +66,7 @@ sub new { "interface:s" => { name => 'interface' }, "speed:s" => { name => 'speed' }, "filter-status:s" => { name => 'filter_status' }, + "use-adminstatus" => { name => 'use_adminstatus' }, "regexp" => { name => 'use_regexp' }, "regexp-isensitive" => { name => 'use_regexpi' }, "oid-filter:s" => { name => 'oid_filter', default => 'ifname'}, @@ -114,6 +116,9 @@ sub run { if (defined($self->{option_results}->{filter_status}) && $operstatus[$result->{$oid_operstatus . "." . $_} - 1] !~ /$self->{option_results}->{filter_status}/i) { next; } + if (defined($self->{option_results}->{use_adminstatus}) && $operstatus[$result->{$oid_adminstatus . "." . $_} - 1] ne 'up') { + next; + } $interfaces_display .= $interfaces_display_append . "name = $display_value [speed = $interface_speed, status = " . $operstatus[$result->{$oid_operstatus . "." . $_} - 1] . ", id = $_]"; $interfaces_display_append = ', '; @@ -128,7 +133,7 @@ sub run { sub get_additional_information { my ($self, %options) = @_; - my $oids = [$oid_operstatus, $oid_speed32]; + my $oids = [$oid_adminstatus, $oid_operstatus, $oid_speed32]; if (!$self->{snmp}->is_snmpv1()) { push @$oids, $oid_speed64; } @@ -232,7 +237,10 @@ sub disco_show { if (defined($self->{option_results}->{filter_status}) && $operstatus[$result->{$oid_operstatus . "." . $_} - 1] !~ /$self->{option_results}->{filter_status}/i) { next; } - + if (defined($self->{option_results}->{use_adminstatus}) && $operstatus[$result->{$oid_adminstatus . "." . $_} - 1] ne 'up') { + next; + } + $self->{output}->add_disco_entry(name => $display_value, total => $interface_speed, status => $result->{$oid_operstatus . "." . $_}, @@ -272,6 +280,10 @@ Set interface speed (in Mb). Display interfaces matching the filter (example: 'up'). +=item B<--use-adminstatus> + +Display interfaces with AdminStatus 'up'. + =item B<--oid-filter> Choose OID used to filter interface (default: ifName) (values: ifDesc, ifAlias, ifName). From 343238ea0395133ef7f6b10bd2eb2a504656677a Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 25 Nov 2013 14:55:30 +0100 Subject: [PATCH 162/458] + Add mode standard 'spanning-tree' mode --- .../perl/plugins/network/cisco/3750/plugin.pm | 1 + .../snmp_standard/mode/spanningtree.pm | 139 ++++++++++++++++++ 2 files changed, 140 insertions(+) create mode 100644 centreon/lib/perl/plugins/snmp_standard/mode/spanningtree.pm diff --git a/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm b/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm index 8e08577fb41..3d9eae31e9b 100644 --- a/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm +++ b/centreon/lib/perl/plugins/network/cisco/3750/plugin.pm @@ -52,6 +52,7 @@ sub new { 'list-interfaces' => 'snmp_standard::mode::listinterfaces', 'memory' => 'network::cisco::common::mode::memory', 'packet-errors' => 'snmp_standard::mode::packeterrors', + 'spanning-tree' => 'snmp_standard::mode::spanningtree', 'stack' => 'network::cisco::common::mode::stack', 'traffic' => 'snmp_standard::mode::traffic', ); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/spanningtree.pm b/centreon/lib/perl/plugins/snmp_standard/mode/spanningtree.pm new file mode 100644 index 00000000000..0c15842e09f --- /dev/null +++ b/centreon/lib/perl/plugins/snmp_standard/mode/spanningtree.pm @@ -0,0 +1,139 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package snmp_standard::mode::spanningtree; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %states = ( + 1 => ['disabled', 'OK'], + 2 => ['blocking', 'CRITICAL'], + 3 => ['listening', 'OK'], + 4 => ['learning', 'OK'], + 5 => ['forwarding', 'OK'], + 6 => ['broken', 'CRITICAL'], +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_dot1dStpPortEnable = '.1.3.6.1.2.1.17.2.15.1.4'; + my $oid_dot1dStpPortState = '.1.3.6.1.2.1.17.2.15.1.3'; + my $oid_dot1dBasePortIfIndex = '.1.3.6.1.2.1.17.1.4.1.2'; + my $oid_ifDesc = '.1.3.6.1.2.1.2.2.1.2'; + my $result = $self->{snmp}->get_table(oid => $oid_dot1dStpPortEnable, nothing_quit => 1); + + foreach my $oid (keys %$result) { + $oid =~ /\.([0-9]+)$/; + my $instance = $1; + + # '2' => disabled, we skip + if ($result->{$oid} == 2) { + $self->{output}->output_add(long_msg => sprintf("Skipping interface '%d': Stp port disabled", $instance)); + next; + } + + $self->{snmp}->load(oids => [$oid_dot1dStpPortState . "." . $instance, $oid_dot1dBasePortIfIndex . "." . $instance]); + } + + $result = $self->{snmp}->get_leef(nothing_quit => 1); + $self->{output}->output_add(severity => 'OK', + short_msg => 'Spanning Tree is ok on all interfaces'); + # Get description + foreach my $oid (keys %$result) { + next if ($oid !~ /^$oid_dot1dBasePortIfIndex/); + $self->{snmp}->load(oids => [$oid_ifDesc . "." . $result->{$oid}]); + } + my $result_desc = $self->{snmp}->get_leef(); + + # Parsing ports + foreach my $oid (keys %$result) { + next if ($oid !~ /^$oid_dot1dStpPortState/); + $oid =~ /\.([0-9]+)$/; + my $instance = $1; + + my $stp_state = $result->{$oid}; + my $descr = $result_desc->{$oid_ifDesc . '.' . $result->{$oid_dot1dBasePortIfIndex . '.' . $instance}}; + + $self->{output}->output_add(long_msg => sprintf("Spanning Tree interface '%s' state is %s", $descr, + ${$states{$stp_state}}[0])); + if (${$states{$stp_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states{$stp_state}}[1], + short_msg => sprintf("Spanning Tree interface '%s' state is %s", $descr, + ${$states{$stp_state}}[0])); + } + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check Spanning-Tree current state of ports (BRIDGE-MIB). + +=over 8 + +=back + +=cut + \ No newline at end of file From 674f6479720707afb6847fea4135dac9502f6d76 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 25 Nov 2013 16:01:00 +0100 Subject: [PATCH 163/458] + Fix round number --- .../perl/plugins/os/windows/mode/memory.pm | 2 +- .../perl/plugins/os/windows/mode/service.pm | 189 ++++++++++++++++++ .../lib/perl/plugins/os/windows/mode/swap.pm | 2 +- .../lib/perl/plugins/os/windows/plugin.pm | 1 + 4 files changed, 192 insertions(+), 2 deletions(-) create mode 100644 centreon/lib/perl/plugins/os/windows/mode/service.pm diff --git a/centreon/lib/perl/plugins/os/windows/mode/memory.pm b/centreon/lib/perl/plugins/os/windows/mode/memory.pm index dae7d7a915c..40334d2a154 100644 --- a/centreon/lib/perl/plugins/os/windows/mode/memory.pm +++ b/centreon/lib/perl/plugins/os/windows/mode/memory.pm @@ -112,7 +112,7 @@ sub run { my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $total_size); $self->{output}->output_add(severity => $exit, - short_msg => sprintf("RAM Total: %s Used: %s (%.2f%%) Free: %s (%d%%)", + short_msg => sprintf("RAM Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", $total_value . " " . $total_unit, $physical_used_value . " " . $physical_used_unit, $prct_used, $physical_free_value . " " . $physical_free_unit, 100 - $prct_used)); diff --git a/centreon/lib/perl/plugins/os/windows/mode/service.pm b/centreon/lib/perl/plugins/os/windows/mode/service.pm new file mode 100644 index 00000000000..fa54b988af0 --- /dev/null +++ b/centreon/lib/perl/plugins/os/windows/mode/service.pm @@ -0,0 +1,189 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package os::windows::mode::service; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %map_installed_state = ( + 1 => 'uninstalled', + 2 => 'install-pending', + 3 => 'uninstall-pending', + 4 => 'installed' +); +my %map_operating_state = ( + 1 => 'active', + 2 => 'continue-pending', + 3 => 'pause-pending', + 4 => 'paused' +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + "service:s@" => { name => 'service', }, + "regexp" => { name => 'use_regexp', }, + "state:s" => { name => 'state', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (!defined($self->{option_results}->{service})) { + $self->{output}->add_option_msg(short_msg => "Need to specify at least one '--service' option."); + $self->{output}->option_exit(); + } + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_svSvcEntry = '.1.3.6.1.4.1.77.1.2.3.1'; + my $oid_svSvcName = '.1.3.6.1.4.1.77.1.2.3.1.1'; + my $oid_svSvcInstalledState = '.1.3.6.1.4.1.77.1.2.3.1.2'; + my $oid_svSvcOperatingState = '.1.3.6.1.4.1.77.1.2.3.1.3'; + my $result = $self->{snmp}->get_table(oid => $oid_svSvcEntry); + + my %services_match = (); + $self->{output}->output_add(severity => 'OK', + short_msg => 'All service states is ok'); + foreach my $oid ($self->{snmp}->oid_lex_sort(keys %$result)) { + next if ($oid !~ /^$oid_svSvcName/); + $oid =~ /^$oid_svSvcName\.([0-9]+)$/; + my $instance = $1; + + my $svc_name = $self->{output}->to_utf8($result->{$oid}); + my $svc_installed_state = $result->{$oid_svSvcInstalledState . '.' . $instance}; + my $svc_operating_state = $result->{$oid_svSvcOperatingState . '.' . $instance}; + + for (my $i = 0; $i <= scalar(@{$self->{option_results}->{service}}); $i++) { + my $filter = ${$self->{option_results}->{service}}[$i]; + if (defined($self->{option_results}->{use_regexp}) && $svc_name =~ /$filter/) { + $services_match{$i}{$svc_name}{operating_state} = $svc_operating_state; + $services_match{$i}{$svc_name}{installed_state} = $svc_installed_state; + } elsif ($svc_name eq $filter) { + $services_match{$i}{$svc_name}{operating_state} = $svc_operating_state; + $services_match{$i}{$svc_name}{installed_state} = $svc_installed_state; + } + } + } + + for (my $i = 0; $i <= scalar(@{$self->{option_results}->{service}}); $i++) { + $numbers = 0; + foreach my $svc_name (keys %{$services_match{$i}}) { + my $operating_state = $services_match{$i}{$svc_name}{operating_state}; + my $installed_state = $services_match{$i}{$svc_name}{installed_state}; + $self->{output}->output_add(long_msg => sprintf("Service '%s' match (pattern: '%s') [operating state = %s, installed state = %s]", + $svc_name, ${$self->{option_results}->{service}}[$i], + $map_operating_state{$operating_state}, $map_installed_state{$installed_state})); + if (defined($self->{option_results}->{state}) && $map_operating_state{$operating_state} !~ /$self->{option_results}->{state}/) { + delete $services_match{$i}{$svc_name}; + next; + } + $numbers++; + } + + my $exit = $self->{perfdata}->threshold_check(value => $numbers, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(long_msg => sprintf("Service pattern '%s': service list %s", + ${$self->{option_results}->{service}}[$i], + join(', ', keys %{$services_match{$i}))); + if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1) { + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Service pattern '%s'"); + } + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check Windows Services in SNMP + +=over 8 + +=item B<--warning> + +Threshold warning. + +=item B<--critical> + +Threshold critical. + +=item B<--service> + +Services to check. (can set multiple times) + +=item B<--regexp> + +Allows to use regexp to filter services. + +=item B<--state> + +Service state. (Regexp allowed) + +=back + +=cut diff --git a/centreon/lib/perl/plugins/os/windows/mode/swap.pm b/centreon/lib/perl/plugins/os/windows/mode/swap.pm index 4714a90ea05..49a3e6ea121 100644 --- a/centreon/lib/perl/plugins/os/windows/mode/swap.pm +++ b/centreon/lib/perl/plugins/os/windows/mode/swap.pm @@ -112,7 +112,7 @@ sub run { my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $total_size); $self->{output}->output_add(severity => $exit, - short_msg => sprintf("Swap Total: %s Used: %s (%.2f%%) Free: %s (%d%%)", + short_msg => sprintf("Swap Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", $total_value . " " . $total_unit, $swap_used_value . " " . $swap_used_unit, $prct_used, $swap_free_value . " " . $swap_free_unit, 100 - $prct_used)); diff --git a/centreon/lib/perl/plugins/os/windows/plugin.pm b/centreon/lib/perl/plugins/os/windows/plugin.pm index 3f65a0001d6..178a4b3d39b 100644 --- a/centreon/lib/perl/plugins/os/windows/plugin.pm +++ b/centreon/lib/perl/plugins/os/windows/plugin.pm @@ -52,6 +52,7 @@ sub new { 'memory' => 'os::windows::mode::memory', 'packet-errors' => 'snmp_standard::mode::packeterrors', 'processcount' => 'snmp_standard::mode::processcount', + 'service' => 'os::windows::mode::service', 'storage' => 'snmp_standard::mode::storage', 'swap' => 'os::windows::mode::swap', 'traffic' => 'snmp_standard::mode::traffic', From d7a014978d57d61471d140655eb11ec47fefa1b1 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Mon, 25 Nov 2013 16:20:56 +0100 Subject: [PATCH 164/458] + Add windows mode for 'service' --- .../perl/plugins/os/windows/mode/service.pm | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/centreon/lib/perl/plugins/os/windows/mode/service.pm b/centreon/lib/perl/plugins/os/windows/mode/service.pm index fa54b988af0..06f2bf91d22 100644 --- a/centreon/lib/perl/plugins/os/windows/mode/service.pm +++ b/centreon/lib/perl/plugins/os/windows/mode/service.pm @@ -106,14 +106,14 @@ sub run { short_msg => 'All service states is ok'); foreach my $oid ($self->{snmp}->oid_lex_sort(keys %$result)) { next if ($oid !~ /^$oid_svSvcName/); - $oid =~ /^$oid_svSvcName\.([0-9]+)$/; + $oid =~ /^$oid_svSvcName\.([0-9\.]+)$/; my $instance = $1; - + my $svc_name = $self->{output}->to_utf8($result->{$oid}); my $svc_installed_state = $result->{$oid_svSvcInstalledState . '.' . $instance}; my $svc_operating_state = $result->{$oid_svSvcOperatingState . '.' . $instance}; - for (my $i = 0; $i <= scalar(@{$self->{option_results}->{service}}); $i++) { + for (my $i = 0; $i < scalar(@{$self->{option_results}->{service}}); $i++) { my $filter = ${$self->{option_results}->{service}}[$i]; if (defined($self->{option_results}->{use_regexp}) && $svc_name =~ /$filter/) { $services_match{$i}{$svc_name}{operating_state} = $svc_operating_state; @@ -125,8 +125,9 @@ sub run { } } - for (my $i = 0; $i <= scalar(@{$self->{option_results}->{service}}); $i++) { - $numbers = 0; + for (my $i = 0; $i < scalar(@{$self->{option_results}->{service}}); $i++) { + my $numbers = 0; + my %svc_name_state_wrong = (); foreach my $svc_name (keys %{$services_match{$i}}) { my $operating_state = $services_match{$i}{$svc_name}{operating_state}; my $installed_state = $services_match{$i}{$svc_name}{installed_state}; @@ -135,6 +136,7 @@ sub run { $map_operating_state{$operating_state}, $map_installed_state{$installed_state})); if (defined($self->{option_results}->{state}) && $map_operating_state{$operating_state} !~ /$self->{option_results}->{state}/) { delete $services_match{$i}{$svc_name}; + $svc_name_state_wrong{$svc_name} = $operating_state; next; } $numbers++; @@ -143,10 +145,16 @@ sub run { my $exit = $self->{perfdata}->threshold_check(value => $numbers, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); $self->{output}->output_add(long_msg => sprintf("Service pattern '%s': service list %s", ${$self->{option_results}->{service}}[$i], - join(', ', keys %{$services_match{$i}))); - if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1) { - $self->{output}->output_add(severity => $exit, - short_msg => sprintf("Service pattern '%s'"); + join(', ', keys %{$services_match{$i}}))); + if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) { + if (scalar(keys %svc_name_state_wrong) > 0) { + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Service pattern '%s' problem: %s [following services match but has the wrong state]", + ${$self->{option_results}->{service}}[$i], join(', ', keys %svc_name_state_wrong))); + } else { + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Service problem '%s'", ${$self->{option_results}->{service}}[$i])); + } } } From b311d7044d6ace4d3d7dc2d626d18247a2bab98a Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 26 Nov 2013 16:21:40 +0100 Subject: [PATCH 165/458] + Add plugin netapp :) --- .../plugins/snmp_standard/mode/storage.pm | 2 +- .../plugins/snmp_standard/mode/traffic.pm | 2 +- .../plugins/storage/netapp/mode/cpuload.pm | 114 ++++++ .../plugins/storage/netapp/mode/diskfailed.pm | 99 +++++ .../perl/plugins/storage/netapp/mode/fan.pm | 95 +++++ .../plugins/storage/netapp/mode/filesys.pm | 267 +++++++++++++ .../storage/netapp/mode/globalstatus.pm | 100 +++++ .../storage/netapp/mode/listfilesys.pm | 202 ++++++++++ .../storage/netapp/mode/ndmpsessions.pm | 114 ++++++ .../perl/plugins/storage/netapp/mode/nvram.pm | 99 +++++ .../perl/plugins/storage/netapp/mode/psu.pm | 95 +++++ .../perl/plugins/storage/netapp/mode/shelf.pm | 378 ++++++++++++++++++ .../storage/netapp/mode/snapmirrorlag.pm | 182 +++++++++ .../storage/netapp/mode/temperature.pm | 93 +++++ .../storage/netapp/mode/volumeoptions.pm | 184 +++++++++ .../lib/perl/plugins/storage/netapp/plugin.pm | 76 ++++ 16 files changed, 2100 insertions(+), 2 deletions(-) create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/cpuload.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/diskfailed.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/fan.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/filesys.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/globalstatus.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/listfilesys.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/ndmpsessions.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/nvram.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/psu.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/shelf.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/snapmirrorlag.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/temperature.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/volumeoptions.pm create mode 100644 centreon/lib/perl/plugins/storage/netapp/plugin.pm diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm index ba1230e7396..fce10cd0339 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm @@ -129,7 +129,7 @@ sub run { my $num_disk_check = 0; foreach (sort @{$self->{storage_id_selected}}) { - # Skipped disks + # Skipped disks my $storage_type = $self->{statefile_cache}->get(name => "type_" . $_); next if (!defined($storage_type) || ($storage_type ne $oid_hrStorageFixedDisk && $storage_type ne $oid_hrStorageNetworkDisk)); diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm index b36c3951a47..eeb7751f889 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/traffic.pm @@ -144,7 +144,7 @@ sub run { } if (!$self->{snmp}->is_snmpv1()) { $self->{snmp}->load(oids => [$oid_in64 . "." . $_, $oid_out64 . "." . $_]); - if (!defined($self->{option_results}->{speed}) || $self->{option_results}->{speed} eq '') { + if (!defined($self->{option_results}->{speed}) || $self->{option_results}->{speed} eq '') { $self->{snmp}->load(oids => [$oid_speed64 . "." . $_]); } } diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/cpuload.pm b/centreon/lib/perl/plugins/storage/netapp/mode/cpuload.pm new file mode 100644 index 00000000000..7400de6e22d --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/cpuload.pm @@ -0,0 +1,114 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::cpuload; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_cpuBusyTimePerCent = '.1.3.6.1.4.1.789.1.2.1.3.0'; + my $result = $self->{snmp}->get_leef(oids => [$oid_cpuBusyTimePerCent], nothing_quit => 1); + + my $exit = $self->{perfdata}->threshold_check(value => $result->{$oid_cpuBusyTimePerCent}, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("CPU Usage %d %%", $result->{$oid_cpuBusyTimePerCent})); + $self->{output}->perfdata_add(label => 'cpuload', unit => '%', + value => sprintf("%d", $result->{$oid_cpuBusyTimePerCent}), + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0, max => 100); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check CPU usage. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/diskfailed.pm b/centreon/lib/perl/plugins/storage/netapp/mode/diskfailed.pm new file mode 100644 index 00000000000..8ba9e3b7450 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/diskfailed.pm @@ -0,0 +1,99 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::diskfailed; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_diskFailedCount = '.1.3.6.1.4.1.789.1.6.4.7.0'; + my $oid_diskFailedMessage = '.1.3.6.1.4.1.789.1.6.4.10.0'; + my $result = $self->{snmp}->get_leef(oids => [$oid_diskFailedCount], nothing_quit => 1); + + $self->{output}->output_add(severity => 'OK', + short_msg => 'Disks are ok.'); + if ($result->{$oid_diskFailedCount} != 0) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => sprintf("'%d' fans are failed [message: %s].", + $result->{$oid_diskFailedCount}, $result->{$oid_diskFailedMessage})); + } + + $self->{output}->perfdata_add(label => 'failed', + value => $result->{$oid_diskFailedCount}, + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check the current number of disk broken. + +=over 8 + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/fan.pm b/centreon/lib/perl/plugins/storage/netapp/mode/fan.pm new file mode 100644 index 00000000000..8d54723d8f2 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/fan.pm @@ -0,0 +1,95 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::fan; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_envFailedFanCount = '.1.3.6.1.4.1.789.1.2.4.2.0'; + my $oid_envFailedFanMessage = '.1.3.6.1.4.1.789.1.2.4.3.0'; + my $result = $self->{snmp}->get_leef(oids => [$oid_envFailedFanCount, $oid_envFailedFanMessage], nothing_quit => 1); + + $self->{output}->output_add(severity => 'OK', + short_msg => 'Fans are ok.'); + if ($result->{$oid_envFailedFanCount} != 0) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => sprintf("'%d' fans are failed [message: %s].", + $result->{$oid_envFailedFanCount}, $result->{$oid_envFailedFanMessage})); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check if fans are failed (not operating within the recommended RPM range). + +=over 8 + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/filesys.pm b/centreon/lib/perl/plugins/storage/netapp/mode/filesys.pm new file mode 100644 index 00000000000..68666e9aec3 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/filesys.pm @@ -0,0 +1,267 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::filesys; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my $oid_dfFileSys = '.1.3.6.1.4.1.789.1.5.4.1.2'; +my $oid_dfType = '.1.3.6.1.4.1.789.1.5.4.1.23'; +my $oid_dfKBytesTotal = '.1.3.6.1.4.1.789.1.5.4.1.3'; +my $oid_dfKBytesUsed = '.1.3.6.1.4.1.789.1.5.4.1.4'; +my $oid_dfKBytesAvail = '.1.3.6.1.4.1.789.1.5.4.1.5'; +my $oid_df64TotalKBytes = '.1.3.6.1.4.1.789.1.5.4.1.29'; +my $oid_df64UsedKBytes = '.1.3.6.1.4.1.789.1.5.4.1.30'; +my $oid_df64AvailKBytes = '.1.3.6.1.4.1.789.1.5.4.1.31'; +my $oid_dfDedupeSavedPercent = '.1.3.6.1.4.1.789.1.5.4.1.40'; +my $oid_dfCompressSavedPercent = '.1.3.6.1.4.1.789.1.5.4.1.38'; + +my %map_types = ( + 1 => 'traditionalVolume', + 2 => 'flexibleVolume', + 3 => 'aggregate', + 4 => 'stripedAggregate', + 5 => 'stripedVolume' +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + "units:s" => { name => 'units', default => '%' }, + "free" => { name => 'free' }, + "name:s" => { name => 'name' }, + "regexp" => { name => 'use_regexp' }, + "type:s" => { name => 'type' }, + }); + $self->{filesys_id_selected} = []; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub manage_selection { + my ($self, %options) = @_; + + $self->{result_names} = $self->{snmp}->get_table(oid => $oid_dfFileSys, nothing_quit => 1); + $self->{result_types} = $self->{snmp}->get_table(oid => $oid_dfType, nothing_quit => 1); + foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{result_names}})) { + next if ($oid !~ /\.([0-9]+)$/); + my $instance = $1; + my $type = $map_types{$self->{result_types}->{$oid_dfType . '.' . $instance}}; + + # Get all without a name + if (!defined($self->{option_results}->{name})) { + push @{$self->{filesys_id_selected}}, $instance; + next; + } + + if (!defined($self->{option_results}->{use_regexp}) && $self->{result_names}->{$oid} eq $self->{option_results}->{name}) { + next if (defined($self->{option_results}->{type}) && $type !~ /$self->{option_results}->{type}/i); + push @{$self->{filesys_id_selected}}, $instance; + } + if (defined($self->{option_results}->{use_regexp}) && $self->{result_names}->{$oid} =~ /$self->{option_results}->{name}/) { + next if (defined($self->{option_results}->{type}) && $type !~ /$self->{option_results}->{type}/i); + push @{$self->{filesys_id_selected}}, $instance; + } + } + + if (scalar(@{$self->{filesys_id_selected}}) <= 0) { + $self->{output}->add_option_msg(short_msg => "No filesys found for name '" . $self->{option_results}->{name} . "' (can be the 'type' filter also)."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->manage_selection(); + if (!$self->{snmp}->is_snmpv1()) { + $self->{snmp}->load(oids => [$oid_df64TotalKBytes, $oid_df64UsedKBytes, $oid_df64AvailKBytes], instances => $self->{filesys_id_selected}); + } + $self->{snmp}->load(oids => [$oid_dfKBytesTotal, $oid_dfKBytesUsed, $oid_dfKBytesAvail, $oid_dfDedupeSavedPercent, $oid_dfCompressSavedPercent], instances => $self->{filesys_id_selected}); + my $result = $self->{snmp}->get_leef(); + + if (!defined($self->{option_results}->{name}) || defined($self->{option_results}->{use_regexp})) { + $self->{output}->output_add(severity => 'OK', + short_msg => 'All filesys are ok.'); + } + + foreach my $instance (sort @{$self->{filesys_id_selected}}) { + my $name = $self->{result_names}->{$oid_dfFileSys . '.' . $instance}; + my $type = $self->{result_types}->{$oid_dfType . '.' . $instance}; + my ($total_size, $total_used, $total_free) = ($result->{$oid_dfKBytesTotal . '.' . $instance} * 1024, $result->{$oid_dfKBytesUsed . '.' . $instance} * 1024, $result->{$oid_dfKBytesAvail . '.' . $instance} * 1024); + if (defined($result->{$oid_df64TotalKBytes . '.' . $instance}) && $result->{$oid_df64TotalKBytes . '.' . $instance} != 0) { + ($total_size, $total_used, $total_free) = ($result->{$oid_df64TotalKBytes . '.' . $instance} * 1024, $result->{$oid_df64UsedKBytes . '.' . $instance} * 1024, $result->{$oid_df64AvailKBytes . '.' . $instance} * 1024); + } + + if ($total_size == 0) { + $self->{output}->output_add(long_msg => sprintf("Skipping filesys '%s' (total size is 0)", $name)); + if (defined($self->{option_results}->{name}) && !defined($self->{option_results}->{use_regexp})) { + $self->{output}->output_add(severity => 'UNKNOWN', + short_msg => sprintf("Skipping filesys '%s' (total size is 0)", $name)); + } + next; + } + + ####### + # Calc + ####### + my $prct_used = $total_used * 100 / $total_size; + my $prct_free = 100 - $prct_used; + my ($exit, $threshold_value); + + $threshold_value = $total_used; + $threshold_value = $total_free if (defined($self->{option_results}->{free})); + if ($self->{option_results}->{units} eq '%') { + $threshold_value = $prct_used; + $threshold_value = $prct_free if (defined($self->{option_results}->{free})); + } + $exit = $self->{perfdata}->threshold_check(value => $threshold_value, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + + my ($total_size_value, $total_size_unit) = $self->{perfdata}->change_bytes(value => $total_size); + my ($total_used_value, $total_used_unit) = $self->{perfdata}->change_bytes(value => $total_used); + my ($total_free_value, $total_free_unit) = $self->{perfdata}->change_bytes(value => ($total_size - $total_used)); + + $self->{output}->output_add(long_msg => sprintf("Filesys '%s' Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%) [type: %s]", $name, + $total_size_value . " " . $total_size_unit, + $total_used_value . " " . $total_used_unit, $prct_used, + $total_free_value . " " . $total_free_unit, $prct_free, $map_types{$type})); + if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1) || (defined($self->{option_results}->{name}) && !defined($self->{option_results}->{use_regexp}))) { + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Filesys '%s' Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", $name, + $total_size_value . " " . $total_size_unit, + $total_used_value . " " . $total_used_unit, $prct_used, + $total_free_value . " " . $total_free_unit, $prct_free)); + } + + my $label = 'used'; + my $value_perf = $total_used; + if (defined($self->{option_results}->{free})) { + $label = 'free'; + $value_perf = $total_free; + } + my $extra_label = ''; + $extra_label = '_' . $name if (!defined($self->{option_results}->{name}) || defined($self->{option_results}->{use_regexp})); + my %total_options = (); + $total_options{total} = $total_size if ($self->{option_results}->{units} eq '%'); + $self->{output}->perfdata_add(label => $label . $extra_label, unit => 'o', + value => $value_perf, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', %total_options), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', %total_options), + min => 0, max => $total_size); + + if (defined($result->{$oid_dfDedupeSavedPercent . '.' . $instance})) { + $self->{output}->perfdata_add(label => 'dedupsaved' . $extra_label, unit => '%', + value => $result->{$oid_dfDedupeSavedPercent . '.' . $instance}, + min => 0, max => 100); + } + if (defined($result->{$oid_dfCompressSavedPercent . '.' . $instance})) { + $self->{output}->perfdata_add(label => 'compresssaved' . $extra_label, unit => '%', + value => $result->{$oid_dfCompressSavedPercent . '.' . $instance}, + min => 0, max => 100); + } + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check filesystem usage (volumes and aggregates also). + +=over 8 + +=item B<--warning> + +Threshold warning. + +=item B<--critical> + +Threshold critical. + +=item B<--units> + +Units of thresholds (Default: '%') ('%', 'B'). + +=item B<--free> + +Thresholds are on free space left. + +=item B<--name> + +Set the filesystem name. + +=item B<--regexp> + +Allows to use regexp to filter filesystem name (with option --name). + +=item B<--type> + +Filter filesystem type (a regexp. Example: 'flexibleVolume|aggregate'). + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/globalstatus.pm b/centreon/lib/perl/plugins/storage/netapp/mode/globalstatus.pm new file mode 100644 index 00000000000..48e093ec567 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/globalstatus.pm @@ -0,0 +1,100 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::globalstatus; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %states = ( + 1 => ['other', 'WARNING'], + 2 => ['unknown', 'UNKNOWN'], + 3 => ['ok', 'OK'], + 4 => ['non critical', 'WARNING'], + 5 => ['critical', 'CRITICAL'], + 6 => ['nonRecoverable', 'WARNING'], +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_miscGlobalStatus = '.1.3.6.1.4.1.789.1.2.2.4.0'; + my $oid_miscGlobalStatusMessage = '.1.3.6.1.4.1.789.1.2.2.25.0'; + my $result = $self->{snmp}->get_leef(oids => [$oid_miscGlobalStatus, $oid_miscGlobalStatusMessage], nothing_quit => 1); + + $self->{output}->output_add(severity => ${$states{$result->{$oid_miscGlobalStatus}}}[1], + short_msg => sprintf("Overall global status is '%s' [message: '%s']", + ${$states{$result->{$oid_miscGlobalStatus}}}[0], $result->{$oid_miscGlobalStatusMessage})); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check the overall status of the appliance. + +=over 8 + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/listfilesys.pm b/centreon/lib/perl/plugins/storage/netapp/mode/listfilesys.pm new file mode 100644 index 00000000000..67a2955f99d --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/listfilesys.pm @@ -0,0 +1,202 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::listfilesys; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my $oid_dfFileSys = '.1.3.6.1.4.1.789.1.5.4.1.2'; +my $oid_dfType = '.1.3.6.1.4.1.789.1.5.4.1.23'; +my $oid_dfKBytesTotal = '.1.3.6.1.4.1.789.1.5.4.1.3'; +my $oid_df64TotalKBytes = '.1.3.6.1.4.1.789.1.5.4.1.29'; + +my %map_types = ( + 1 => 'traditionalVolume', + 2 => 'flexibleVolume', + 3 => 'aggregate', + 4 => 'stripedAggregate', + 5 => 'stripedVolume' +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "name:s" => { name => 'name' }, + "regexp" => { name => 'use_regexp' }, + "type:s" => { name => 'type' }, + "skip-total-zero" => { name => 'skip_total_zero' }, + }); + $self->{filesys_id_selected} = []; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub manage_selection { + my ($self, %options) = @_; + + $self->{result_names} = $self->{snmp}->get_table(oid => $oid_dfFileSys, nothing_quit => 1); + $self->{result_types} = $self->{snmp}->get_table(oid => $oid_dfType, nothing_quit => 1); + foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{result_names}})) { + next if ($oid !~ /\.([0-9]+)$/); + my $instance = $1; + my $type = $map_types{$self->{result_types}->{$oid_dfType . '.' . $instance}}; + + # Get all without a name + if (!defined($self->{option_results}->{name})) { + push @{$self->{filesys_id_selected}}, $instance; + next; + } + + if (!defined($self->{option_results}->{use_regexp}) && $self->{result_names}->{$oid} eq $self->{option_results}->{name}) { + next if (defined($self->{option_results}->{type}) && $type !~ /$self->{option_results}->{type}/i); + push @{$self->{filesys_id_selected}}, $instance; + } + if (defined($self->{option_results}->{use_regexp}) && $self->{result_names}->{$oid} =~ /$self->{option_results}->{name}/) { + next if (defined($self->{option_results}->{type}) && $type !~ /$self->{option_results}->{type}/i); + push @{$self->{filesys_id_selected}}, $instance; + } + } +} + +sub get_additional_information { + my ($self, %options) = @_; + + return if (scalar(@{$self->{filesys_id_selected}}) <= 0); + $self->{snmp}->load(oids => [$oid_dfKBytesTotal], instances => $self->{filesys_id_selected}); + if (!$self->{snmp}->is_snmpv1()) { + $self->{snmp}->load(oids => [$oid_df64TotalKBytes], instances => $self->{filesys_id_selected}); + } + return $self->{snmp}->get_leef(); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->manage_selection(); + my $result = $self->get_additional_information(); + my $filesys_display = ''; + my $filesys_display_append = ''; + foreach my $instance (sort @{$self->{filesys_id_selected}}) { + my $name = $self->{result_names}->{$oid_dfFileSys . '.' . $instance}; + my $type = $self->{result_types}->{$oid_dfType . '.' . $instance}; + my $total_size = $result->{$oid_dfKBytesTotal . '.' . $instance} * 1024; + if (defined($result->{$oid_df64TotalKBytes . '.' . $instance}) && $result->{$oid_df64TotalKBytes . '.' . $instance} != 0) { + $total_size = $result->{$oid_df64TotalKBytes . '.' . $instance} * 1024; + } + next if (defined($self->{option_results}->{skip_total_zero}) && $total_size == 0); + + $filesys_display .= $filesys_display_append . "name = $name [total_size = $total_size B, type = " . $map_types{$type} . "]"; + $filesys_display_append = ', '; + } + + $self->{output}->output_add(severity => 'OK', + short_msg => 'List filesys: ' . $filesys_display); + $self->{output}->display(nolabel => 1); + $self->{output}->exit(); +} + +sub disco_format { + my ($self, %options) = @_; + + $self->{output}->add_disco_format(elements => ['name', 'total', 'type']); +} + +sub disco_show { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->manage_selection(); + my $result = $self->get_additional_information(); + foreach my $instance (sort @{$self->{filesys_id_selected}}) { + my $name = $self->{result_names}->{$oid_dfFileSys . '.' . $instance}; + my $type = $self->{result_types}->{$oid_dfType . '.' . $instance}; + my $total_size = $result->{$oid_dfKBytesTotal . '.' . $instance} * 1024; + if (defined($result->{$oid_df64TotalKBytes . '.' . $instance}) && $result->{$oid_df64TotalKBytes . '.' . $instance} != 0) { + $total_size = $result->{$oid_df64TotalKBytes . '.' . $instance} * 1024; + } + next if (defined($self->{option_results}->{skip_total_zero}) && $total_size == 0); + + $self->{output}->add_disco_entry(name => $name, + total => $total_size, + type => $map_types{$type}); + } +} + +1; + +__END__ + +=head1 MODE + +List filesystems (volumes and aggregates also). + +=over 8 + +=item B<--name> + +Set the filesystem name. + +=item B<--regexp> + +Allows to use regexp to filter filesystem name (with option --name). + +=item B<--type> + +Filter filesystem type (a regexp. Example: 'flexibleVolume|aggregate'). + +=item B<--skip-total-zero> + +Don't display filesys with total equals 0. + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/ndmpsessions.pm b/centreon/lib/perl/plugins/storage/netapp/mode/ndmpsessions.pm new file mode 100644 index 00000000000..43675b74082 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/ndmpsessions.pm @@ -0,0 +1,114 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::ndmpsessions; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_ndmpSessionOpened = '.1.3.6.1.4.1.789.1.10.2.0'; + my $result = $self->{snmp}->get_leef(oids => [$oid_ndmpSessionOpened], nothing_quit => 1); + + my $exit = $self->{perfdata}->threshold_check(value => $result->{$oid_ndmpSessionOpened}, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Current number of ndmp sessions opened: %d", $result->{$oid_ndmpSessionOpened})); + $self->{output}->perfdata_add(label => 'sessions', + value => $result->{$oid_ndmpSessionOpened}, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check current total of ndmp sessions opened. + +=over 8 + +=item B<--warning> + +Threshold warning. + +=item B<--critical> + +Threshold critical. + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/nvram.pm b/centreon/lib/perl/plugins/storage/netapp/mode/nvram.pm new file mode 100644 index 00000000000..7573371caa9 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/nvram.pm @@ -0,0 +1,99 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::nvram; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %states = ( + 1 => ['ok', 'OK'], + 2 => ['partially discharged', 'WARNING'], + 3 => ['fully discharged', 'CRITICAL'], + 4 => ['not present', 'CRITICAL'], + 5 => ['near end of life', 'WARNING'], + 6 => ['at end of life', 'CRITICAL'], + 7 => ['unknown', 'UNKNOWN'], +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_nvramBatteryStatus = '.1.3.6.1.4.1.789.1.2.5.1.0'; + my $result = $self->{snmp}->get_leef(oids => [$oid_nvramBatteryStatus], nothing_quit => 1); + + $self->{output}->output_add(severity => ${$states{$result->{$oid_nvramBatteryStatus}}}[1], + short_msg => sprintf("NVRAM Batteries status is '%s'.", ${$states{$result->{$oid_nvramBatteryStatus}}}[0])); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check current status of the NVRAM batteries. + +=over 8 + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/psu.pm b/centreon/lib/perl/plugins/storage/netapp/mode/psu.pm new file mode 100644 index 00000000000..bfe81b54b4c --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/psu.pm @@ -0,0 +1,95 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::psu; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_envFailedPowerSupplyCount = '.1.3.6.1.4.1.789.1.2.4.4.0'; + my $oid_envFailedPowerSupplyMessage = '.1.3.6.1.4.1.789.1.2.4.5.0'; + my $result = $self->{snmp}->get_leef(oids => [$oid_envFailedPowerSupplyCount, $oid_envFailedPowerSupplyMessage], nothing_quit => 1); + + $self->{output}->output_add(severity => 'OK', + short_msg => 'Power supplies are ok.'); + if ($result->{$oid_envFailedPowerSupplyCount} != 0) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => sprintf("'%d' power supplies are failed [message: %s].", + $result->{$oid_envFailedPowerSupplyCount}, $result->{$oid_envFailedPowerSupplyMessage})); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check if power supplies are failed (in degraded mode). + +=over 8 + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/shelf.pm b/centreon/lib/perl/plugins/storage/netapp/mode/shelf.pm new file mode 100644 index 00000000000..26ad3da5cb0 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/shelf.pm @@ -0,0 +1,378 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::shelf; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; +use centreon::plugins::misc; + +my %com_states = ( + 1 => ['initializing', 'WARNING'], + 2 => ['transitioning', 'WARNING'], + 3 => ['active', 'OK'], + 4 => ['inactive', 'CRITICAL'], + 5 => ['reconfiguring', 'WARNING'], + 6 => ['nonexistent', 'CRITICAL'], +); + +my $oid_enclNumber = '.1.3.6.1.4.1.789.1.21.1.1.0'; +my $oid_enclContactState = '.1.3.6.1.4.1.789.1.21.1.2.1.2'; +my $oid_enclChannelShelfAddr = '.1.3.6.1.4.1.789.1.21.1.2.1.3'; +my $oid_enclPowerSuppliesPresent = '.1.3.6.1.4.1.789.1.21.1.2.1.13'; +my $oid_enclPowerSuppliesFailed = '.1.3.6.1.4.1.789.1.21.1.2.1.15'; +my $oid_enclFansPresent = '.1.3.6.1.4.1.789.1.21.1.2.1.17'; +my $oid_enclFansFailed = '.1.3.6.1.4.1.789.1.21.1.2.1.18'; +my $oid_enclTempSensorsPresent = '.1.3.6.1.4.1.789.1.21.1.2.1.20'; +my $oid_enclTempSensorsOverTempFail = '.1.3.6.1.4.1.789.1.21.1.2.1.21'; +my $oid_enclTempSensorsOverTempWarn = '.1.3.6.1.4.1.789.1.21.1.2.1.22'; +my $oid_enclTempSensorsUnderTempFail = '.1.3.6.1.4.1.789.1.21.1.2.1.23'; +my $oid_enclTempSensorsUnderTempWarn = '.1.3.6.1.4.1.789.1.21.1.2.1.24'; +my $oid_enclTempSensorsCurrentTemp = '.1.3.6.1.4.1.789.1.21.1.2.1.25'; +my $oid_enclTempSensorsOverTempFailThr = '.1.3.6.1.4.1.789.1.21.1.2.1.26'; +my $oid_enclTempSensorsOverTempWarnThr = '.1.3.6.1.4.1.789.1.21.1.2.1.27'; +my $oid_enclTempSensorsUnderTempFailThr = '.1.3.6.1.4.1.789.1.21.1.2.1.28'; +my $oid_enclTempSensorsUnderTempWarnThr = '.1.3.6.1.4.1.789.1.21.1.2.1.29'; +my $oid_enclElectronicsPresent = '.1.3.6.1.4.1.789.1.21.1.2.1.31'; +my $oid_enclElectronicsFailed = '.1.3.6.1.4.1.789.1.21.1.2.1.33'; +my $oid_enclVoltSensorsPresent = '.1.3.6.1.4.1.789.1.21.1.2.1.35'; +my $oid_enclVoltSensorsOverVoltFail = '.1.3.6.1.4.1.789.1.21.1.2.1.36'; +my $oid_enclVoltSensorsOverVoltWarn = '.1.3.6.1.4.1.789.1.21.1.2.1.37'; +my $oid_enclVoltSensorsUnderVoltFail = '.1.3.6.1.4.1.789.1.21.1.2.1.38'; +my $oid_enclVoltSensorsUnderVoltWarn = '.1.3.6.1.4.1.789.1.21.1.2.1.39'; +my $oid_enclVoltSensorsCurrentVolt = '.1.3.6.1.4.1.789.1.21.1.2.1.40'; +my $oid_enclVoltSensorsOverVoltFailThr = '.1.3.6.1.4.1.789.1.21.1.2.1.41'; +my $oid_enclVoltSensorsOverVoltWarnThr = '.1.3.6.1.4.1.789.1.21.1.2.1.42'; +my $oid_enclVoltSensorsUnderVoltFailThr = '.1.3.6.1.4.1.789.1.21.1.2.1.43'; +my $oid_enclVoltSensorsUnderVoltWarnThr = '.1.3.6.1.4.1.789.1.21.1.2.1.44'; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $result = $self->{snmp}->get_leef(oids => [$oid_enclNumber], nothing_quit => 1); + $self->{snmp}->load(oids => [$oid_enclContactState, $oid_enclChannelShelfAddr, $oid_enclPowerSuppliesPresent, $oid_enclPowerSuppliesFailed, + $oid_enclFansPresent, $oid_enclFansFailed, $oid_enclTempSensorsPresent, $oid_enclTempSensorsOverTempFail, $oid_enclTempSensorsOverTempWarn, + $oid_enclTempSensorsUnderTempFail, $oid_enclTempSensorsUnderTempWarn, $oid_enclTempSensorsCurrentTemp, + $oid_enclTempSensorsOverTempFailThr, $oid_enclTempSensorsOverTempWarnThr, $oid_enclTempSensorsUnderTempFailThr, + $oid_enclTempSensorsUnderTempWarnThr, $oid_enclElectronicsPresent, $oid_enclElectronicsFailed, $oid_enclVoltSensorsPresent, + $oid_enclVoltSensorsOverVoltFail, $oid_enclVoltSensorsOverVoltWarn, $oid_enclVoltSensorsUnderVoltFail, $oid_enclVoltSensorsUnderVoltWarn, + $oid_enclVoltSensorsCurrentVolt, $oid_enclVoltSensorsOverVoltFailThr, $oid_enclVoltSensorsOverVoltWarnThr, $oid_enclVoltSensorsUnderVoltFailThr, + $oid_enclVoltSensorsUnderVoltWarnThr], + begin => 1, end => $result->{$oid_enclNumber}); + $self->{result} = $self->{snmp}->get_leef(); + + $self->{number_shelf} = $result->{$oid_enclNumber}; + $self->{components_fans} = 0; + $self->{components_psus} = 0; + $self->{components_temperatures} = 0; + $self->{components_electronics} = 0; + $self->{components_voltages} = 0; + + $self->check_communication(); + $self->check_fans(); + $self->check_psus(); + $self->check_temperatures(); + $self->check_electronics(); + $self->check_voltages(); + + $self->{output}->output_add(severity => 'OK', + short_msg => sprintf("All %d shelves [%d fans, %d power supplies, %d temperatures, %d voltages, %d electronics] are ok", + $self->{number_shelf}, + $self->{components_fans}, $self->{components_psus}, $self->{components_temperatures}, $self->{components_voltages}, $self->{components_electronics})); + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub check_communication { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking communications"); + + for (my $i = 1; $i <= $self->{number_shelf}; $i++) { + my $shelf_addr = $self->{result}->{$oid_enclChannelShelfAddr . '.' . $i}; + my $com_state = $self->{result}->{$oid_enclContactState . '.' . $i}; + + $self->{output}->output_add(long_msg => sprintf("Shelve '%s' communication state is '%s'", + $shelf_addr, ${$com_states{$com_state}}[0])); + if (${$com_states{$com_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$com_states{$com_state}}[0], + short_msg => sprintf("Shelve '%s' communication state is '%s'", + $shelf_addr, ${$com_states{$com_state}}[0])); + } + } +} + +sub check_fans { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking fans"); + + for (my $i = 1; $i <= $self->{number_shelf}; $i++) { + my $shelf_addr = $self->{result}->{$oid_enclChannelShelfAddr . '.' . $i}; + my $present = $self->{result}->{$oid_enclFansPresent . '.' . $i}; + my $failed = $self->{result}->{$oid_enclFansFailed . '.' . $i}; + + foreach my $num (split /,/, $present) { + $num = centreon::plugins::misc::trim($num); + next if ($num !~ /[0-9]/); + + $self->{components_fans}++; + if ($failed =~ /(^|,|\s)$num(,|\s|$)/) { + $self->{output}->output_add(severity => 'CRITICAL', + long_msg => sprintf("Shelve '%s' Fan '%s' is failed", + $shelf_addr, $num)); + } else { + $self->{output}->output_add(long_msg => sprintf("Shelve '%s' Fan '%s' is ok", + $shelf_addr, $num)); + } + } + } +} + +sub check_psus { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking power supplies"); + + for (my $i = 1; $i <= $self->{number_shelf}; $i++) { + my $shelf_addr = $self->{result}->{$oid_enclChannelShelfAddr . '.' . $i}; + my $present = $self->{result}->{$oid_enclPowerSuppliesPresent . '.' . $i}; + my $failed = $self->{result}->{$oid_enclPowerSuppliesFailed . '.' . $i}; + + foreach my $num (split /,/, $present) { + $num = centreon::plugins::misc::trim($num); + next if ($num !~ /[0-9]/); + + $self->{components_psus}++; + if ($failed =~ /(^|,|\s)$num(,|\s|$)/) { + $self->{output}->output_add(severity => 'CRITICAL', + long_msg => sprintf("Shelve '%s' PSU '%s' is failed", + $shelf_addr, $num)); + } else { + $self->{output}->output_add(long_msg => sprintf("Shelve '%s' PSU '%s' is ok", + $shelf_addr, $num)); + } + } + } +} + +sub check_electronics { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking electronics"); + + for (my $i = 1; $i <= $self->{number_shelf}; $i++) { + my $shelf_addr = $self->{result}->{$oid_enclChannelShelfAddr . '.' . $i}; + my $present = $self->{result}->{$oid_enclElectronicsPresent . '.' . $i}; + my $failed = $self->{result}->{$oid_enclElectronicsFailed . '.' . $i}; + + foreach my $num (split /,/, $present) { + $num = centreon::plugins::misc::trim($num); + next if ($num !~ /[0-9]/); + + $self->{components_electronics}++; + if ($failed =~ /(^|,|\s)$num(,|\s|$)/) { + $self->{output}->output_add(severity => 'CRITICAL', + long_msg => sprintf("Shelve '%s' electronics '%s' is failed", + $shelf_addr, $num)); + } else { + $self->{output}->output_add(long_msg => sprintf("Shelve '%s' electronics '%s' is ok", + $shelf_addr, $num)); + } + } + } +} + +sub check_voltages { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking voltages"); + for (my $i = 1; $i <= $self->{number_shelf}; $i++) { + my $shelf_addr = $self->{result}->{$oid_enclChannelShelfAddr . '.' . $i}; + my $present = $self->{result}->{$oid_enclVoltSensorsPresent . '.' . $i}; + my @current_volt = split /,/, $self->{result}->{$oid_enclVoltSensorsCurrentVolt . '.' . $i}; + + my $warn_under = $self->{result}->{$oid_enclVoltSensorsUnderVoltWarn . '.' . $i}; + my $crit_under = $self->{result}->{$oid_enclVoltSensorsUnderVoltFail . '.' . $i}; + my $warn_over = $self->{result}->{$oid_enclVoltSensorsOverVoltWarn . '.' . $i}; + my $crit_over = $self->{result}->{$oid_enclVoltSensorsOverVoltFail . '.' . $i}; + + my @warn_under_thr = split /,/, $self->{result}->{$oid_enclVoltSensorsUnderVoltWarnThr . '.' . $i}; + my @crit_under_thr = split /,/, $self->{result}->{$oid_enclVoltSensorsUnderVoltFailThr . '.' . $i}; + my @warn_over_thr = split /,/, $self->{result}->{$oid_enclVoltSensorsOverVoltWarnThr . '.' . $i}; + my @crit_over_thr = split /,/, $self->{result}->{$oid_enclVoltSensorsOverVoltFailThr . '.' . $i}; + + foreach my $num (split /,/, $present) { + $num = centreon::plugins::misc::trim($num); + next if ($num !~ /[0-9]/); + + my $wu_thr = (defined($warn_under_thr[$i - 1]) && $warn_under_thr[$i - 1] =~ /(^|\s)(-*[0-9]+)/) ? $2 : ''; + my $cu_thr = (defined($crit_under_thr[$i - 1]) && $crit_under_thr[$i - 1] =~ /(^|\s)(-*[0-9]+)/) ? $2 : ''; + my $wo_thr = (defined($warn_over_thr[$i - 1]) && $warn_over_thr[$i - 1] =~ /(^|\s)(-*[0-9]+)/) ? $2 : ''; + my $co_thr = (defined($crit_over_thr[$i - 1]) && $crit_over_thr[$i - 1] =~ /(^|\s)(-*[0-9]+)/) ? $2 : ''; + my $current_value = ($current_volt[$i - 1] =~ /(^|\s)(-*[0-9]+)/) ? $2 : ''; + + $self->{components_voltages}++; + if ($crit_under =~ /(^|,|\s)$num(,|\s|$)/) { + $self->{output}->output_add(severity => 'CRITICAL', + long_msg => sprintf("Shelve '%s' voltage sensor '%s' is under critical threshold [current = %s < %s]", + $shelf_addr, $num, $current_value, $cu_thr)); + } elsif ($warn_under =~ /(^|,|\s)$num(,|\s|$)/) { + $self->{output}->output_add(severity => 'WARNING', + long_msg => sprintf("Shelve '%s' voltage sensor '%s' is under warning threshold [current = %s < %s]", + $shelf_addr, $num, $current_value, $wu_thr)); + } elsif ($crit_over =~ /(^|,|\s)$num(,|\s|$)/) { + $self->{output}->output_add(severity => 'CRITICAL', + long_msg => sprintf("Shelve '%s' voltage sensor '%s' is over critical threshold [current = %s > %s]", + $shelf_addr, $num, $current_value, $co_thr)); + } elsif ($warn_over =~ /(^|,|\s)$num(,|\s|$)/) { + $self->{output}->output_add(severity => 'WARNING', + long_msg => sprintf("Shelve '%s' voltage sensor '%s' is over warning threshold [current = %s > %s]", + $shelf_addr, $num, $current_value, $wo_thr)); + } else { + $self->{output}->output_add(long_msg => sprintf("Shelve '%s' voltage sensor '%s' is ok [current = %s]", + $shelf_addr, $num, $current_value)); + } + + $self->{output}->perfdata_add(label => "volt_" . $i . "_" . $num, unit => 'mV', + value => $current_value, + warning => ($wu_thr ne '' || $wo_thr ne '') ? ($wu_thr . ':' . $wo_thr) : '', + critical => ($cu_thr ne '' || $co_thr ne '') ? ($cu_thr . ':' . $co_thr) : ''); + } + } +} + +sub check_temperatures { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking temperatures"); + + for (my $i = 1; $i <= $self->{number_shelf}; $i++) { + my $shelf_addr = $self->{result}->{$oid_enclChannelShelfAddr . '.' . $i}; + my $present = $self->{result}->{$oid_enclTempSensorsPresent . '.' . $i}; + my @current_temp = split /,/, $self->{result}->{$oid_enclTempSensorsCurrentTemp . '.' . $i}; + + my $warn_under = $self->{result}->{$oid_enclTempSensorsUnderTempWarn . '.' . $i}; + my $crit_under = $self->{result}->{$oid_enclTempSensorsUnderTempFail . '.' . $i}; + my $warn_over = $self->{result}->{$oid_enclTempSensorsOverTempWarn . '.' . $i}; + my $crit_over = $self->{result}->{$oid_enclTempSensorsOverTempFail . '.' . $i}; + + my @warn_under_thr = split /,/, $self->{result}->{$oid_enclTempSensorsUnderTempWarnThr . '.' . $i}; + my @crit_under_thr = split /,/, $self->{result}->{$oid_enclTempSensorsUnderTempFailThr . '.' . $i}; + my @warn_over_thr = split /,/, $self->{result}->{$oid_enclTempSensorsOverTempWarnThr . '.' . $i}; + my @crit_over_thr = split /,/, $self->{result}->{$oid_enclTempSensorsOverTempFailThr . '.' . $i}; + + foreach my $num (split /,/, $present) { + $num = centreon::plugins::misc::trim($num); + next if ($num !~ /[0-9]/); + + $warn_under_thr[$i - 1] =~ /(-*[0-9]+)C/; + my $wu_thr = $1; + $crit_under_thr[$i - 1] =~ /(-*[0-9]+)C/; + my $cu_thr = $1; + $warn_over_thr[$i - 1] =~ /(-*[0-9]+)C/; + my $wo_thr = $1; + $crit_over_thr[$i - 1] =~ /(-*[0-9]+)C/; + my $co_thr = $1; + $current_temp[$i - 1] =~ /(-*[0-9]+)C/; + my $current_value = $1; + + $self->{components_temperatures}++; + if ($crit_under =~ /(^|,|\s)$num(,|\s|$)/) { + $self->{output}->output_add(severity => 'CRITICAL', + long_msg => sprintf("Shelve '%s' temperature sensor '%s' is under critical threshold [current = %s < %s]", + $shelf_addr, $num, $current_value, $cu_thr)); + } elsif ($warn_under =~ /(^|,|\s)$num(,|\s|$)/) { + $self->{output}->output_add(severity => 'WARNING', + long_msg => sprintf("Shelve '%s' temperature sensor '%s' is under warning threshold [current = %s < %s]", + $shelf_addr, $num, $current_value, $wu_thr)); + } elsif ($crit_over =~ /(^|,|\s)$num(,|\s|$)/) { + $self->{output}->output_add(severity => 'CRITICAL', + long_msg => sprintf("Shelve '%s' temperature sensor '%s' is over critical threshold [current = %s > %s]", + $shelf_addr, $num, $current_value, $co_thr)); + } elsif ($warn_over =~ /(^|,|\s)$num(,|\s|$)/) { + $self->{output}->output_add(severity => 'WARNING', + long_msg => sprintf("Shelve '%s' temperature sensor '%s' is over warning threshold [current = %s > %s]", + $shelf_addr, $num, $current_value, $wo_thr)); + } else { + $self->{output}->output_add(long_msg => sprintf("Shelve '%s' temperature sensor '%s' is ok [current = %s]", + $shelf_addr, $num, $current_value)); + } + + $self->{output}->perfdata_add(label => "temp_" . $i . "_" . $num, unit => 'C', + value => $current_value, + warning => $wu_thr . ':' . $wo_thr, + critical => $cu_thr . ':' . $co_thr); + } + } +} + +1; + +__END__ + +=head1 MODE + +Check Shelves hardware (temperatures, voltages, electronics, fan, power supplies). + +=over 8 + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/snapmirrorlag.pm b/centreon/lib/perl/plugins/storage/netapp/mode/snapmirrorlag.pm new file mode 100644 index 00000000000..555da32b1a4 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/snapmirrorlag.pm @@ -0,0 +1,182 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::snapmirrorlag; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my $oid_snapmirrorOn = '.1.3.6.1.4.1.789.1.9.1.0'; +my $oid_snapmirrorSrc = '.1.3.6.1.4.1.789.1.9.20.1.2'; +my $oid_snapmirrorLag = '.1.3.6.1.4.1.789.1.9.20.1.6'; # hundreth of seconds + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning' }, + "critical:s" => { name => 'critical' }, + "name:s" => { name => 'name' }, + "regexp" => { name => 'use_regexp' }, + }); + $self->{snapmirrors_id_selected} = []; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub manage_selection { + my ($self, %options) = @_; + + my $result = $self->{snmp}->get_leef(oids => [$oid_snapmirrorOn]); + if (!defined($result->{$oid_snapmirrorOn}) || $result->{$oid_snapmirrorOn} != 2) { + $self->{output}->add_option_msg(short_msg => "Snapmirror is not turned on."); + $self->{output}->option_exit(); + } + + $self->{result_names} = $self->{snmp}->get_table(oid => $oid_snapmirrorSrc, nothing_quit => 1); + foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{result_names}})) { + next if ($oid !~ /\.([0-9]+)$/); + my $instance = $1; + + # Get all without a name + if (!defined($self->{option_results}->{name})) { + push @{$self->{snapmirrors_id_selected}}, $instance; + next; + } + + if (!defined($self->{option_results}->{use_regexp}) && $self->{result_names}->{$oid} eq $self->{option_results}->{name}) { + push @{$self->{snapmirrors_id_selected}}, $instance; + } + if (defined($self->{option_results}->{use_regexp}) && $self->{result_names}->{$oid} =~ /$self->{option_results}->{name}/) { + push @{$self->{snapmirrors_id_selected}}, $instance; + } + } + + if (scalar(@{$self->{snapmirrors_id_selected}}) <= 0) { + $self->{output}->add_option_msg(short_msg => "No snapmirrors found for name '" . $self->{option_results}->{name} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->manage_selection(); + $self->{snmp}->load(oids => [$oid_snapmirrorLag], instances => $self->{snapmirrors_id_selected}); + my $result = $self->{snmp}->get_leef(nothing_quit => 1); + + if (!defined($self->{option_results}->{name}) || defined($self->{option_results}->{use_regexp})) { + $self->{output}->output_add(severity => 'OK', + short_msg => 'All snapmirrors lags are ok.'); + } + + foreach my $instance (sort @{$self->{snapmirrors_id_selected}}) { + my $name = $self->{result_names}->{$oid_snapmirrorSrc . '.' . $instance}; + my $lag = int($result->{$oid_snapmirrorLag . '.' . $instance} / 100); + + my $exit = $self->{perfdata}->threshold_check(value => $lag, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + + $self->{output}->output_add(long_msg => sprintf("Snapmirror '%s' lag: %s secondes", $name, $lag)); + if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1) || (defined($self->{option_results}->{name}) && !defined($self->{option_results}->{use_regexp}))) { + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Snapmirror '%s' lag: %s secondes", $name, $lag)); + } + + my $extra_label = ''; + $extra_label = '_' . $name if (!defined($self->{option_results}->{name}) || defined($self->{option_results}->{use_regexp})); + my %total_options = (); + $self->{output}->perfdata_add(label => 'lag' . $extra_label, unit => 's', + value => $lag, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check snapmirrors lag. + +=over 8 + +=item B<--warning> + +Threshold warning in seconds. + +=item B<--critical> + +Threshold critical in seconds. + +=item B<--name> + +Set the snapmirror name. + +=item B<--regexp> + +Allows to use regexp to filter snampmirror name (with option --name). + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/temperature.pm b/centreon/lib/perl/plugins/storage/netapp/mode/temperature.pm new file mode 100644 index 00000000000..2273d335455 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/temperature.pm @@ -0,0 +1,93 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::temperature; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_envOverTemperature = '.1.3.6.1.4.1.789.1.2.4.1.0'; + my $result = $self->{snmp}->get_leef(oids => [$oid_envOverTemperature], nothing_quit => 1); + + $self->{output}->output_add(severity => 'OK', + short_msg => 'Hardware temperature is ok.'); + if ($result->{$oid_envOverTemperature} == 2) { + $self->{output}->output_add(severity => 'CRITICAL', + short_msg => 'Hardware temperature is over temperature range.'); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check if hardware is currently operating outside of its recommended temperature range. + +=over 8 + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/volumeoptions.pm b/centreon/lib/perl/plugins/storage/netapp/mode/volumeoptions.pm new file mode 100644 index 00000000000..037147a017c --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/volumeoptions.pm @@ -0,0 +1,184 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::volumeoptions; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my $oid_volName = '.1.3.6.1.4.1.789.1.5.8.1.2'; +my $oid_volOptions = '.1.3.6.1.4.1.789.1.5.8.1.7'; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warn" => { name => 'warn' }, + "crit" => { name => 'crit' }, + "name:s" => { name => 'name' }, + "regexp" => { name => 'use_regexp' }, + "option:s" => { name => 'option' }, + }); + $self->{volume_id_selected} = []; + $self->{status} = 'OK'; + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (defined($self->{option_results}->{warn})) { + $self->{status} = 'WARNING'; + } + if (defined($self->{option_results}->{crit})) { + $self->{status} = 'CRITICAL'; + } +} + +sub manage_selection { + my ($self, %options) = @_; + + $self->{result_names} = $self->{snmp}->get_table(oid => $oid_volName, nothing_quit => 1); + foreach my $oid ($self->{snmp}->oid_lex_sort(keys %{$self->{result_names}})) { + next if ($oid !~ /\.([0-9]+)$/); + my $instance = $1; + + # Get all without a name + if (!defined($self->{option_results}->{name})) { + push @{$self->{volume_id_selected}}, $instance; + next; + } + + if (!defined($self->{option_results}->{use_regexp}) && $self->{result_names}->{$oid} eq $self->{option_results}->{name}) { + push @{$self->{volume_id_selected}}, $instance; + } + if (defined($self->{option_results}->{use_regexp}) && $self->{result_names}->{$oid} =~ /$self->{option_results}->{name}/) { + push @{$self->{volume_id_selected}}, $instance; + } + } + + if (scalar(@{$self->{volume_id_selected}}) <= 0) { + $self->{output}->add_option_msg(short_msg => "No volume found for name '" . $self->{option_results}->{name} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->manage_selection(); + $self->{snmp}->load(oids => [$oid_volOptions], instances => $self->{volume_id_selected}); + my $result = $self->{snmp}->get_leef(); + + if (!defined($self->{option_results}->{name}) || defined($self->{option_results}->{use_regexp})) { + $self->{output}->output_add(severity => 'OK', + short_msg => 'All volume options are ok.'); + } + + my $failed = 0; + foreach my $instance (sort @{$self->{volume_id_selected}}) { + my $name = $self->{result_names}->{$oid_volName . '.' . $instance}; + my $option = $result->{$oid_volOptions . '.' . $instance}; + + $self->{output}->output_add(long_msg => sprintf("Volume '%s' options: %s", $name, $option)); + + my $status; + if (defined($self->{option_results}->{option}) && $option !~ /$self->{option_results}->{option}/) { + $status = $self->{status}; + $failed++; + } + + # Can be 'ok' if we don't set a threshold option '--warn', '--crit' + if (defined($status)) { + $self->{output}->output_add(severity => $status, + short_msg => sprintf("Volume '%s' pattern '%s' is not matching", $name, $self->{option_results}->{option})); + } elsif (defined($self->{option_results}->{name}) && !defined($self->{option_results}->{use_regexp})) { + $self->{output}->output_add(severity => $status, + short_msg => sprintf("Volume '%s' option is ok", $name)); + } + } + + $self->{output}->perfdata_add(label => 'failed', + value => $failed, + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check options from volumes. + +=over 8 + +=item B<--warn> + +Return Warning (need '--option' also). + +=item B<--critical> + +Return Critical (need '--option' also). + +=item B<--name> + +Set the volume name. + +=item B<--regexp> + +Allows to use regexp to filter volume name (with option --name). + +=item B<--option> + +Options to check (Example: if 'nosnap=off' not maching, returns Warning or Critical for the volume). + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/plugin.pm b/centreon/lib/perl/plugins/storage/netapp/plugin.pm new file mode 100644 index 00000000000..f1a5c5b11a9 --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/plugin.pm @@ -0,0 +1,76 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::plugin; + +use strict; +use warnings; +use base qw(centreon::plugins::script_snmp); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '1.0'; + %{$self->{modes}} = ( + 'cpuload' => 'storage::netapp::mode::cpuload', + 'diskfailed' => 'storage::netapp::mode::diskfailed', + 'fan' => 'storage::netapp::mode::fan', + 'filesys' => 'storage::netapp::mode::filesys', + 'globalstatus' => 'storage::netapp::mode::globalstatus', + 'list-filesys' => 'storage::netapp::mode::listfilesys', + 'ndmpsessions' => 'storage::netapp::mode::ndmpsessions', + 'nvram' => 'storage::netapp::mode::nvram', + 'psu' => 'storage::netapp::mode::psu', + 'shelf' => 'storage::netapp::mode::shelf', + 'snapmirrorlag' => 'storage::netapp::mode::snapmirrorlag', + 'temperature' => 'storage::netapp::mode::temperature', + 'volumeoptions' => 'storage::netapp::mode::volumeoptions', + ); + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check Netapp in SNMP (Some Check needs ONTAP 8.x). + +=cut From 7ba7220dcfef940feccf63db5d1394be08f947fd Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Tue, 26 Nov 2013 16:50:40 +0100 Subject: [PATCH 166/458] + Add mode 'partnerstatus' for netapp --- .../storage/netapp/mode/partnerstatus.pm | 118 ++++++++++++++++++ .../lib/perl/plugins/storage/netapp/plugin.pm | 1 + 2 files changed, 119 insertions(+) create mode 100644 centreon/lib/perl/plugins/storage/netapp/mode/partnerstatus.pm diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/partnerstatus.pm b/centreon/lib/perl/plugins/storage/netapp/mode/partnerstatus.pm new file mode 100644 index 00000000000..5089b4ae13b --- /dev/null +++ b/centreon/lib/perl/plugins/storage/netapp/mode/partnerstatus.pm @@ -0,0 +1,118 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package storage::netapp::mode::partnerstatus; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %states = ( + 1 => ['maybe down', 'WARNING'], + 2 => ['ok', 'OK'], + 3 => ['dead', 'CRITICAL'], +); +my %connect_state = ( + 1 => ['not present', 'CRITICAL'], + 2 => ['down', 'CRITICAL'], + 3 => ['partial failure', 'WARNING'], + 4 => ['up', 'OK'], +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_cfPartnerStatus = '.1.3.6.1.4.1.789.1.2.3.4.0'; + my $oid_cfPartnerName = '.1.3.6.1.4.1.789.1.2.3.6.0'; + my $oid_cfInterconnectStatus = '.1.3.6.1.4.1.789.1.2.3.8.0'; + my $result = $self->{snmp}->get_leef(oids => [$oid_cfPartnerStatus, $oid_cfPartnerName, $oid_cfInterconnectStatus], nothing_quit => 1); + + $self->{output}->output_add(severity => 'OK', + short_msg => sprintf("Partner '%s' status is '%s'", $result->{$oid_cfPartnerName}, + ${$states{$result->{$oid_cfPartnerStatus}}}[0])); + if (${$states{$result->{$oid_cfPartnerStatus}}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$states{$result->{$oid_cfPartnerStatus}}}[1], + short_msg => sprintf("Partner '%s' status is '%s'", $result->{$oid_cfPartnerName}, + ${$states{$result->{$oid_cfPartnerStatus}}}[0])); + } + + $self->{output}->output_add(severity => 'OK', + short_msg => sprintf("Interconnect status is '%s'", + ${$connect_state{$result->{$oid_cfInterconnectStatus}}}[0])); + if (${$connect_state{$result->{$oid_cfInterconnectStatus}}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$connect_state{$result->{$oid_cfInterconnectStatus}}}[1], + short_msg => sprintf("Interconnect status is '%s'", + ${$connect_state{$result->{$oid_cfInterconnectStatus}}}[0])); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check status of clustered failover partner. + +=over 8 + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/storage/netapp/plugin.pm b/centreon/lib/perl/plugins/storage/netapp/plugin.pm index f1a5c5b11a9..eb4b5b2dada 100644 --- a/centreon/lib/perl/plugins/storage/netapp/plugin.pm +++ b/centreon/lib/perl/plugins/storage/netapp/plugin.pm @@ -55,6 +55,7 @@ sub new { 'list-filesys' => 'storage::netapp::mode::listfilesys', 'ndmpsessions' => 'storage::netapp::mode::ndmpsessions', 'nvram' => 'storage::netapp::mode::nvram', + 'partnerstatus' => 'storage::netapp::mode::partnerstatus', 'psu' => 'storage::netapp::mode::psu', 'shelf' => 'storage::netapp::mode::shelf', 'snapmirrorlag' => 'storage::netapp::mode::snapmirrorlag', From 90e8ae2750a908142cc814a878e8d49d843aabd1 Mon Sep 17 00:00:00 2001 From: Sylvestre Ho Date: Fri, 29 Nov 2013 10:07:59 +0100 Subject: [PATCH 167/458] fixes #4972; escape single quotes --- centreon/lib/perl/centreon/script/centcore.pm | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index d725d2e9be9..f9e2a87bfa7 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -362,8 +362,9 @@ sub sendExternalCommand($$){ $self->{logger}->writeLogError("Cannot write external command on central server : \"".$cmd."\""); } } else { + $cmd =~ s/\'/\'\\\'\'/g; $self->{logger}->writeLogInfo("External command : ".$server_info->{'ns_ip_address'}." ($id) : \"".$cmd."\""); - $cmd2 = "$self->{ssh} -q ". $server_info->{'ns_ip_address'} ." -p $port '$self->{echo} \"".$cmd."\" >> ".$command_file."'"; + $cmd2 = "$self->{ssh} -q ". $server_info->{'ns_ip_address'} ." -p $port \"$self->{echo} '".$cmd."' >> ".$command_file."\""; ($lerror, $stdout) = centreon::common::misc::backtick(command => $cmd2, logger => $self->{logger}, timeout => $self->{cmd_timeout} From 61be0ae6405cc4cdc03779952d08bcc17a4d40f6 Mon Sep 17 00:00:00 2001 From: Julien Mathis Date: Fri, 29 Nov 2013 13:24:55 +0100 Subject: [PATCH 168/458] change header for perl files. --- .../centreon/centstorage/CentstorageAction.pm | 32 ++++++++++++++++ .../centreon/centstorage/CentstorageLib.pm | 32 ++++++++++++++++ .../centstorage/CentstoragePerfdataFile.pm | 32 ++++++++++++++++ .../centreon/centstorage/CentstoragePool.pm | 32 ++++++++++++++++ .../centreon/centstorage/CentstorageRRD.pm | 32 ++++++++++++++++ .../centstorage/CentstorageRebuild.pm | 32 ++++++++++++++++ centreon/lib/perl/centreon/common/db.pm | 32 ++++++++++++++++ centreon/lib/perl/centreon/common/lock.pm | 33 ++++++++++++++++ centreon/lib/perl/centreon/common/logger.pm | 33 ++++++++++++++++ centreon/lib/perl/centreon/common/misc.pm | 32 ++++++++++++++++ .../perl/centreon/reporting/CentreonAck.pm | 34 ++++++++++++++++- .../centreon/reporting/CentreonDashboard.pm | 32 ++++++++++++++++ .../centreon/reporting/CentreonDownTime.pm | 34 ++++++++++++++++- .../perl/centreon/reporting/CentreonHost.pm | 34 ++++++++++++++++- .../reporting/CentreonHostStateEvents.pm | 34 ++++++++++++++++- .../perl/centreon/reporting/CentreonLog.pm | 32 ++++++++++++++++ .../reporting/CentreonProcessStateEvents.pm | 34 ++++++++++++++++- .../centreon/reporting/CentreonService.pm | 34 ++++++++++++++++- .../reporting/CentreonServiceStateEvents.pm | 34 ++++++++++++++++- centreon/lib/perl/centreon/script.pm | 33 ++++++++++++++++ .../perl/centreon/script/centFillTrapDB.pm | 32 ++++++++++++++++ centreon/lib/perl/centreon/script/centcore.pm | 32 ++++++++++++++++ .../centreon/script/centreonSyncArchives.pm | 32 ++++++++++++++++ .../centreon/script/centreonSyncPlugins.pm | 34 ++++++++++++++++- .../script/centreon_check_perfdata.pm | 33 ++++++++++++++++ .../centreon/script/centreon_trap_send.pm | 33 ++++++++++++++++ .../lib/perl/centreon/script/centreontrapd.pm | 32 ++++++++++++++++ .../centreon/script/centreontrapdforward.pm | 34 ++++++++++++++++- .../lib/perl/centreon/script/centstorage.pm | 32 ++++++++++++++++ .../perl/centreon/script/centstorage_purge.pm | 33 ++++++++++++++++ .../perl/centreon/script/dashboardBuilder.pm | 32 ++++++++++++++++ .../centreon/script/eventReportBuilder.pm | 32 ++++++++++++++++ .../lib/perl/centreon/script/logAnalyser.pm | 33 ++++++++++++++++ .../perl/centreon/script/logAnalyserBroker.pm | 35 ++++++++++++++++- .../perl/centreon/script/nagiosPerfTrace.pm | 32 ++++++++++++++++ centreon/lib/perl/centreon/trapd/Log.pm | 38 +++++++++++++++++-- centreon/lib/perl/centreon/trapd/lib.pm | 34 ++++++++++++++++- 37 files changed, 1206 insertions(+), 14 deletions(-) diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm index 929108e3f18..d625cb2fe39 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageAction.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::centstorage::CentstorageAction; diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm b/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm index 85810a6402c..73e638d168c 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageLib.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::centstorage::CentstorageLib; use File::Basename; diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm index 53ac3a654cb..3836d085b06 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePerfdataFile.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use strict; use warnings; diff --git a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm index a4a2c361548..8d49329ec4c 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstoragePool.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::centstorage::CentstoragePool; diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageRRD.pm b/centreon/lib/perl/centreon/centstorage/CentstorageRRD.pm index 23dc432013d..75076e259d3 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageRRD.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageRRD.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use RRDs; use strict; diff --git a/centreon/lib/perl/centreon/centstorage/CentstorageRebuild.pm b/centreon/lib/perl/centreon/centstorage/CentstorageRebuild.pm index 6fe807a6d5b..9c9299f2a71 100644 --- a/centreon/lib/perl/centreon/centstorage/CentstorageRebuild.pm +++ b/centreon/lib/perl/centreon/centstorage/CentstorageRebuild.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use strict; use warnings; diff --git a/centreon/lib/perl/centreon/common/db.pm b/centreon/lib/perl/centreon/common/db.pm index eaa0af03a86..f2eeaa5459b 100644 --- a/centreon/lib/perl/centreon/common/db.pm +++ b/centreon/lib/perl/centreon/common/db.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::common::db; diff --git a/centreon/lib/perl/centreon/common/lock.pm b/centreon/lib/perl/centreon/common/lock.pm index 10d9b20170a..ddb9da817d1 100644 --- a/centreon/lib/perl/centreon/common/lock.pm +++ b/centreon/lib/perl/centreon/common/lock.pm @@ -1,3 +1,36 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### + package centreon::common::lock; use strict; diff --git a/centreon/lib/perl/centreon/common/logger.pm b/centreon/lib/perl/centreon/common/logger.pm index 3a875aeab65..454cafb3470 100644 --- a/centreon/lib/perl/centreon/common/logger.pm +++ b/centreon/lib/perl/centreon/common/logger.pm @@ -1,3 +1,36 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### + package centreon::common::logger; =head1 NOM diff --git a/centreon/lib/perl/centreon/common/misc.pm b/centreon/lib/perl/centreon/common/misc.pm index c4356f5d3cf..d0ee433df14 100644 --- a/centreon/lib/perl/centreon/common/misc.pm +++ b/centreon/lib/perl/centreon/common/misc.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::common::misc; diff --git a/centreon/lib/perl/centreon/reporting/CentreonAck.pm b/centreon/lib/perl/centreon/reporting/CentreonAck.pm index 1bb79a817cc..eb6268f8d56 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonAck.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonAck.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use strict; use warnings; @@ -106,4 +138,4 @@ sub getHostAckTime { return ($ackTime); } -1; \ No newline at end of file +1; diff --git a/centreon/lib/perl/centreon/reporting/CentreonDashboard.pm b/centreon/lib/perl/centreon/reporting/CentreonDashboard.pm index cbe1507bfbc..26a643135ec 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonDashboard.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonDashboard.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use strict; use warnings; diff --git a/centreon/lib/perl/centreon/reporting/CentreonDownTime.pm b/centreon/lib/perl/centreon/reporting/CentreonDownTime.pm index 029e3ed22bd..a89600d17a2 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonDownTime.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonDownTime.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use strict; use warnings; @@ -219,4 +251,4 @@ sub splitUpdateEventDownTime { return ($updateTime, \@events); } -1; \ No newline at end of file +1; diff --git a/centreon/lib/perl/centreon/reporting/CentreonHost.pm b/centreon/lib/perl/centreon/reporting/CentreonHost.pm index d38bf06a70d..ab55e4efc47 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonHost.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonHost.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use strict; use warnings; @@ -60,4 +92,4 @@ sub getAllHostsByName { return ($host_names); } -1; \ No newline at end of file +1; diff --git a/centreon/lib/perl/centreon/reporting/CentreonHostStateEvents.pm b/centreon/lib/perl/centreon/reporting/CentreonHostStateEvents.pm index 4dcf9d31260..43424b400c6 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonHostStateEvents.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonHostStateEvents.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use strict; use warnings; @@ -199,4 +231,4 @@ sub getFirstLastIncidentTimes { return ($start, $end); } -1; \ No newline at end of file +1; diff --git a/centreon/lib/perl/centreon/reporting/CentreonLog.pm b/centreon/lib/perl/centreon/reporting/CentreonLog.pm index f740cb823ad..22834294702 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonLog.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonLog.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use strict; use warnings; diff --git a/centreon/lib/perl/centreon/reporting/CentreonProcessStateEvents.pm b/centreon/lib/perl/centreon/reporting/CentreonProcessStateEvents.pm index e84f787fc8d..b5f6d65fa81 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonProcessStateEvents.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonProcessStateEvents.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use strict; use warnings; @@ -176,4 +208,4 @@ sub insertLastHostEvents { } } -1; \ No newline at end of file +1; diff --git a/centreon/lib/perl/centreon/reporting/CentreonService.pm b/centreon/lib/perl/centreon/reporting/CentreonService.pm index 0ef539451e8..5958328c328 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonService.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonService.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use strict; use warnings; @@ -83,4 +115,4 @@ sub getAllservicesByName { return ($service_names); } -1; \ No newline at end of file +1; diff --git a/centreon/lib/perl/centreon/reporting/CentreonServiceStateEvents.pm b/centreon/lib/perl/centreon/reporting/CentreonServiceStateEvents.pm index 1b098044f4c..8be29dba542 100644 --- a/centreon/lib/perl/centreon/reporting/CentreonServiceStateEvents.pm +++ b/centreon/lib/perl/centreon/reporting/CentreonServiceStateEvents.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### use strict; use warnings; @@ -200,4 +232,4 @@ sub getFirstLastIncidentTimes { return ($start, $end); } -1; \ No newline at end of file +1; diff --git a/centreon/lib/perl/centreon/script.pm b/centreon/lib/perl/centreon/script.pm index 557c1fa33f0..4264be4e837 100644 --- a/centreon/lib/perl/centreon/script.pm +++ b/centreon/lib/perl/centreon/script.pm @@ -1,3 +1,36 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### + package centreon::script; use strict; diff --git a/centreon/lib/perl/centreon/script/centFillTrapDB.pm b/centreon/lib/perl/centreon/script/centFillTrapDB.pm index c84b72bbc56..fd7002077c1 100644 --- a/centreon/lib/perl/centreon/script/centFillTrapDB.pm +++ b/centreon/lib/perl/centreon/script/centFillTrapDB.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::script::centFillTrapDB; diff --git a/centreon/lib/perl/centreon/script/centcore.pm b/centreon/lib/perl/centreon/script/centcore.pm index f9e2a87bfa7..83114fafb88 100644 --- a/centreon/lib/perl/centreon/script/centcore.pm +++ b/centreon/lib/perl/centreon/script/centcore.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::script::centcore; diff --git a/centreon/lib/perl/centreon/script/centreonSyncArchives.pm b/centreon/lib/perl/centreon/script/centreonSyncArchives.pm index 57be92c484e..c266450bcf0 100644 --- a/centreon/lib/perl/centreon/script/centreonSyncArchives.pm +++ b/centreon/lib/perl/centreon/script/centreonSyncArchives.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::script::centreonSyncArchives; diff --git a/centreon/lib/perl/centreon/script/centreonSyncPlugins.pm b/centreon/lib/perl/centreon/script/centreonSyncPlugins.pm index eaad605dc16..10972522925 100644 --- a/centreon/lib/perl/centreon/script/centreonSyncPlugins.pm +++ b/centreon/lib/perl/centreon/script/centreonSyncPlugins.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::script::centreonSyncPlugins; @@ -58,4 +90,4 @@ __END__ sample - Using GetOpt::Long and Pod::Usage -=cut \ No newline at end of file +=cut diff --git a/centreon/lib/perl/centreon/script/centreon_check_perfdata.pm b/centreon/lib/perl/centreon/script/centreon_check_perfdata.pm index 82ff19607e3..cfff14b6fe1 100644 --- a/centreon/lib/perl/centreon/script/centreon_check_perfdata.pm +++ b/centreon/lib/perl/centreon/script/centreon_check_perfdata.pm @@ -1,3 +1,36 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### + package centreon::script::centreon_check_perfdata; use strict; diff --git a/centreon/lib/perl/centreon/script/centreon_trap_send.pm b/centreon/lib/perl/centreon/script/centreon_trap_send.pm index 65f5d29bda5..685f88dbc5b 100644 --- a/centreon/lib/perl/centreon/script/centreon_trap_send.pm +++ b/centreon/lib/perl/centreon/script/centreon_trap_send.pm @@ -1,3 +1,36 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### + package centreon::script::centreon_trap_send; use strict; diff --git a/centreon/lib/perl/centreon/script/centreontrapd.pm b/centreon/lib/perl/centreon/script/centreontrapd.pm index a9c3e3c353d..d3ef3932829 100644 --- a/centreon/lib/perl/centreon/script/centreontrapd.pm +++ b/centreon/lib/perl/centreon/script/centreontrapd.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::script::centreontrapd; diff --git a/centreon/lib/perl/centreon/script/centreontrapdforward.pm b/centreon/lib/perl/centreon/script/centreontrapdforward.pm index 33863efcd43..94af76f333b 100644 --- a/centreon/lib/perl/centreon/script/centreontrapdforward.pm +++ b/centreon/lib/perl/centreon/script/centreontrapdforward.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::script::centreontrapdforward; @@ -85,4 +117,4 @@ sub run { exit(0); } -1; \ No newline at end of file +1; diff --git a/centreon/lib/perl/centreon/script/centstorage.pm b/centreon/lib/perl/centreon/script/centstorage.pm index fd3e7cd218c..d0fd7e54578 100644 --- a/centreon/lib/perl/centreon/script/centstorage.pm +++ b/centreon/lib/perl/centreon/script/centstorage.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::script::centstorage; diff --git a/centreon/lib/perl/centreon/script/centstorage_purge.pm b/centreon/lib/perl/centreon/script/centstorage_purge.pm index ae9db04dbaa..83abb1a1413 100644 --- a/centreon/lib/perl/centreon/script/centstorage_purge.pm +++ b/centreon/lib/perl/centreon/script/centstorage_purge.pm @@ -1,3 +1,36 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### + package centreon::script::centstorage_purge; use strict; diff --git a/centreon/lib/perl/centreon/script/dashboardBuilder.pm b/centreon/lib/perl/centreon/script/dashboardBuilder.pm index d2c19ff456f..0e601e181ef 100644 --- a/centreon/lib/perl/centreon/script/dashboardBuilder.pm +++ b/centreon/lib/perl/centreon/script/dashboardBuilder.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::script::dashboardBuilder; diff --git a/centreon/lib/perl/centreon/script/eventReportBuilder.pm b/centreon/lib/perl/centreon/script/eventReportBuilder.pm index c78fe113a86..b1ce0e39339 100644 --- a/centreon/lib/perl/centreon/script/eventReportBuilder.pm +++ b/centreon/lib/perl/centreon/script/eventReportBuilder.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::script::eventReportBuilder; diff --git a/centreon/lib/perl/centreon/script/logAnalyser.pm b/centreon/lib/perl/centreon/script/logAnalyser.pm index 90336a17262..417ee790ee7 100644 --- a/centreon/lib/perl/centreon/script/logAnalyser.pm +++ b/centreon/lib/perl/centreon/script/logAnalyser.pm @@ -1,3 +1,36 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### + package centreon::script::logAnalyser; use strict; diff --git a/centreon/lib/perl/centreon/script/logAnalyserBroker.pm b/centreon/lib/perl/centreon/script/logAnalyserBroker.pm index fe07fe05b67..73da68b2c3c 100644 --- a/centreon/lib/perl/centreon/script/logAnalyserBroker.pm +++ b/centreon/lib/perl/centreon/script/logAnalyserBroker.pm @@ -1,3 +1,36 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### + package centreon::script::logAnalyserBroker; use strict; @@ -321,4 +354,4 @@ sub run { $self->{logger}->writeLogInfo("Done"); } -1; \ No newline at end of file +1; diff --git a/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm b/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm index b835ae21a41..f7ec8490a20 100644 --- a/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm +++ b/centreon/lib/perl/centreon/script/nagiosPerfTrace.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::script::nagiosPerfTrace; diff --git a/centreon/lib/perl/centreon/trapd/Log.pm b/centreon/lib/perl/centreon/trapd/Log.pm index 22218d2193d..215c488630b 100644 --- a/centreon/lib/perl/centreon/trapd/Log.pm +++ b/centreon/lib/perl/centreon/trapd/Log.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::trapd::Log; @@ -139,7 +171,7 @@ sub main { # We have to manage if you don't need infos $self->{'dbcentstorage'}->force(0); - + my $read_select = new IO::Select(); $read_select->add($pipe_read); while (1) { @@ -153,7 +185,7 @@ sub main { $readline =~ /^(.*?):(.*?):(.*?):(.*)/; my ($id, $type, $num, $value) = ($1, $2, $3, $4); $value =~ s/\\n/\n/g; - + if ($type == 0) { if ($num <= 0) { $self->{request_log}->{$id} = { value => $value }; @@ -174,7 +206,7 @@ sub main { } } } - + $self->compute_request(); if ($self->{reload} == 0) { diff --git a/centreon/lib/perl/centreon/trapd/lib.pm b/centreon/lib/perl/centreon/trapd/lib.pm index e21be1d81d6..9f3da0137e5 100644 --- a/centreon/lib/perl/centreon/trapd/lib.pm +++ b/centreon/lib/perl/centreon/trapd/lib.pm @@ -1,3 +1,35 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# +#################################################################################### package centreon::trapd::lib; @@ -867,4 +899,4 @@ sub strip_domain_name { return $name; } -1; \ No newline at end of file +1; From a1ae97fe701242872994c067b0341f7609b7f1c5 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 5 Dec 2013 15:14:50 +0100 Subject: [PATCH 169/458] + Add Juniper SRX monitoring plugin --- centreon/lib/perl/centreon/plugins/snmp.pm | 4 +- .../network/juniper/common/mode/cpsessions.pm | 139 ++++++++++ .../juniper/common/mode/cpuforwarding.pm | 126 +++++++++ .../network/juniper/common/mode/cpurouting.pm | 154 +++++++++++ .../juniper/common/mode/flowsessions.pm | 139 ++++++++++ .../network/juniper/common/mode/hardware.pm | 242 ++++++++++++++++++ .../juniper/common/mode/memoryforwarding.pm | 126 +++++++++ .../juniper/common/mode/memoryrouting.pm | 151 +++++++++++ .../plugins/network/juniper/srx/plugin.pm | 73 ++++++ centreon/lib/perl/plugins/os/linux/plugin.pm | 2 +- 10 files changed, 1154 insertions(+), 2 deletions(-) create mode 100644 centreon/lib/perl/plugins/network/juniper/common/mode/cpsessions.pm create mode 100644 centreon/lib/perl/plugins/network/juniper/common/mode/cpuforwarding.pm create mode 100644 centreon/lib/perl/plugins/network/juniper/common/mode/cpurouting.pm create mode 100644 centreon/lib/perl/plugins/network/juniper/common/mode/flowsessions.pm create mode 100644 centreon/lib/perl/plugins/network/juniper/common/mode/hardware.pm create mode 100644 centreon/lib/perl/plugins/network/juniper/common/mode/memoryforwarding.pm create mode 100644 centreon/lib/perl/plugins/network/juniper/common/mode/memoryrouting.pm create mode 100644 centreon/lib/perl/plugins/network/juniper/srx/plugin.pm diff --git a/centreon/lib/perl/centreon/plugins/snmp.pm b/centreon/lib/perl/centreon/plugins/snmp.pm index a32358dca01..94caee59916 100644 --- a/centreon/lib/perl/centreon/plugins/snmp.pm +++ b/centreon/lib/perl/centreon/plugins/snmp.pm @@ -123,6 +123,7 @@ sub load { # $options{oids} = ref to array of oids (example: ['.1.2', '.1.2']) # $options{instances} = ref to array of oids instances # $options{begin}, $args->{end} = integer instance end + # $options{instance_regexp} = str # 3 way to use: with instances, with end, none if (defined($options{end})) { @@ -135,8 +136,9 @@ sub load { } if (defined($options{instances})) { + $options{instance_regexp} = defined($options{instance_regexp}) ? $options{instance_regexp} : '(\d+)$'; foreach my $instance (@{$options{instances}}) { - $instance =~ /(\d+)$/; + $instance =~ /$options{instance_regexp}/; foreach (@{$options{oids}}) { push @{$self->{oids_loaded}}, $_ . "." . $1; } diff --git a/centreon/lib/perl/plugins/network/juniper/common/mode/cpsessions.pm b/centreon/lib/perl/plugins/network/juniper/common/mode/cpsessions.pm new file mode 100644 index 00000000000..98a71a6f7ab --- /dev/null +++ b/centreon/lib/perl/plugins/network/juniper/common/mode/cpsessions.pm @@ -0,0 +1,139 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::juniper::common::mode::cpsessions; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_jnxJsSPUMonitoringSPUIndex = '.1.3.6.1.4.1.2636.3.39.1.12.1.1.1.3'; + my $oid_jnxJsSPUMonitoringCurrentCPSession = '.1.3.6.1.4.1.2636.3.39.1.12.1.1.1.8'; + my $oid_jnxJsSPUMonitoringMaxCPSession = '.1.3.6.1.4.1.2636.3.39.1.12.1.1.1.9'; + + my $result = $self->{snmp}->get_table(oid => $oid_jnxJsSPUMonitoringSPUIndex, nothing_quit => 1); + $self->{snmp}->load(oids => [$oid_jnxJsSPUMonitoringCurrentCPSession, $oid_jnxJsSPUMonitoringMaxCPSession], + instances => [keys %$result], + instance_regexp => '\.(\d+)$'); + my $result2 = $self->{snmp}->get_leef(nothing_quit => 1); + + my $spu_done = 0; + foreach my $oid (keys %$result) { + $oid =~ /\.(\d+)$/; + my $instance = $1; + my $cp_total = $result2->{$oid_jnxJsSPUMonitoringMaxCPSession . '.' . $instance}; + my $cp_used = $result2->{$oid_jnxJsSPUMonitoringCurrentCPSession . '.' . $instance}; + + next if ($cp_total == 0); + my $prct_used = $cp_used * 100 / $cp_total; + + $spu_done = 1; + my $exit_code = $self->{perfdata}->threshold_check(value => $prct_used, + threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("SPU '%d': %.2f%% of the cp sessions limit reached (%d of max. %d)", + $instance, $prct_used, $cp_used, $cp_total)); + $self->{output}->perfdata_add(label => 'sessions_' . $instance, + value => $cp_used, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $cp_total), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $cp_total), + min => 0, max => $cp_total); + } + + if ($spu_done == 0) { + $self->{output}->add_option_msg(short_msg => "Cannot check cp sessions usage (no total values)."); + $self->{output}->option_exit(); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check CP ('central point') sessions usage. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/juniper/common/mode/cpuforwarding.pm b/centreon/lib/perl/plugins/network/juniper/common/mode/cpuforwarding.pm new file mode 100644 index 00000000000..45880e833d3 --- /dev/null +++ b/centreon/lib/perl/plugins/network/juniper/common/mode/cpuforwarding.pm @@ -0,0 +1,126 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::juniper::common::mode::cpuforwarding; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_jnxJsSPUMonitoringSPUIndex = '.1.3.6.1.4.1.2636.3.39.1.12.1.1.1.3'; + my $oid_jnxJsSPUMonitoringCPUUsage = '.1.3.6.1.4.1.2636.3.39.1.12.1.1.1.4'; + + my $result = $self->{snmp}->get_table(oid => $oid_jnxJsSPUMonitoringSPUIndex, nothing_quit => 1); + $self->{snmp}->load(oids => [$oid_jnxJsSPUMonitoringCPUUsage], + instances => [keys %$result], + instance_regexp => '\.(\d+)$'); + my $result2 = $self->{snmp}->get_leef(nothing_quit => 1); + + foreach my $oid (keys %$result) { + $oid =~ /\.(\d+)$/; + my $instance = $1; + my $cpu_usage = $result2->{$oid_jnxJsSPUMonitoringCPUUsage . '.' . $instance}; + + my $exit_code = $self->{perfdata}->threshold_check(value => $cpu_usage, + threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("CPU '%d' average usage is: %s%%", $instance, $cpu_usage)); + $self->{output}->perfdata_add(label => 'cpu_' . $instance, unit => '%', + value => $cpu_usage, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0, max => 100); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check CPU Usage of packet forwarding engine. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/juniper/common/mode/cpurouting.pm b/centreon/lib/perl/plugins/network/juniper/common/mode/cpurouting.pm new file mode 100644 index 00000000000..c5e10428028 --- /dev/null +++ b/centreon/lib/perl/plugins/network/juniper/common/mode/cpurouting.pm @@ -0,0 +1,154 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::juniper::common::mode::cpurouting; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_jnxOperatingDescr = '.1.3.6.1.4.1.2636.3.1.13.1.5'; + my $oid_jnxOperatingCPU = '.1.3.6.1.4.1.2636.3.1.13.1.8'; + my $oid_jnxOperating1MinLoadAvg = '.1.3.6.1.4.1.2636.3.1.13.1.20'; + my $oid_jnxOperating5MinLoadAvg = '.1.3.6.1.4.1.2636.3.1.13.1.21'; + my $oid_jnxOperating15MinLoadAvg = '.1.3.6.1.4.1.2636.3.1.13.1.22'; + + my $result = $self->{snmp}->get_table(oid => $oid_jnxOperatingDescr, nothing_quit => 1); + my $routing_engine_find = 0; + my $oid_routing_engine; + foreach my $oid (keys %$result) { + if ($result->{$oid} =~ /routing/i) { + $routing_engine_find = 1; + $oid_routing_engine = $oid; + last; + } + } + + if ($routing_engine_find == 0) { + $self->{output}->add_option_msg(short_msg => "Cannot find operating with 'routing' in description."); + $self->{output}->option_exit(); + } + + $self->{snmp}->load(oids => [$oid_jnxOperatingCPU, $oid_jnxOperating1MinLoadAvg, $oid_jnxOperating5MinLoadAvg, $oid_jnxOperating15MinLoadAvg], + instances => [$oid_routing_engine], + instance_regexp => "^" . $oid_jnxOperatingDescr . '\.(.+)'); + my $result2 = $self->{snmp}->get_leef(); + + $oid_routing_engine =~ /^$oid_jnxOperatingDescr\.(.+)/; + my $instance = $1; + my $cpu_usage = $result2->{$oid_jnxOperatingCPU . '.' . $instance}; + my $cpu_load1 = $result2->{$oid_jnxOperating1MinLoadAvg . '.' . $instance}; + my $cpu_load5 = $result2->{$oid_jnxOperating5MinLoadAvg . '.' . $instance}; + my $cpu_load15 = $result2->{$oid_jnxOperating15MinLoadAvg . '.' . $instance}; + + my $exit_code = $self->{perfdata}->threshold_check(value => $cpu_usage, + threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("CPU(s) average usage is: %s%%", $cpu_usage)); + $self->{output}->perfdata_add(label => 'cpu', unit => '%', + value => $cpu_usage, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0, max => 100); + $self->{output}->perfdata_add(label => 'load1', + value => $cpu_load1, + min => 0); + $self->{output}->perfdata_add(label => 'load5', + value => $cpu_load5, + min => 0); + $self->{output}->perfdata_add(label => 'load15', + value => $cpu_load15, + min => 0); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check CPU Usage of routing engine. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/juniper/common/mode/flowsessions.pm b/centreon/lib/perl/plugins/network/juniper/common/mode/flowsessions.pm new file mode 100644 index 00000000000..a93af914fe8 --- /dev/null +++ b/centreon/lib/perl/plugins/network/juniper/common/mode/flowsessions.pm @@ -0,0 +1,139 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::juniper::common::mode::flowsessions; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_jnxJsSPUMonitoringSPUIndex = '.1.3.6.1.4.1.2636.3.39.1.12.1.1.1.3'; + my $oid_jnxJsSPUMonitoringCurrentFlowSession = '.1.3.6.1.4.1.2636.3.39.1.12.1.1.1.6'; + my $oid_jnxJsSPUMonitoringMaxFlowSession = '.1.3.6.1.4.1.2636.3.39.1.12.1.1.1.7'; + + my $result = $self->{snmp}->get_table(oid => $oid_jnxJsSPUMonitoringSPUIndex, nothing_quit => 1); + $self->{snmp}->load(oids => [$oid_jnxJsSPUMonitoringCurrentFlowSession, $oid_jnxJsSPUMonitoringMaxFlowSession], + instances => [keys %$result], + instance_regexp => '\.(\d+)$'); + my $result2 = $self->{snmp}->get_leef(nothing_quit => 1); + + my $spu_done = 0; + foreach my $oid (keys %$result) { + $oid =~ /\.(\d+)$/; + my $instance = $1; + my $flow_total = $result2->{$oid_jnxJsSPUMonitoringMaxFlowSession . '.' . $instance}; + my $flow_used = $result2->{$oid_jnxJsSPUMonitoringCurrentFlowSession . '.' . $instance}; + + next if ($flow_total == 0); + my $prct_used = $flow_used * 100 / $flow_total; + + $spu_done = 1; + my $exit_code = $self->{perfdata}->threshold_check(value => $prct_used, + threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("SPU '%d': %.2f%% of the flow sessions limit reached (%d of max. %d)", + $instance, $prct_used, $flow_used, $flow_total)); + $self->{output}->perfdata_add(label => 'sessions_' . $instance, + value => $flow_used, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $flow_total), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $flow_total), + min => 0, max => $flow_total); + } + + if ($spu_done == 0) { + $self->{output}->add_option_msg(short_msg => "Cannot check flow sessions usage (no total values)."); + $self->{output}->option_exit(); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check Packet Forwarding Engine sessions usage. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/juniper/common/mode/hardware.pm b/centreon/lib/perl/plugins/network/juniper/common/mode/hardware.pm new file mode 100644 index 00000000000..c525731308b --- /dev/null +++ b/centreon/lib/perl/plugins/network/juniper/common/mode/hardware.pm @@ -0,0 +1,242 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::juniper::common::mode::hardware; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +my %map_fru_offline = ( + 1 => 'unknown', 2 => 'none', 3 => 'error', 4 => 'noPower', 5 => 'configPowerOff', 6 => 'configHoldInReset', + 7 => 'cliCommand', 8 => 'buttonPress', 9 => 'cliRestart', 10 => 'overtempShutdown', 11 => 'masterClockDown', + 12 => 'singleSfmModeChange', 13 => 'packetSchedulingModeChange', 14 => 'physicalRemoval', 15 => 'unresponsiveRestart', + 16 => 'sonetClockAbsent', 17 => 'rddPowerOff', 18 => 'majorErrors', 19 => 'minorErrors', 20 => 'lccHardRestart', + 21 => 'lccVersionMismatch', 22 => 'powerCycle', 23 => 'reconnect', 24 => 'overvoltage', 25 => 'pfeVersionMismatch', + 26 => 'febRddCfgChange', 27 => 'fpcMisconfig', 28 => 'fruReconnectFail', 29 => 'fruFwddReset', 30 => 'fruFebSwitch', + 31 => 'fruFebOffline', 32 => 'fruInServSoftUpgradeError', 33 => 'fruChasdPowerRatingExceed', 34 => 'fruConfigOffline', + 35 => 'fruServiceRestartRequest', 36 => 'spuResetRequest', 37 => 'spuFlowdDown', 38 => 'spuSpi4Down', 39 => 'spuWatchdogTimeout', + 40 => 'spuCoreDump', 41 => 'fpgaSpi4LinkDown', 42 => 'i3Spi4LinkDown', 43 => 'cppDisconnect', 44 => 'cpuNotBoot', + 45 => 'spuCoreDumpComplete', 46 => 'rstOnSpcSpuFailure', 47 => 'softRstOnSpcSpuFailure', 48 => 'hwAuthenticationFailure', + 49 => 'reconnectFpcFail', 50 => 'fpcAppFailed', 51 => 'fpcKernelCrash', 52 => 'spuFlowdDownNoCore', 53 => 'spuFlowdCoreDumpIncomplete', + 54 => 'spuFlowdCoreDumpComplete', 55 => 'spuIdpdDownNoCore', 56 => 'spuIdpdCoreDumpIncomplete', 57 => 'spuIdpdCoreDumpComplete', + 58 => 'spuCoreDumpIncomplete', 59 => 'spuIdpdDown', 60 => 'fruPfeReset', 61 => 'fruReconnectNotReady', 62 => 'fruSfLinkDown', + 63 => 'fruFabricDown', 64 => 'fruAntiCounterfeitRetry', 65 => 'fruFPCChassisClusterDisable', 66 => 'spuFipsError', + 67 => 'fruFPCFabricDownOffline', 68 => 'febCfgChange', 69 => 'routeLocalizationRoleChange', 70 => 'fruFpcUnsupported', + 71 => 'psdVersionMismatch', 72 => 'fruResetThresholdExceeded', 73 => 'picBounce', 74 => 'badVoltage', 75 => 'fruFPCReducedFabricBW', + 76 => 'fruAutoheal', 77 => 'builtinPicBounce', 78 => 'fruFabricDegraded', 79 => 'fruFPCFabricDegradedOffline', 80 => 'fruUnsupportedSlot', + 81 => 'fruRouteLocalizationMisCfg', 82 => 'fruTypeConfigMismatch', 83 => 'lccModeChanged', 84 => 'hwFault', 85 => 'fruPICOfflineOnEccErrors', + 86 => 'fruFpcIncompatible', 87 => 'fruFpcFanTrayPEMIncompatible', 88 => 'fruUnsupportedFirmware', + 89 => 'openflowConfigChange', 90 => 'fruFpcScbIncompatible', 91 => 'fruReUnresponsive' +); +my %map_fru_type = ( + 1 => 'other', 2 => 'clockGenerator', 3 => 'flexiblePicConcentrator', 4 => 'switchingAndForwardingModule', 5 => 'controlBoard', + 6 => 'routingEngine', 7 => 'powerEntryModule', 8 => 'frontPanelModule', 9 => 'switchInterfaceBoard', 10 => 'processorMezzanineBoardForSIB', + 11 => 'portInterfaceCard', 12 => 'craftInterfacePanel', 13 => 'fan', 14 => 'lineCardChassis', 15 => 'forwardingEngineBoard', + 16 => 'protectedSystemDomain', 17 => 'powerDistributionUnit', 18 => 'powerSupplyModule', 19 => 'switchFabricBoard', 20 => 'adapterCard' +); +my %fru_states = ( + 1 => ['unknown', 'UNKNOWN'], + 2 => ['empty', 'OK'], + 3 => ['present', 'OK'], + 4 => ['ready', 'OK'], + 5 => ['announce online', 'OK'], + 6 => ['online', 'OK'], + 7 => ['announce offline', 'WARNING'], + 8 => ['offline', 'CRITICAL'], + 9 => ['diagnostic', 'WARNING'], + 10 => ['standby', 'WARNING'], +); +my %operating_states = ( + 1 => ['unknown', 'UNKNOWN'], + 2 => ['running', 'OK'], + 3 => ['ready', 'OK'], + 4 => ['reset', 'WARNING'], + 5 => ['runningAtFullSpeed', 'WARNING'], + 6 => ['down', 'CRITICAL'], + 7 => ['standby', 'OK'], +); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + $self->{components_frus} = 0; + $self->{components_operating} = 0; + + $self->get_type(); + $self->check_frus(); + $self->check_operating(); + + $self->{output}->output_add(severity => 'OK', + short_msg => sprintf("All %d components [%d frus, %d operating] are ok, Environment type: %s", + ($self->{components_frus} + $self->{components_operating}), + $self->{components_frus}, $self->{components_operating}, $self->{env_type})); + + $self->{output}->display(); + $self->{output}->exit(); +} + +sub get_type { + my ($self) = @_; + + my $oid_jnxBoxDescr = ".1.3.6.1.4.1.2636.3.1.2.0"; + + my $result = $self->{snmp}->get_leef(oids => [$oid_jnxBoxDescr]); + + $self->{env_type} = defined($result->{$oid_jnxBoxDescr}) ? $result->{$oid_jnxBoxDescr} : 'unknown'; +} + +sub check_frus { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking frus"); + + my $oid_jnxFruName = '.1.3.6.1.4.1.2636.3.1.15.1.5'; + my $oid_jnxFruType = '.1.3.6.1.4.1.2636.3.1.15.1.6'; + my $oid_jnxFruState = '.1.3.6.1.4.1.2636.3.1.15.1.8'; + my $oid_jnxFruTemp = '.1.3.6.1.4.1.2636.3.1.15.1.9'; + my $oid_jnxFruOfflineReason = '.1.3.6.1.4.1.2636.3.1.15.1.10'; + + my $result = $self->{snmp}->get_table(oid => $oid_jnxFruName); + return if (scalar(keys %$result) <= 0); + + $self->{snmp}->load(oids => [$oid_jnxFruType, $oid_jnxFruState, $oid_jnxFruTemp, $oid_jnxFruOfflineReason], + instances => [keys %$result], + instance_regexp => "^" . $oid_jnxFruName . '\.(.+)'); + my $result2 = $self->{snmp}->get_leef(); + + foreach my $oid (keys %$result) { + $oid =~ /^$oid_jnxFruName\.(.+)/; + my $instance = $1; + + my $fru_name = $result->{$oid}; + my $fru_type = $result2->{$oid_jnxFruType . "." . $instance}; + my $fru_state = $result2->{$oid_jnxFruState . "." . $instance}; + my $fru_temp = $result2->{$oid_jnxFruTemp . "." . $instance}; + my $fru_offlinereason = $result2->{$oid_jnxFruOfflineReason . "." . $instance}; + + # Empty. Skip + if ($fru_state == 2) { + $self->{output}->output_add(long_msg => sprintf("Skipping fru '%s' [type: %s]: empty.", + $fru_name, $map_fru_type{$fru_type})); + next; + } + + $self->{components_frus}++; + $self->{output}->output_add(long_msg => sprintf("Fru '%s' state is %s [type: %s, offline reason: %s]", + $fru_name, ${$fru_states{$fru_state}}[0], + $map_fru_type{$fru_type}, $map_fru_offline{$fru_offlinereason})); + if (${$fru_states{$fru_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$fru_states{$fru_state}}[1], + short_msg => sprintf("Fru '%s' state is %s [offline reason: %s]", $fru_name, ${$fru_states{$fru_state}}[0], + $map_fru_offline{$fru_offlinereason})); + } + + if ($fru_temp != 0) { + $self->{output}->perfdata_add(label => 'temp_' . $fru_name, unit => 'C', + value => $fru_temp); + } + } +} + +sub check_operating { + my ($self) = @_; + + $self->{output}->output_add(long_msg => "Checking operating"); + + my $oid_jnxOperatingDescr = '.1.3.6.1.4.1.2636.3.1.13.1.5'; + my $oid_jnxOperatingState = '.1.3.6.1.4.1.2636.3.1.13.1.6'; + + my $result = $self->{snmp}->get_table(oid => $oid_jnxOperatingDescr); + return if (scalar(keys %$result) <= 0); + + $self->{snmp}->load(oids => [$oid_jnxOperatingState], + instances => [keys %$result], + instance_regexp => "^" . $oid_jnxOperatingDescr . '\.(.+)'); + my $result2 = $self->{snmp}->get_leef(); + + foreach my $oid (keys %$result) { + $oid =~ /^$oid_jnxOperatingDescr\.(.+)/; + my $instance = $1; + + my $operating_descr = $result->{$oid}; + my $operating_state = $result2->{$oid_jnxOperatingState . "." . $instance}; + + $self->{components_operating}++; + $self->{output}->output_add(long_msg => sprintf("Operating '%s' state is %s", + $operating_descr, ${$operating_states{$operating_state}}[0])); + if (${$operating_states{$operating_state}}[1] ne 'OK') { + $self->{output}->output_add(severity => ${$operating_states{$operating_state}}[1], + short_msg => sprintf("Operating '%s' state is %s", + $operating_descr, ${$operating_states{$operating_state}}[0])); + } + } +} + +1; + +__END__ + +=head1 MODE + +Check Hardware (mib-jnx-chassis) (frus, operating). + +=over 8 + +=back + +=cut + \ No newline at end of file diff --git a/centreon/lib/perl/plugins/network/juniper/common/mode/memoryforwarding.pm b/centreon/lib/perl/plugins/network/juniper/common/mode/memoryforwarding.pm new file mode 100644 index 00000000000..eb0c0c1594f --- /dev/null +++ b/centreon/lib/perl/plugins/network/juniper/common/mode/memoryforwarding.pm @@ -0,0 +1,126 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::juniper::common::mode::memoryforwarding; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_jnxJsSPUMonitoringSPUIndex = '.1.3.6.1.4.1.2636.3.39.1.12.1.1.1.3'; + my $oid_jnxJsSPUMonitoringMemoryUsage = '.1.3.6.1.4.1.2636.3.39.1.12.1.1.1.5'; + + my $result = $self->{snmp}->get_table(oid => $oid_jnxJsSPUMonitoringSPUIndex, nothing_quit => 1); + $self->{snmp}->load(oids => [$oid_jnxJsSPUMonitoringMemoryUsage], + instances => [keys %$result], + instance_regexp => '\.(\d+)$'); + my $result2 = $self->{snmp}->get_leef(nothing_quit => 1); + + foreach my $oid (keys %$result) { + $oid =~ /\.(\d+)$/; + my $instance = $1; + my $mem_usage = $result2->{$oid_jnxJsSPUMonitoringMemoryUsage . '.' . $instance}; + + my $exit_code = $self->{perfdata}->threshold_check(value => $mem_usage, + threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + $self->{output}->output_add(severity => $exit_code, + short_msg => sprintf("Memory '%d' usage is: %s%%", $instance, $mem_usage)); + $self->{output}->perfdata_add(label => 'mem_' . $instance, unit => '%', + value => $mem_usage, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning'), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical'), + min => 0, max => 100); + } + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check Memory Usage of packet forwarding engine. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/juniper/common/mode/memoryrouting.pm b/centreon/lib/perl/plugins/network/juniper/common/mode/memoryrouting.pm new file mode 100644 index 00000000000..4dd0564c901 --- /dev/null +++ b/centreon/lib/perl/plugins/network/juniper/common/mode/memoryrouting.pm @@ -0,0 +1,151 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::juniper::common::mode::memoryrouting; + +use base qw(centreon::plugins::mode); + +use strict; +use warnings; + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + + $self->{version} = '1.0'; + $options{options}->add_options(arguments => + { + "warning:s" => { name => 'warning', }, + "critical:s" => { name => 'critical', }, + }); + + return $self; +} + +sub check_options { + my ($self, %options) = @_; + $self->SUPER::init(%options); + + if (($self->{perfdata}->threshold_validate(label => 'warning', value => $self->{option_results}->{warning})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong warning threshold '" . $self->{option_results}->{warning} . "'."); + $self->{output}->option_exit(); + } + if (($self->{perfdata}->threshold_validate(label => 'critical', value => $self->{option_results}->{critical})) == 0) { + $self->{output}->add_option_msg(short_msg => "Wrong critical threshold '" . $self->{option_results}->{critical} . "'."); + $self->{output}->option_exit(); + } +} + +sub run { + my ($self, %options) = @_; + # $options{snmp} = snmp object + $self->{snmp} = $options{snmp}; + + my $oid_jnxOperatingDescr = '.1.3.6.1.4.1.2636.3.1.13.1.5'; + my $oid_jnxOperatingBuffer = '.1.3.6.1.4.1.2636.3.1.13.1.11'; + my $oid_jnxOperatingMemory = '.1.3.6.1.4.1.2636.3.1.13.1.15'; # MB + + my $result = $self->{snmp}->get_table(oid => $oid_jnxOperatingDescr, nothing_quit => 1); + my $routing_engine_find = 0; + my $oid_routing_engine; + foreach my $oid (keys %$result) { + if ($result->{$oid} =~ /routing/i) { + $routing_engine_find = 1; + $oid_routing_engine = $oid; + last; + } + } + + if ($routing_engine_find == 0) { + $self->{output}->add_option_msg(short_msg => "Cannot find operating with 'routing' in description."); + $self->{output}->option_exit(); + } + + $self->{snmp}->load(oids => [$oid_jnxOperatingBuffer, $oid_jnxOperatingMemory], + instances => [$oid_routing_engine], + instance_regexp => "^" . $oid_jnxOperatingDescr . '\.(.+)'); + my $result2 = $self->{snmp}->get_leef(); + + $oid_routing_engine =~ /^$oid_jnxOperatingDescr\.(.+)/; + my $instance = $1; + my $total_size = $result2->{$oid_jnxOperatingMemory . '.' . $instance} * 1024 * 1024; + my $prct_used = $result2->{$oid_jnxOperatingBuffer . '.' . $instance}; + my $prct_free = 100 - $prct_used; + my $memory_used = $total_size * $prct_used / 100; + my $memory_free = $total_size - $memory_used; + + my $exit = $self->{perfdata}->threshold_check(value => $prct_used, threshold => [ { label => 'critical', 'exit_litteral' => 'critical' }, { label => 'warning', exit_litteral => 'warning' } ]); + my ($total_value, $total_unit) = $self->{perfdata}->change_bytes(value => $total_size); + my ($used_value, $used_unit) = $self->{perfdata}->change_bytes(value => $memory_used); + my ($free_value, $free_unit) = $self->{perfdata}->change_bytes(value => $memory_free); + + $self->{output}->output_add(severity => $exit, + short_msg => sprintf("Memory Total: %s Used: %s (%.2f%%) Free: %s (%.2f%%)", + $total_value . " " . $total_unit, + $used_value . " " . $used_unit, $prct_used, + $free_value . " " . $free_unit, $prct_free)); + + $self->{output}->perfdata_add(label => "used", + value => $memory_used, + warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', total => $total_size), + critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical', total => $total_size), + min => 0, max => $total_size); + + $self->{output}->display(); + $self->{output}->exit(); +} + +1; + +__END__ + +=head1 MODE + +Check Memory Usage of routing engine. + +=over 8 + +=item B<--warning> + +Threshold warning in percent. + +=item B<--critical> + +Threshold critical in percent. + +=back + +=cut diff --git a/centreon/lib/perl/plugins/network/juniper/srx/plugin.pm b/centreon/lib/perl/plugins/network/juniper/srx/plugin.pm new file mode 100644 index 00000000000..ab034a2af2a --- /dev/null +++ b/centreon/lib/perl/plugins/network/juniper/srx/plugin.pm @@ -0,0 +1,73 @@ +################################################################################ +# Copyright 2005-2013 MERETHIS +# Centreon is developped by : Julien Mathis and Romain Le Merlus under +# GPL Licence 2.0. +# +# This program is free software; you can redistribute it and/or modify it under +# the terms of the GNU General Public License as published by the Free Software +# Foundation ; either version 2 of the License. +# +# 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 General Public License for more details. +# +# You should have received a copy of the GNU General Public License along with +# this program; if not, see . +# +# Linking this program statically or dynamically with other modules is making a +# combined work based on this program. Thus, the terms and conditions of the GNU +# General Public License cover the whole combination. +# +# As a special exception, the copyright holders of this program give MERETHIS +# permission to link this program with independent modules to produce an executable, +# regardless of the license terms of these independent modules, and to copy and +# distribute the resulting executable under terms of MERETHIS choice, provided that +# MERETHIS also meet, for each linked independent module, the terms and conditions +# of the license of that module. An independent module is a module which is not +# derived from this program. If you modify this program, you may extend this +# exception to your version of the program, but you are not obliged to do so. If you +# do not wish to do so, delete this exception statement from your version. +# +# For more information : contact@centreon.com +# Authors : Quentin Garnier +# +#################################################################################### + +package network::juniper::srx::plugin; + +use strict; +use warnings; +use base qw(centreon::plugins::script_snmp); + +sub new { + my ($class, %options) = @_; + my $self = $class->SUPER::new(package => __PACKAGE__, %options); + bless $self, $class; + # $options->{options} = options object + + $self->{version} = '1.0'; + %{$self->{modes}} = ( + 'hardware' => 'network::juniper::common::mode::hardware', + 'cpu-routing' => 'network::juniper::common::mode::cpurouting', # routing engine + 'cpu-forwarding' => 'network::juniper::common::mode::cpuforwarding', # packet forwarding engine + 'memory-routing' => 'network::juniper::common::mode::memoryrouting', # routing engine + 'memory-forwarding' => 'network::juniper::common::mode::memoryforwarding', # packet forwarding engine + 'cp-sessions' => 'network::juniper::common::mode::cpsessions', # CP = 'central point' + 'flow-sessions' => 'network::juniper::common::mode::flowsessions', + 'traffic' => 'snmp_standard::mode::traffic', + 'list-interfaces' => 'snmp_standard::mode::listinterfaces', + 'storage' => 'snmp_standard::mode::storage', + ); + + return $self; +} + +1; + +__END__ + +=head1 PLUGIN DESCRIPTION + +Check Juniper SRX in SNMP. + +=cut diff --git a/centreon/lib/perl/plugins/os/linux/plugin.pm b/centreon/lib/perl/plugins/os/linux/plugin.pm index 652476a7b19..9d40bc9dfe2 100644 --- a/centreon/lib/perl/plugins/os/linux/plugin.pm +++ b/centreon/lib/perl/plugins/os/linux/plugin.pm @@ -50,7 +50,7 @@ sub new { 'cpu' => 'snmp_standard::mode::cpu', 'diskio' => 'snmp_standard::mode::diskio', 'load' => 'snmp_standard::mode::loadaverage', - 'list-interfaces' => 'snmp_standard::mode::list-interfaces', + 'list-interfaces' => 'snmp_standard::mode::listinterfaces', 'memory' => 'os::linux::mode::memory', 'packet-errors' => 'snmp_standard::mode::packeterrors', 'processcount' => 'snmp_standard::mode::processcount', From 57426cf02ea4f3050bdf09a7b9cb439cf0ce861f Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Thu, 5 Dec 2013 17:09:41 +0100 Subject: [PATCH 170/458] + better output for some plugins --- centreon/lib/perl/plugins/snmp_standard/mode/storage.pm | 5 ++++- centreon/lib/perl/plugins/storage/netapp/mode/filesys.pm | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm index fce10cd0339..5a9873bc12d 100644 --- a/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm +++ b/centreon/lib/perl/plugins/snmp_standard/mode/storage.pm @@ -179,7 +179,10 @@ sub run { my $extra_label = ''; $extra_label = '_' . $name_storage if (!defined($self->{option_results}->{storage}) || defined($self->{option_results}->{use_regexp})); my %total_options = (); - $total_options{total} = $total_size if ($self->{option_results}->{units} eq '%'); + if ($self->{option_results}->{units} eq '%') { + $total_options{total} = $total_size; + $total_options{cast_int} = 1; + } $self->{output}->perfdata_add(label => $label . $extra_label, unit => 'o', value => $value_perf, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', %total_options), diff --git a/centreon/lib/perl/plugins/storage/netapp/mode/filesys.pm b/centreon/lib/perl/plugins/storage/netapp/mode/filesys.pm index 68666e9aec3..9ad90abdd1c 100644 --- a/centreon/lib/perl/plugins/storage/netapp/mode/filesys.pm +++ b/centreon/lib/perl/plugins/storage/netapp/mode/filesys.pm @@ -200,7 +200,10 @@ sub run { my $extra_label = ''; $extra_label = '_' . $name if (!defined($self->{option_results}->{name}) || defined($self->{option_results}->{use_regexp})); my %total_options = (); - $total_options{total} = $total_size if ($self->{option_results}->{units} eq '%'); + if ($self->{option_results}->{units} eq '%') { + $total_options{total} = $total_size; + $total_options{cast_int} = 1; + } $self->{output}->perfdata_add(label => $label . $extra_label, unit => 'o', value => $value_perf, warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning', %total_options), From 2dc6d81a97e9bcfd4b3cba8c90548434a76bccb3 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 6 Dec 2013 16:19:46 +0100 Subject: [PATCH 171/458] + Minor fix issue in options --- centreon/lib/perl/centreon/script/centFillTrapDB.pm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script/centFillTrapDB.pm b/centreon/lib/perl/centreon/script/centFillTrapDB.pm index fd7002077c1..7a7f5d768ad 100644 --- a/centreon/lib/perl/centreon/script/centFillTrapDB.pm +++ b/centreon/lib/perl/centreon/script/centFillTrapDB.pm @@ -48,7 +48,7 @@ sub new { bless $self, $class; $self->add_options( - "f=s" => \$self->{opt_f}, "file" => \$self->{opt_f}, + "f=s" => \$self->{opt_f}, "file=s" => \$self->{opt_f}, "m=s" => \$self->{opt_m}, "man=s" => \$self->{opt_m} ); return $self; From 140585537424aa2e2a43ef9385516717c01ec810 Mon Sep 17 00:00:00 2001 From: Quentin Garnier Date: Fri, 6 Dec 2013 17:46:59 +0100 Subject: [PATCH 172/458] + Begin working on migrate of snmpconvertmib --- .../perl/centreon/script/centFillTrapDB.pm | 621 +++++++++++++++++- 1 file changed, 620 insertions(+), 1 deletion(-) diff --git a/centreon/lib/perl/centreon/script/centFillTrapDB.pm b/centreon/lib/perl/centreon/script/centFillTrapDB.pm index 7a7f5d768ad..3dd498254b4 100644 --- a/centreon/lib/perl/centreon/script/centFillTrapDB.pm +++ b/centreon/lib/perl/centreon/script/centFillTrapDB.pm @@ -47,13 +47,52 @@ sub new { ); bless $self, $class; + + $self->{no_description} = 0; + $self->{no_variables} = 0; + $self->{no_format_summary} = 0; + $self->{no_format_desc} = 0; + $self->{format} = 0; + $self->{format_desc} = 0; + $self->{no_desc_wildcard} = 0; + $self->{no_severity} = 0; + $self->{severity} = 'Normal'; + + # Set this to 1 to have the --TYPE string prepended to the --SUMMARY string. + # Set to 0 to disable + $self->{prepend_type} = 1; + $self->{net_snmp_perl} = 0; + $self->{total_translations} = 0; + $self->{successful_translations} = 0; + $self->{failed_translations} = 0; + $self->add_options( "f=s" => \$self->{opt_f}, "file=s" => \$self->{opt_f}, "m=s" => \$self->{opt_m}, "man=s" => \$self->{opt_m} ); + return $self; } +sub check_snmptranslate_version { + my $self = shift; + $self->{snmptranslate_use_On} = 1; + + if (open SNMPTRANSLATE, "snmptranslate -V 2>&1|") { + my $snmptranslatever = ; + close SNMPTRANSLATE; + + chomp ($snmptranslatever); + + print "snmptranslate version: " . $snmptranslatever. "\n"; + + if ($snmptranslatever =~ /UCD/i || $snmptranslatever =~ /NET-SNMP version: 5.0.1/i) { + $self->{snmptranslate_use_On} = 0; + $self->{logger}->writeLogDebug("snmptranslate is either UCD-SNMP, or NET-SNMP v5.0.1, so do not use the -On switch. Version found: $snmptranslatever"); + } + } +} + ######################################### ## TEST IF OID ALREADY EXISTS IN DATABASE # @@ -101,9 +140,589 @@ sub main { my $manuf = $self->{opt_m}; if (!open(FILE, $self->{opt_f})) { - $self->{logger}->writeLogError("Cannot open configuration file : $self->{opt_f}"); + $self->{logger}->writeLogError("Cannot get mib file : $self->{opt_f}"); exit(1); } + + # From snmpconvertmib + # Copyright 2002-2013 Alex Burger + # alex_b@users.sourceforge.net + + $self->check_snmptranslate_version(); + my @mibfile; + while () { + chomp; # remove at end of line + s/\015//; # Remove any DOS carriage returns + push(@mibfile, $_); # add to each line to @trapconf array + } + + my $currentline = 0; + # A mib file can contain multiple BEGIN definitions. This finds the first one + # to make sure we have at least one definition. + # Determine name of MIB file + my $mib_name = ''; + while ($currentline <= $#mibfile) { + my $line = $mibfile[$currentline]; + + # Sometimes DEFINITIONS ::= BEGIN will appear on the line following the mib name. + # Look for DEFINITIONS ::= BEGIN with nothing (white space allowed) around it and a previous line with + # only a single word with whitespace around it. + if ($currentline > 0 && $line =~ /^\s*DEFINITIONS\s*::=\s*BEGIN\s*$/ && $mibfile[$currentline-1] =~ /^\s*(\S+)\s*$/) { + # We should have found the mib name + $mib_name = $1; + $self->{logger}->writeLogInfo("Split line DEFINITIONS ::= BEGIN found ($1)."); + $mib_name =~ s/\s+//g; + last; + } elsif ($line =~ /(.*)DEFINITIONS\s*::=\s*BEGIN/) { + $mib_name = $1; + $mib_name =~ s/\s+//g; + last; + } + $currentline++; + } + $self->{logger}->writeLogInfo("mib name: $mib_name"); + if ($mib_name eq '') { + $self->{logger}->writeLogError("Could not find DEFINITIONS ::= BEGIN statement in MIB file!"); + exit (1); + } + + while ($currentline <= $#mibfile) { + my $line = $mibfile[$currentline]; + + # Sometimes DEFINITIONS ::= BEGIN will appear on the line following the mib name. + # Look for DEFINITIONS ::= BEGIN with nothing (white space allowed) around it and a previous line with + # only a single word with whitespace around it. + if ($currentline > 0 && $line =~ /^\s*DEFINITIONS\s*::=\s*BEGIN\s*$/ && $mibfile[$currentline-1] =~ /^\s*(\S+)\s*$/) { + # We should have found the mib name + print "\n\nSplit line DEFINITIONS ::= BEGIN found ($1).\n"; + + $mib_name = $1; + $mib_name =~ s/\s+//g; + print "Processing MIB: $mib_name\n"; + + $currentline++; # Increment to the next line + next; + } elsif ($line =~ /(.*)DEFINITIONS\s*::=\s*BEGIN/) { + $mib_name = $1; + $mib_name =~ s/\s+//g; + print "\n\nProcessing MIB: $mib_name\n"; + + $currentline++; # Increment to the next line + next; + } + + # TRAP-TYPE (V1) / NOTIFICATION-TYPE (V2) + # + # eg: 'mngmtAgentTrap-23003 TRAP-TYPE'; + # eg: 'ciscoSystemClockChanged NOTIFICATION-TYPE'; + if ($line =~ /(.*)\s*TRAP-TYPE.*/ || + $line =~ /(.*)\s*(?