]> git.uio.no Git - check_openmanage.git/blob - check_openmanage
jau
[check_openmanage.git] / check_openmanage
1 #!/usr/bin/perl
2 #
3 # Nagios plugin
4 #
5 # Monitor Dell server hardware status using Dell OpenManage Server
6 # Administrator, either locally via NRPE, or remotely via SNMP.
7 #
8 # $Id$
9 #
10 # Copyright (C) 2009 Trond H. Amundsen
11 #
12 # This program is free software: you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation, either version 3 of the License, or
15 # (at your option) any later version.
16 #
17 # This program is distributed in the hope that it will be useful, but
18 # WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 # General Public License for more details.
21 #
22 # You should have received a copy of the GNU General Public License
23 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 #
25
26 require 5.006;  # Perl v5.6.0 or newer is required
27 use strict;
28 use warnings;
29 use POSIX qw(isatty ceil);
30 use Getopt::Long qw(:config no_ignore_case);
31
32 # Global (package) variables used throughout the code
33 use vars qw( $NAME $VERSION $AUTHOR $CONTACT $E_OK $E_WARNING $E_CRITICAL
34              $E_UNKNOWN $FW_LOCK $USAGE $HELP $LICENSE
35              $snmp_session $snmp_error $omreport $globalstatus $global
36              $linebreak $omopt_chassis $omopt_system $blade
37              $exit_code $snmp
38              %check %opt %perfdata %reverse_exitcode %status2nagios
39              %snmp_status %snmp_probestatus %probestatus2nagios %sysinfo
40              %blacklist %nagios_alert_count %count
41              @controllers @enclosures
42              @report_storage @report_chassis @report_other
43           );
44
45 #---------------------------------------------------------------------
46 # Initialization and global variables
47 #---------------------------------------------------------------------
48
49 # If we don't have a TTY, the plugin is probably run by Nagios. In
50 # that case, redirect all output to STDERR to STDOUT. Nagios ignores
51 # output to STDERR.
52 if (! isatty *STDOUT) {
53     open STDERR, '>&', 'STDOUT'
54       or do { print "ERROR: Couldn't redirect STDERR to STDOUT\n"; exit 2; }
55 }
56
57 # Version and similar info
58 $NAME    = 'check_openmanage';
59 $VERSION = '3.5.0-beta14';
60 $AUTHOR  = 'Trond H. Amundsen';
61 $CONTACT = 't.h.amundsen@usit.uio.no';
62
63 # Exit codes
64 $E_OK       = 0;
65 $E_WARNING  = 1;
66 $E_CRITICAL = 2;
67 $E_UNKNOWN  = 3;
68
69 # Firmware update lock file [FIXME: location on Windows?]
70 $FW_LOCK = '/var/lock/.spsetup';  # default on Linux
71
72 # Usage text
73 $USAGE = <<"END_USAGE";
74 Usage: $NAME [OPTION]...
75 END_USAGE
76
77 # Help text
78 $HELP = <<'END_HELP';
79
80 GENERAL OPTIONS:
81
82    -p, --perfdata      Output performance data
83    -t, --timeout       Plugin timeout in seconds
84    -c, --critical      Customise temperature critical limits
85    -w, --warning       Customise temperature warning limits
86    -d, --debug         Debug output, reports everything
87    -h, --help          Display this help text
88    -V, --version       Display version info
89
90 SNMP OPTIONS:
91
92    -H, --hostname      Hostname or IP of the server (needed for SNMP)
93    -C, --community     SNMP community string
94    -P, --protocol      SNMP protocol version
95    --port              SNMP port number
96
97 OUTPUT OPTIONS:
98
99    -i, --info          Prefix any alerts with the service tag
100    -e, --extinfo       Append system info to alerts
101    -s, --state         Prefix alerts with alert state
102    --short-state       Prefix alerts with alert state (abbreviated)
103    -o, --okinfo        Verbosity when check result is OK
104    --htmlinfo          HTML output with clickable links
105
106 CHECK CONTROL AND BLACKLISTING:
107
108    -a, --all           Check everything, even log content
109    -b, --blacklist     Blacklist missing and/or failed components
110    --only              Only check a certain component or alert type
111    --check             Fine-tune which components are checked
112
113 For more information and advanced options, see the manual page or URL:
114   http://folk.uio.no/trondham/software/check_openmanage.html
115 END_HELP
116
117 # Version and license text
118 $LICENSE = <<"END_LICENSE";
119 $NAME $VERSION
120 Copyright (C) 2009 $AUTHOR
121 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
122 This is free software: you are free to change and redistribute it.
123 There is NO WARRANTY, to the extent permitted by law.
124
125 Written by $AUTHOR <$CONTACT>
126 END_LICENSE
127
128 # Options with default values
129 %opt = ( 'blacklist'         => [],
130          'check'             => [],
131          'critical'          => [],
132          'warning'           => [],
133          'timeout'           => 30,  # default timeout is 30 seconds
134          'debug'             => 0,
135          'help'              => 0,
136          'perfdata'          => undef,
137          'info'              => 0,
138          'extinfo'           => 0,
139          'htmlinfo'          => undef,
140          'postmsg'           => undef,
141          'state'             => 0,
142          'short-state'       => 0,
143          'okinfo'            => 0,   # default "ok" output level
144          'linebreak'         => undef,
145          'version'           => 0,
146          'all'               => 0,
147          'only'              => undef,
148          'omreport'          => undef,
149          'port'              => 161, # default SNMP port
150          'hostname'          => undef,
151          'community'         => 'public',  # SMNP v1 or v2c
152          'protocol'          => 2,
153          'username'          => undef, # SMNP v3
154          'authpassword'      => undef, # SMNP v3
155          'authkey'           => undef, # SMNP v3
156          'authprotocol'      => undef, # SMNP v3
157          'privpassword'      => undef, # SMNP v3
158          'privkey'           => undef, # SMNP v3
159          'privprotocol'      => undef, # SMNP v3
160        );
161
162 # Get options
163 GetOptions('b|blacklist=s'      => \@{ $opt{blacklist} },
164            'check=s'            => \@{ $opt{check} },
165            'c|critical=s'       => \@{ $opt{critical} },
166            'w|warning=s'        => \@{ $opt{warning} },
167            't|timeout=i'        => \$opt{timeout},
168            'd|debug'            => \$opt{debug},
169            'h|help'             => \$opt{help},
170            'V|version'          => \$opt{version},
171            'p|perfdata:s'       => \$opt{perfdata},
172            'i|info'             => \$opt{info},
173            'e|extinfo'          => \$opt{extinfo},
174            'htmlinfo:s'         => \$opt{htmlinfo},
175            'postmsg=s'          => \$opt{postmsg},
176            's|state'            => \$opt{state},
177            'short-state'        => \$opt{shortstate},
178            'o|ok-info=i'        => \$opt{okinfo},
179            'l|linebreak=s'      => \$opt{linebreak},
180            'a|all'              => \$opt{all},
181            'only=s'             => \$opt{only},
182            'omreport=s'         => \$opt{omreport},
183            'port=i'             => \$opt{port},
184            'H|hostname=s'       => \$opt{hostname},
185            'C|community=s'      => \$opt{community},
186            'P|protocol=i'       => \$opt{protocol},
187            'U|username=s'       => \$opt{username},
188            'authpassword=s'     => \$opt{authpassword},
189            'authkey=s'          => \$opt{authkey},
190            'authprotocol=s'     => \$opt{authprotocol},
191            'privpassword=s'     => \$opt{privpassword},
192            'privkey=s'          => \$opt{privkey},
193            'privprotocol=s'     => \$opt{privprotocol},
194           ) or do { print $USAGE; exit $E_UNKNOWN };
195
196 # If user requested help
197 if ($opt{help}) {
198     print $USAGE, $HELP;
199     exit $E_OK;
200 }
201
202 # If user requested version info
203 if ($opt{version}) {
204     print $LICENSE;
205     exit $E_OK;
206 }
207
208 # Setting timeout
209 $SIG{ALRM} = sub {
210     print "PLUGIN TIMEOUT: $NAME timed out after $opt{timeout} seconds\n";
211     exit $E_UNKNOWN;
212 };
213 alarm $opt{timeout};
214
215 # If we're using SNMP
216 $snmp = defined $opt{hostname} ? 1 : 0;
217
218 # SNMP session variables
219 $snmp_session = undef;
220 $snmp_error   = undef;
221
222 # The omreport command
223 $omreport = undef;
224
225 # Check flags, override available with the --check option
226 %check = ( 'storage'     => 1,   # check storage subsystem
227            'memory'      => 1,   # check memory (dimms)
228            'fans'        => 1,   # check fan status
229            'power'       => 1,   # check power supplies
230            'temp'        => 1,   # check temperature
231            'cpu'         => 1,   # check processors
232            'voltage'     => 1,   # check voltage
233            'batteries'   => 1,   # check battery probes
234            'amperage'    => 1,   # check power consumption
235            'intrusion'   => 1,   # check intrusion detection
236            'alertlog'    => 0,   # check the alert log
237            'esmlog'      => 0,   # check the ESM log (hardware log)
238            'esmhealth'   => 1,   # check the ESM log overall health
239          );
240
241 # Default line break
242 $linebreak = isatty(*STDOUT) ? "\n" : '<br/>';
243
244 # Line break from option
245 if (defined $opt{linebreak}) {
246     if ($opt{linebreak} eq 'REG') {
247         $linebreak = "\n";
248     }
249     elsif ($opt{linebreak} eq 'HTML') {
250         $linebreak = '<br/>';
251     }
252     else {
253         $linebreak = $opt{linebreak};
254     }
255 }
256
257 # Exit with status=UNKNOWN if there is firmware upgrade in progress
258 if (!$snmp && -f $FW_LOCK) {
259     print "MONITORING DISABLED - Firmware update in progress ($FW_LOCK exists)\n";
260     exit $E_UNKNOWN;
261 }
262
263 # List of controllers and enclosures
264 @controllers = ();  # controllers
265 @enclosures  = ();  # enclosures
266
267 # Messages
268 @report_storage = ();  # messages with associated nagios level (storage)
269 @report_chassis = ();  # messages with associated nagios level (chassis)
270 @report_other   = ();  # messages with associated nagios level (other)
271
272 # Counters for everything
273 %count
274   = (
275      'pdisk'  => 0, # number of physical disks
276      'vdisk'  => 0, # number of logical drives (virtual disks)
277      'temp'   => 0, # number of temperature probes
278      'volt'   => 0, # number of voltage probes
279      'amp'    => 0, # number of amperage probes
280      'intr'   => 0, # number of intrusion probes
281      'dimm'   => 0, # number of memory modules
282      'fan'    => 0, # number of fan probes
283      'cpu'    => 0, # number of CPUs
284      'bat'    => 0, # number of batteries
285      'power'  => 0, # number of power supplies
286      'esm'    => {
287                   'Critical'     => 0, # critical entries in ESM log
288                   'Non-Critical' => 0, # warning entries in ESM log
289                   'Ok'           => 0, # ok entries in ESM log
290                  },
291      'alert'  => {
292                   'Critical'     => 0, # critical entries in alert log
293                   'Non-Critical' => 0, # warning entries in alert log
294                   'Ok'           => 0, # ok entries in alert log
295                  },
296     );
297
298 # Performance data
299 %perfdata = ();
300
301 # Global health status
302 $global         = 1;      # default is to check global status
303 $globalstatus   = $E_OK;  # default global health status is "OK"
304
305 # Nagios error levels reversed
306 %reverse_exitcode
307   = (
308      $E_OK       => 'OK',
309      $E_WARNING  => 'WARNING',
310      $E_CRITICAL => 'CRITICAL',
311      $E_UNKNOWN  => 'UNKNOWN',
312     );
313
314 # OpenManage (omreport) and SNMP error levels
315 %status2nagios
316   = (
317      'Unknown'         => $E_CRITICAL,
318      'Critical'        => $E_CRITICAL,
319      'Non-Critical'    => $E_WARNING,
320      'Ok'              => $E_OK,
321      'Non-Recoverable' => $E_CRITICAL,
322      'Other'           => $E_CRITICAL,
323     );
324
325 # Status via SNMP
326 %snmp_status
327   = (
328      1 => 'Other',
329      2 => 'Unknown',
330      3 => 'Ok',
331      4 => 'Non-Critical',
332      5 => 'Critical',
333      6 => 'Non-Recoverable',
334     );
335
336 # Probe Status via SNMP
337 %snmp_probestatus
338   = (
339      1  => 'Other',               # probe status is not one of the following:
340      2  => 'Unknown',             # probe status is unknown (not known or monitored)
341      3  => 'Ok',                  # probe is reporting a value within the thresholds
342      4  => 'nonCriticalUpper',    # probe has crossed upper noncritical threshold
343      5  => 'criticalUpper',       # probe has crossed upper critical threshold
344      6  => 'nonRecoverableUpper', # probe has crossed upper non-recoverable threshold
345      7  => 'nonCriticalLower',    # probe has crossed lower noncritical threshold
346      8  => 'criticalLower',       # probe has crossed lower critical threshold
347      9  => 'nonRecoverableLower', # probe has crossed lower non-recoverable threshold
348      10 => 'failed',              # probe is not functional
349     );
350
351 # Probe status translated to Nagios alarm levels
352 %probestatus2nagios
353   = (
354      'Other'               => $E_CRITICAL,
355      'Unknown'             => $E_CRITICAL,
356      'Ok'                  => $E_OK,
357      'nonCriticalUpper'    => $E_WARNING,
358      'criticalUpper'       => $E_CRITICAL,
359      'nonRecoverableUpper' => $E_CRITICAL,
360      'nonCriticalLower'    => $E_WARNING,
361      'criticalLower'       => $E_CRITICAL,
362      'nonRecoverableLower' => $E_CRITICAL,
363      'failed'              => $E_CRITICAL,
364     );
365
366 # System information gathered
367 %sysinfo
368   = (
369      'bios'     => 'N/A',  # BIOS version
370      'biosdate' => 'N/A',  # BIOS release date
371      'serial'   => 'N/A',  # serial number (service tag)
372      'model'    => 'N/A',  # system model
373      'osname'   => 'N/A',  # OS name
374      'osver'    => 'N/A',  # OS version
375      'om'       => 'N/A',  # OMSA version
376      'bmc'      => 0,      # HAS baseboard management controller (BMC)
377      'rac'      => 0,      # HAS remote access controller (RAC)
378      'rac_name' => 'N/A',  # remote access controller (RAC)
379      'bmc_fw'   => 'N/A',  # BMC firmware
380      'rac_fw'   => 'N/A',  # RAC firmware
381     );
382
383 # Adjust which checks to perform
384 adjust_checks() if defined $opt{check};
385
386 # Blacklisted components
387 %blacklist = defined $opt{blacklist} ? %{ get_blacklist() } : ();
388
389 # If blacklisting is in effect, don't check global health status
390 if (scalar keys %blacklist > 0) {
391     $global = 0;
392 }
393
394 # Take into account new hardware and blades
395 $omopt_chassis = 'chassis';  # default "chassis" option to omreport
396 $omopt_system  = 'system';   # default "system" option to omreport
397 $blade         = 0;          # if this is a blade system
398
399 # Some initializations and checking before we begin
400 if ($snmp) {
401     snmp_initialize();    # initialize SNMP
402     snmp_check();         # check that SNMP works
403     snmp_detect_blade();  # detect blade via SNMP
404 }
405 else {
406     # Find the omreport binary
407     find_omreport();
408     # Check help output from omreport, see which options are available.
409     # Also detecting blade via omreport.
410     check_omreport_options();
411 }
412
413
414 #---------------------------------------------------------------------
415 # Helper functions
416 #---------------------------------------------------------------------
417
418 #
419 # Store a message in one of the message arrays
420 #
421 sub report {
422     my ($type, $msg, $exval, $id) = @_;
423     defined $id or $id = q{};
424
425     my %type2array
426       = (
427          'storage' => \@report_storage,
428          'chassis' => \@report_chassis,
429          'other'   => \@report_other,
430         );
431
432     return push @{ $type2array{$type} }, [ $msg, $exval, $id ];
433 }
434
435
436 #
437 # Run command, put resulting output lines in an array and return a
438 # pointer to that array
439 #
440 sub run_command {
441     my $command = shift;
442
443     open my $CMD, '-|', $command
444       or do { report('other', "Couldn't run command '$command': $!", $E_UNKNOWN)
445                 and return [] };
446     my @lines = <$CMD>;
447     close $CMD
448       or do { report('other', "Couldn't close filehandle for command '$command': $!", $E_UNKNOWN)
449                 and return \@lines };
450     return \@lines;
451 }
452
453 #
454 # Run command, put resulting output in a string variable and return it
455 #
456 sub slurp_command {
457     my $command = shift;
458
459     open my $CMD, '-|', $command
460       or do { report('other', "Couldn't run command '$command': $!", $E_UNKNOWN) and return };
461     my $rawtext = do { local $/ = undef; <$CMD> }; # slurping
462     close $CMD;
463
464     # NOTE: We don't check the return value of close() since omreport
465     # does something weird sometimes.
466
467     return $rawtext;
468 }
469
470 #
471 # Initialize SNMP
472 #
473 sub snmp_initialize {
474     # Legal SNMP v3 protocols
475     my $snmp_v3_privprotocol = qr{\A des|aes|aes128|3des|3desde \z}xms;
476     my $snmp_v3_authprotocol = qr{\A md5|sha \z}xms;
477
478     # Parameters to Net::SNMP->session()
479     my %param
480       = (
481          '-port'     => $opt{port},
482          '-hostname' => $opt{hostname},
483          '-version'  => $opt{protocol},
484         );
485
486     # Parameters for SNMP v3
487     if ($opt{protocol} == 3) {
488
489         # Username is mandatory
490         if (defined $opt{username}) {
491             $param{'-username'} = $opt{username};
492         }
493         else {
494             print "SNMP ERROR: With SNMPv3 the username must be specified\n";
495             exit $E_UNKNOWN;
496         }
497
498         # Authpassword is optional
499         if (defined $opt{authpassword}) {
500             $param{'-authpassword'} = $opt{authpassword};
501         }
502
503         # Authkey is optional
504         if (defined $opt{authkey}) {
505             $param{'-authkey'} = $opt{authkey};
506         }
507
508         # Privpassword is optional
509         if (defined $opt{privpassword}) {
510             $param{'-privpassword'} = $opt{privpassword};
511         }
512
513         # Privkey is optional
514         if (defined $opt{privkey}) {
515             $param{'-privkey'} = $opt{privkey};
516         }
517
518         # Privprotocol is optional
519         if (defined $opt{privprotocol}) {
520             if ($opt{privprotocol} =~ m/$snmp_v3_privprotocol/xms) {
521                 $param{'-privprotocol'} = $opt{privprotocol};
522             }
523             else {
524                 print "SNMP ERROR: Unknown privprotocol '$opt{privprotocol}', "
525                   . "must be one of [des|aes|aes128|3des|3desde]\n";
526                 exit $E_UNKNOWN;
527             }
528         }
529
530         # Authprotocol is optional
531         if (defined $opt{authprotocol}) {
532             if ($opt{authprotocol} =~ m/$snmp_v3_authprotocol/xms) {
533                 $param{'-authprotocol'} = $opt{authprotocol};
534             }
535             else {
536                 print "SNMP ERROR: Unknown authprotocol '$opt{authprotocol}', "
537                   . "must be one of [md5|sha]\n";
538                 exit $E_UNKNOWN;
539             }
540         }
541     }
542     # Parameters for SNMP v2c or v1
543     elsif ($opt{protocol} == 2 or $opt{protocol} == 1) {
544         $param{'-community'} = $opt{community};
545     }
546     else {
547         print "SNMP ERROR: Unknown SNMP version '$opt{protocol}'\n";
548         exit $E_UNKNOWN;
549     }
550
551     # Try to initialize the SNMP session
552     if ( eval { require Net::SNMP; 1 } ) {
553         ($snmp_session, $snmp_error) = Net::SNMP->session( %param );
554         if (!defined $snmp_session) {
555             printf "SNMP: %s\n", $snmp_error;
556             exit $E_UNKNOWN;
557         }
558     }
559     else {
560         print "You need perl module Net::SNMP to run $NAME in SNMP mode\n";
561         exit $E_UNKNOWN;
562     }
563     return;
564 }
565
566 #
567 # Checking if SNMP works by probing for "chassisModelName", which all
568 # servers should have
569 #
570 sub snmp_check {
571     my $chassisModelName = '1.3.6.1.4.1.674.10892.1.300.10.1.9.1';
572     my $result = $snmp_session->get_request(-varbindlist => [$chassisModelName]);
573
574     # Typically if remote host isn't responding
575     if (!defined $result) {
576         printf "SNMP CRITICAL: %s\n", $snmp_session->error;
577         exit $E_CRITICAL;
578     }
579
580     # If OpenManage isn't installed or is not working
581     if ($result->{$chassisModelName} =~ m{\A noSuch (Instance|Object) \z}xms) {
582         print "ERROR: (SNMP) OpenManage is not installed or is not working correctly\n";
583         exit $E_UNKNOWN;
584     }
585     return;
586 }
587
588 #
589 # Detecting blade via SNMP
590 #
591 sub snmp_detect_blade {
592     my $DellBaseBoardType = '1.3.6.1.4.1.674.10892.1.300.80.1.7.1.1';
593     my $result = $snmp_session->get_request(-varbindlist => [$DellBaseBoardType]);
594
595     # Identify blade. Older models (4th and 5th gen models) and/or old
596     # OMSA (4.x) don't have this OID. If we get "noSuchInstance" or
597     # similar, we assume that this isn't a blade
598     if ($result->{$DellBaseBoardType} eq '3') {
599         $blade = 1;
600     }
601     return;
602 }
603
604 #
605 # Locate the omreport binary
606 #
607 sub find_omreport {
608     # If user has specified path to omreport
609     if (defined $opt{omreport} and -x $opt{omreport}) {
610         $omreport = $opt{omreport};
611         return;
612     }
613
614     # Possible full paths for omreport
615     my @omreport_paths
616       = (
617          '/usr/bin/omreport',                            # default on Linux
618          '/opt/dell/srvadmin/oma/bin/omreport.sh',       # alternate on Linux
619          '/opt/dell/srvadmin/oma/bin/omreport',          # alternate on Linux
620          'C:\Program Files (x86)\Dell\SysMgt\oma\bin\omreport.exe', # default on Windows x64
621          'C:\Program Files\Dell\SysMgt\oma\bin\omreport.exe',       # default on Windows x32
622          'c:\progra~1\dell\sysmgt\oma\bin\omreport.exe', # 8bit legacy default on Windows x32
623          'c:\progra~2\dell\sysmgt\oma\bin\omreport.exe', # 8bit legacy default on Windows x64
624         );
625
626     # Find the one to use
627   OMREPORT_PATH:
628     foreach my $bin (@omreport_paths) {
629         if (-x $bin) {
630             $omreport = $bin;
631             last OMREPORT_PATH;
632         }
633     }
634
635     # Exit with status=UNKNOWN if OM is not installed, or we don't
636     # have permission to execute the binary
637     if (!defined $omreport) {
638         print "ERROR: Dell OpenManage Server Administrator (OMSA) is not installed\n";
639         exit $E_UNKNOWN;
640     }
641     return;
642 }
643
644 #
645 # Checks output from 'omreport -?' and searches for arguments to
646 # omreport, to accommodate deprecated options "chassis" and "system"
647 # (on newer hardware), as well as blade servers.
648 #
649 sub check_omreport_options {
650     foreach (@{ run_command("$omreport -? 2>&1") }) {
651        if (m/\A servermodule /xms) {
652            # If "servermodule" argument to omreport exists, use it
653            # instead of argument "system"
654            $omopt_system = 'servermodule';
655        }
656        elsif (m/\A mainsystem /xms) {
657            # If "mainsystem" argument to omreport exists, use it
658            # instead of argument "chassis"
659            $omopt_chassis = 'mainsystem';
660        }
661        elsif (m/\A modularenclosure /xms) {
662            # If "modularenclusure" argument to omreport exists, assume
663            # that this is a blade
664            $blade = 1;
665        }
666     }
667     return;
668 }
669
670 #
671 # Read the blacklist option and return a hash containing the
672 # blacklisted components
673 #
674 sub get_blacklist {
675     my @bl = ();
676     my %blacklist = ();
677
678     if (scalar @{ $opt{blacklist} } >= 0) {
679         foreach my $black (@{ $opt{blacklist} }) {
680             my $tmp = q{};
681             if (-f $black) {
682                 open my $BL, '<', $black
683                   or do { report('other', "Couldn't open blacklist file $black: $!", $E_UNKNOWN)
684                             and return {} };
685                 $tmp = <$BL>;
686                 close $BL;
687                 chomp $tmp;
688             }
689             else {
690                 $tmp = $black;
691             }
692             push @bl, $tmp;
693         }
694     }
695
696     return {} if $#bl < 0;
697
698     # Parse blacklist string, put in hash
699     foreach my $black (@bl) {
700         my @comps = split m{/}xms, $black;
701         foreach my $c (@comps) {
702             next if $c !~ m/=/xms;
703             my ($key, $val) = split /=/xms, $c;
704             my @vals = split /,/xms, $val;
705             $blacklist{$key} = \@vals;
706         }
707     }
708
709     return \%blacklist;
710 }
711
712 #
713 # Read the check option and adjust the hash %check, which is a rough
714 # list of components to be checked
715 #
716 sub adjust_checks {
717     my @cl = ();
718
719     # Adjust checking based on the '--all' option
720     if ($opt{all}) {
721         # Check option usage
722         if (defined $opt{only} and $opt{only} !~ m{\A critical|warning \z}xms) {
723             print qq{ERROR: Wrong simultaneous usage of the "--all" and "--only" options\n};
724             exit $E_UNKNOWN;
725         }
726         if (scalar @{ $opt{check} } > 0) {
727             print qq{ERROR: Wrong simultaneous usage of the "--all" and "--check" options\n};
728             exit $E_UNKNOWN;
729         }
730
731         # set the check hash to check everything
732         map { $_ = 1 } values %check;
733
734         return;
735     }
736
737     # Adjust checking based on the '--only' option
738     if (defined $opt{only} and $opt{only} !~ m{\A critical|warning \z}xms) {
739         # Check option usage
740         if (scalar @{ $opt{check} } > 0) {
741             print qq{ERROR: Wrong simultaneous usage of the "--only" and "--check" options\n};
742             exit $E_UNKNOWN;
743         }
744         if (! exists $check{$opt{only}} and $opt{only} ne 'chassis') {
745             print qq{ERROR: "$opt{only}" is not a known keyword for the "--only" option\n};
746             exit $E_UNKNOWN;
747         }
748
749         # reset the check hash
750         map { $_ = 0 } values %check;
751
752         # adjust the check hash
753         if ($opt{only} eq 'chassis') {
754             map { $check{$_} = 1 } qw(memory fans power temp cpu voltage
755                                       batteries amperage intrusion esmhealth);
756         }
757         else {
758             $check{$opt{only}} = 1;
759         }
760
761         return;
762     }
763
764     # Adjust checking based on the '--check' option
765     if (scalar @{ $opt{check} } >= 0) {
766         foreach my $check (@{ $opt{check} }) {
767             my $tmp = q{};
768             if (-f $check) {
769                 open my $CL, '<', $check
770                   or do { report('other', "Couldn't open check file $check: $!", $E_UNKNOWN) and return };
771                 $tmp = <$CL>;
772                 close $CL;
773             }
774             else {
775                 $tmp = $check;
776             }
777             push @cl, $tmp;
778         }
779     }
780
781     return if $#cl < 0;
782
783     # Parse checklist string, put in hash
784     foreach my $check (@cl) {
785         my @checks = split /,/xms, $check;
786         foreach my $c (@checks) {
787             next if $c !~ m/=/xms;
788             my ($key, $val) = split /=/xms, $c;
789             $check{$key} = $val;
790         }
791     }
792
793     # Check if we should check global health status
794   CHECK_KEY:
795     foreach (keys %check) {
796         next CHECK_KEY if $_ eq 'esmlog';   # not part of global status
797         next CHECK_KEY if $_ eq 'alertlog'; # not part of global status
798
799         if ($check{$_} == 0) { # found something with checking turned off
800             $global = 0;
801             last CHECK_KEY;
802         }
803     }
804
805     return;
806 }
807
808 #
809 # Runs omreport and returns an array of anonymous hashes containing
810 # the output.
811 # Takes one argument: string containing parameters to omreport
812 #
813 sub run_omreport {
814     my $command = shift;
815     my @output  = ();
816     my @keys    = ();
817
818     # Errors that are OK. Some low-end poweredge (and blades) models
819     # don't have RAID controllers, intrusion detection sensor, or
820     # redundant/instrumented power supplies etc.
821     my $ok_errors
822       = qr{
823             Intrusion\sinformation\sis\snot\sfound\sfor\sthis\ssystem  # No intrusion probe
824           | No\sinstrumented\spower\ssupplies\sfound\son\sthis\ssystem # No instrumented PS (blades/low-end)
825           | No\scontrollers\sfound                                     # No RAID controller
826           | No\sbattery\sprobes\sfound\son\sthis\ssystem               # No battery probes
827           | Invalid\scommand:\spwrmonitoring                           # Older OMSAs lack this command(?)
828         }xms;
829
830     # Errors that are OK on blade servers
831     my $ok_blade_errors
832       = qr{
833               No\sfan\sprobes\sfound\son\sthis\ssystem   # No fan probes
834       }xms;
835
836     # Run omreport and fetch output
837     my $rawtext = slurp_command("$omreport $command -fmt ssv 2>&1");
838     return [] if !defined $rawtext;
839
840     # Workaround for Openmanage BUG introduced in OMSA 5.5.0
841     $rawtext =~ s/\n;/;/gxms if $command eq 'storage controller';
842
843     # Parse output, store in array
844     for ((split /\n/xms, $rawtext)) {
845         if (m/\A Error/xms) {
846             next if m{$ok_errors}xms;
847             next if ($blade and m{$ok_blade_errors}xms);
848             report('other', "Problem running 'omreport $command': $_", $E_UNKNOWN);
849         }
850
851         next if !m/(.*?;){2}/xms;  # ignore lines with less than 3 fields
852         my @vals = split /;/xms;
853         if ($vals[0] =~ m/\A (Index|ID|Severity) \z/xms) {
854             @keys = @vals;
855         }
856         else {
857             my $i = 0;
858             push @output, { map { $_ => $vals[$i++] } @keys };
859         }
860
861     }
862
863     # Finally, return the collected information
864     return \@output;
865 }
866
867
868 #
869 # Checks if a component is blacklisted. Returns 1 if the component is
870 # blacklisted, 0 otherwise. Takes two arguments:
871 #   arg1: component name
872 #   arg2: component id or index
873 #
874 sub blacklisted {
875     my $name = shift;  # component name
876     my $id   = shift;  # component id
877     my $ret  = 0;      # return value
878
879     if (defined $blacklist{$name}) {
880         foreach my $comp (@{ $blacklist{$name} }) {
881             if (defined $id and $comp eq $id) {
882                 $ret = 1;
883             }
884         }
885     }
886
887     return $ret;
888 }
889
890 # Converts the NexusID from SNMP to our version
891 sub convert_nexus {
892     my $nexus = shift;
893     $nexus =~ s{\A \\}{}xms;
894     $nexus =~ s{\\}{:}gxms;
895     return $nexus;
896 }
897
898 # Sets custom temperature thresholds based on user supplied options
899 sub custom_temperature_thresholds {
900     my $type   = shift; # type of threshold, either w (warning) or c (critical)
901     my %thres  = ();    # will contain the thresholds
902     my @limits = ();    # holds the input
903
904     my @opt =  $type eq 'w' ? @{ $opt{warning} } : @{ $opt{critical} };
905
906     if (scalar @opt >= 0) {
907         foreach my $t (@opt) {
908             my $tmp = q{};
909             if (-f $t) {
910                 open my $F, '<', $t
911                   or do { report('other', "Couldn't open temperature threshold file $t: $!",
912                                  $E_UNKNOWN) and return {} };
913                 $tmp = <$F>;
914                 close $F;
915             }
916             else {
917                 $tmp = $t;
918             }
919             push @limits, $tmp;
920         }
921     }
922
923     # Parse checklist string, put in hash
924     foreach my $th (@limits) {
925         my @tmp = split m{,}xms, $th;
926         foreach my $t (@tmp) {
927             next if $t !~ m{=}xms;
928             my ($key, $val) = split m{=}xms, $t;
929             if ($val =~ m{/}xms) {
930                 my ($max, $min) = split m{/}xms, $val;
931                 $thres{$key}{max} = $max;
932                 $thres{$key}{min} = $min;
933             }
934             else {
935                 $thres{$key}{max} = $val;
936             }
937         }
938     }
939
940     return \%thres;
941 }
942
943
944 # Gets the output from SNMP result according to the OIDs checked
945 sub get_snmp_output {
946     my ($result,$oidref) = @_;
947     my @output = ();
948
949     foreach my $oid (keys %{ $result }) {
950         my @dummy = split /\./xms, $oid;
951         my $id = pop @dummy;
952         --$id;
953         my $foo = join q{.}, @dummy;
954         if (exists $oidref->{$foo}) {
955             $output[$id]{$oidref->{$foo}} = $result->{$oid};
956         }
957     }
958     return \@output;
959 }
960
961
962 # Map the controller or other item in-place
963 sub map_item {
964     my ($key, $val, $list)  = @_;
965
966     foreach my $lst (@{ $list }) {
967         if (!exists $lst->{$key}) {
968             $lst->{$key} = $val;
969         }
970     }
971     return;
972 }
973
974 # Return the URL for official Dell documentation for a specific
975 # PowerEdge server
976 sub documentation_url {
977     my $model = shift;
978
979     # create model short form, e.g. "r710"
980     $model =~ s{\A PowerEdge \s (.+?) \z}{lc($1)}exms;
981
982     # special case for blades (e.g. M600, M710), they have common
983     # documentation
984     $model =~ s{\A m\d+ \z}{m}xms;
985
986     return 'http://support.dell.com/support/edocs/systems/pe' . $model . '/';
987 }
988
989 # Return the URL for warranty information for a server with a given
990 # serial number (servicetag)
991 sub warranty_url {
992     my $tag = shift;
993
994     # Dell support sites for different parts of the world
995     my %supportsite
996       = (
997          'emea' => 'http://support.euro.dell.com/support/topics/topic.aspx/emea/shared/support/my_systems_info/',
998          'ap'   => 'http://supportapj.dell.com/support/topics/topic.aspx/ap/shared/support/my_systems_info/en/details?',
999          'glob' => 'http://support.dell.com/support/topics/global.aspx/support/my_systems_info/details?',
1000         );
1001
1002     # warranty URLs for different country codes
1003     my %url
1004       = (
1005          # EMEA
1006          'at' => $supportsite{emea} . 'de/details?c=at&l=de&ServiceTag=',  # Austria
1007          'be' => $supportsite{emea} . 'nl/details?c=be&l=nl&ServiceTag=',  # Belgium
1008          'cz' => $supportsite{emea} . 'cs/details?c=cz&l=cs&ServiceTag=',  # Czech Republic
1009          'de' => $supportsite{emea} . 'de/details?c=de&l=de&ServiceTag=',  # Germany
1010          'dk' => $supportsite{emea} . 'da/details?c=dk&l=da&ServiceTag=',  # Denmark
1011          'es' => $supportsite{emea} . 'es/details?c=es&l=es&ServiceTag=',  # Spain
1012          'fi' => $supportsite{emea} . 'fi/details?c=fi&l=fi&ServiceTag=',  # Finland
1013          'fr' => $supportsite{emea} . 'fr/details?c=fr&l=fr&ServiceTag=',  # France
1014          'gr' => $supportsite{emea} . 'en/details?c=gr&l=el&ServiceTag=',  # Greece
1015          'it' => $supportsite{emea} . 'it/details?c=it&l=it&ServiceTag=',  # Italy
1016          'il' => $supportsite{emea} . 'en/details?c=il&l=en&ServiceTag=',  # Israel
1017          'me' => $supportsite{emea} . 'en/details?c=me&l=en&ServiceTag=',  # Middle East
1018          'no' => $supportsite{emea} . 'no/details?c=no&l=no&ServiceTag=',  # Norway
1019          'nl' => $supportsite{emea} . 'nl/details?c=nl&l=nl&ServiceTag=',  # The Netherlands
1020          'pl' => $supportsite{emea} . 'pl/details?c=pl&l=pl&ServiceTag=',  # Poland
1021          'pt' => $supportsite{emea} . 'en/details?c=pt&l=pt&ServiceTag=',  # Portugal
1022          'ru' => $supportsite{emea} . 'ru/details?c=ru&l=ru&ServiceTag=',  # Russia
1023          'se' => $supportsite{emea} . 'sv/details?c=se&l=sv&ServiceTag=',  # Sweden
1024          'uk' => $supportsite{emea} . 'en/details?c=uk&l=en&ServiceTag=',  # United Kingdom
1025          'za' => $supportsite{emea} . 'en/details?c=za&l=en&ServiceTag=',  # South Africa
1026          # America
1027          'br' => $supportsite{glob} . 'c=br&l=pt&ServiceTag=',  # Brazil
1028          'ca' => $supportsite{glob} . 'c=ca&l=en&ServiceTag=',  # Canada
1029          'mx' => $supportsite{glob} . 'c=mx&l=es&ServiceTag=',  # Mexico
1030          'us' => $supportsite{glob} . 'c=us&l=en&ServiceTag=',  # USA
1031          # Asia/Pacific
1032          'au' => $supportsite{ap} . 'c=au&l=en&ServiceTag=',  # Australia
1033          'cn' => $supportsite{ap} . 'c=cn&l=zh&ServiceTag=',  # China
1034          'in' => $supportsite{ap} . 'c=in&l=en&ServiceTag=',  # India
1035          # default fallback
1036          'XX' => $supportsite{glob} . 'ServiceTag=',  # default
1037         );
1038
1039     if (exists $url{$opt{htmlinfo}}) {
1040         return $url{$opt{htmlinfo}} . $tag;
1041     }
1042     else {
1043         return $url{XX} . $tag;
1044     }
1045 }
1046
1047
1048
1049 #---------------------------------------------------------------------
1050 # Check functions
1051 #---------------------------------------------------------------------
1052
1053 #-----------------------------------------
1054 # Check global health status
1055 #-----------------------------------------
1056 sub check_global {
1057     my $health = $E_OK;
1058
1059     if ($snmp) {
1060         #
1061         # Checks global status, i.e. both storage and chassis
1062         #
1063         my $systemStateGlobalSystemStatus = '1.3.6.1.4.1.674.10892.1.200.10.1.2.1';
1064         my $result = $snmp_session->get_request(-varbindlist => [$systemStateGlobalSystemStatus]);
1065         if (!defined $result) {
1066             printf "SNMP ERROR [global]: %s\n", $snmp_error;
1067             exit $E_UNKNOWN;
1068         }
1069         $health = $status2nagios{$snmp_status{$result->{$systemStateGlobalSystemStatus}}};
1070     }
1071     else {
1072         #
1073         # NB! This does not check storage, only chassis...
1074         #
1075         foreach (@{ run_command("$omreport $omopt_system -fmt ssv") }) {
1076             next if !m/;/xms;
1077             next if m/\A SEVERITY;COMPONENT/xms;
1078             if (m/\A (.+?);Main\sSystem(\sChassis)? /xms) {
1079                 $health = $status2nagios{$1};
1080                 last;
1081             }
1082         }
1083     }
1084
1085     # Return the status
1086     return $health;
1087 }
1088
1089
1090 #-----------------------------------------
1091 # STORAGE: Check controllers
1092 #-----------------------------------------
1093 sub check_controllers {
1094     my $id       = undef;
1095     my $nexus    = undef;
1096     my $name     = undef;
1097     my $state    = undef;
1098     my $status   = undef;
1099     my $minfw    = undef;
1100     my $mindr    = undef;
1101     my $firmware = undef;
1102     my $driver   = undef;
1103     my @output   = ();
1104
1105     if ($snmp) {
1106         my %ctrl_oid
1107           = (
1108              '1.3.6.1.4.1.674.10893.1.20.130.1.1.1'  => 'controllerNumber',
1109              '1.3.6.1.4.1.674.10893.1.20.130.1.1.2'  => 'controllerName',
1110              '1.3.6.1.4.1.674.10893.1.20.130.1.1.5'  => 'controllerState',
1111              '1.3.6.1.4.1.674.10893.1.20.130.1.1.8'  => 'controllerFWVersion',
1112              '1.3.6.1.4.1.674.10893.1.20.130.1.1.38' => 'controllerComponentStatus',
1113              '1.3.6.1.4.1.674.10893.1.20.130.1.1.39' => 'controllerNexusID',
1114              '1.3.6.1.4.1.674.10893.1.20.130.1.1.41' => 'controllerDriverVersion',
1115              '1.3.6.1.4.1.674.10893.1.20.130.1.1.44' => 'controllerMinFWVersion',
1116              '1.3.6.1.4.1.674.10893.1.20.130.1.1.45' => 'controllerMinDriverVersion',
1117             );
1118
1119         # We use get_table() here for the odd case where a server has
1120         # two or more controllers, and where some OIDs are missing on
1121         # one of the controllers.
1122         my $controllerTable = '1.3.6.1.4.1.674.10893.1.20.130.1';
1123         my $result = $snmp_session->get_table(-baseoid => $controllerTable);
1124
1125         # No controllers is OK
1126         return if !defined $result;
1127
1128         @output = @{ get_snmp_output($result, \%ctrl_oid) };
1129     }
1130     else {
1131         @output = @{ run_omreport('storage controller') };
1132     }
1133
1134     my %ctrl_state
1135       = (
1136          0 => 'Unknown',
1137          1 => 'Ready',
1138          2 => 'Failed',
1139          3 => 'Online',
1140          4 => 'Offline',
1141          6 => 'Degraded',
1142         );
1143
1144   CTRL:
1145     foreach my $out (@output) {
1146         if ($snmp) {
1147             $id       = $out->{'controllerNumber'} - 1;
1148             $name     = $out->{'controllerName'};
1149             $state    = $ctrl_state{$out->{'controllerState'}};
1150             $status   = $snmp_status{$out->{'controllerComponentStatus'}};
1151             $minfw    = exists $out->{'controllerMinFWVersion'}
1152               ? $out->{'controllerMinFWVersion'} : undef;
1153             $mindr    = exists $out->{'controllerMinDriverVersion'}
1154               ? $out->{'controllerMinDriverVersion'} : undef;
1155             $firmware = exists $out->{controllerFWVersion}
1156               ? $out->{controllerFWVersion} : 'N/A';
1157             $driver   = exists $out->{controllerDriverVersion}
1158               ? $out->{controllerDriverVersion} : 'N/A';
1159             $nexus    = convert_nexus($out->{controllerNexusID});
1160         }
1161         else {
1162             $id       = $out->{ID};
1163             $name     = $out->{Name};
1164             $state    = $out->{State};
1165             $status   = $out->{Status};
1166             $minfw    = $out->{'Minimum Required Firmware Version'} ne 'Not Applicable'
1167               ? $out->{'Minimum Required Firmware Version'} : undef;
1168             $mindr    = $out->{'Minimum Required Driver Version'} ne 'Not Applicable'
1169               ? $out->{'Minimum Required Driver Version'} : undef;
1170             $firmware = $out->{'Firmware Version'} ne 'Not Applicable'
1171               ? $out->{'Firmware Version'} : 'N/A';
1172             $driver   = $out->{'Driver Version'} ne 'Not Applicable'
1173               ? $out->{'Driver Version'} : 'N/A';
1174             $nexus    = $id;
1175         }
1176
1177         $name =~ s{\s+\z}{}xms; # remove trailing whitespace
1178         push @controllers, $id;
1179
1180         # Collecting some storage info
1181         $sysinfo{'controller'}{$id}{'id'}       = $nexus;
1182         $sysinfo{'controller'}{$id}{'name'}     = $name;
1183         $sysinfo{'controller'}{$id}{'driver'}   = $driver;
1184         $sysinfo{'controller'}{$id}{'firmware'} = $firmware;
1185
1186         next CTRL if blacklisted('ctrl', $nexus);
1187
1188         # Special case: old firmware
1189         if (!blacklisted('ctrl_fw', $id) && defined $minfw) {
1190             chomp $firmware;
1191             my $msg = sprintf q{Controller %d [%s]: Firmware '%s' is out of date},
1192               $id, $name, $firmware;
1193             report('storage', $msg, $E_WARNING, $nexus);
1194         }
1195         # Special case: old driver
1196         if (!blacklisted('ctrl_driver', $id) && defined $mindr) {
1197             chomp $driver;
1198             my $msg = sprintf q{Controller %d [%s]: Driver '%s' is out of date},
1199               $id, $name, $driver;
1200             report('storage', $msg, $E_WARNING, $nexus);
1201         }
1202         # Ok
1203         if ($status eq 'Ok' or ($status eq 'Non-Critical'
1204                                 and (defined $minfw or defined $mindr))) {
1205             my $msg = sprintf 'Controller %d [%s] is %s',
1206               $id, $name, $state;
1207             report('storage', $msg, $E_OK, $nexus);
1208         }
1209         # Default
1210         else {
1211             my $msg = sprintf 'Controller %d [%s] needs attention: %s',
1212               $id, $name, $state;
1213             report('storage', $msg, $status2nagios{$status}, $nexus);
1214         }
1215     }
1216     return;
1217 }
1218
1219
1220 #-----------------------------------------
1221 # STORAGE: Check physical drives
1222 #-----------------------------------------
1223 sub check_physical_disks {
1224     return if $#controllers == -1;
1225
1226     my $id       = undef;
1227     my $nexus    = undef;
1228     my $name     = undef;
1229     my $state    = undef;
1230     my $status   = undef;
1231     my $fpred    = undef;
1232     my $progr    = undef;
1233     my $ctrl     = undef;
1234     my $vendor   = undef;  # disk vendor
1235     my $product  = undef;  # product ID
1236     my $capacity = undef;  # disk length (size) in bytes
1237     my @output  = ();
1238
1239     if ($snmp) {
1240         my %pdisk_oid
1241           = (
1242              '1.3.6.1.4.1.674.10893.1.20.130.4.1.1'  => 'arrayDiskNumber',
1243              '1.3.6.1.4.1.674.10893.1.20.130.4.1.2'  => 'arrayDiskName',
1244              '1.3.6.1.4.1.674.10893.1.20.130.4.1.3'  => 'arrayDiskVendor',
1245              '1.3.6.1.4.1.674.10893.1.20.130.4.1.4'  => 'arrayDiskState',
1246              '1.3.6.1.4.1.674.10893.1.20.130.4.1.6'  => 'arrayDiskProductID',
1247              '1.3.6.1.4.1.674.10893.1.20.130.4.1.9'  => 'arrayDiskEnclosureID',
1248              '1.3.6.1.4.1.674.10893.1.20.130.4.1.10' => 'arrayDiskChannel',
1249              '1.3.6.1.4.1.674.10893.1.20.130.4.1.11' => 'arrayDiskLengthInMB',
1250              '1.3.6.1.4.1.674.10893.1.20.130.4.1.15' => 'arrayDiskTargetID',
1251              '1.3.6.1.4.1.674.10893.1.20.130.4.1.16' => 'arrayDiskLunID',
1252              '1.3.6.1.4.1.674.10893.1.20.130.4.1.24' => 'arrayDiskComponentStatus',
1253              '1.3.6.1.4.1.674.10893.1.20.130.4.1.26' => 'arrayDiskNexusID',
1254              '1.3.6.1.4.1.674.10893.1.20.130.4.1.31' => 'arrayDiskSmartAlertIndication',
1255              '1.3.6.1.4.1.674.10893.1.20.130.5.1.5'  => 'arrayDiskEnclosureConnectionEnclosureNumber',
1256              '1.3.6.1.4.1.674.10893.1.20.130.5.1.7'  => 'arrayDiskEnclosureConnectionControllerNumber',
1257             );
1258         my $result = $snmp_session->get_entries(-columns => [keys %pdisk_oid]);
1259
1260         if (!defined $result) {
1261             printf "SNMP ERROR [storage / pdisk]: %s.\n", $snmp_session->error;
1262             $snmp_session->close;
1263             exit $E_UNKNOWN;
1264         }
1265
1266         @output = @{ get_snmp_output($result, \%pdisk_oid) };
1267     }
1268     else {
1269         foreach my $c (@controllers) {
1270             push @output, @{ run_omreport("storage pdisk controller=$c") };
1271             map_item('ctrl', $c, \@output);
1272         }
1273     }
1274
1275     my %pdisk_state
1276       = (
1277          0  => 'Unknown',
1278          1  => 'Ready',
1279          2  => 'Failed',
1280          3  => 'Online',
1281          4  => 'Offline',
1282          6  => 'Degraded',
1283          7  => 'Recovering',
1284          11 => 'Removed',
1285          15 => 'Resynching',
1286          24 => 'Rebuilding',
1287          25 => 'No Media',
1288          26 => 'Formatting',
1289          28 => 'Diagnostics',
1290          34 => 'Predictive failure',
1291          35 => 'Initializing',
1292          39 => 'Foreign',
1293          40 => 'Clear',
1294          41 => 'Unsupported',
1295          53 => 'Incompatible',
1296         );
1297
1298     # Check physical disks on each of the controllers
1299   PDISK:
1300     foreach my $out (@output) {
1301         if ($snmp) {
1302             $name   = $out->{arrayDiskName};
1303             if ($name =~ m{.*\d+:\d+:\d+\z}xms) {
1304                 $id = join q{:}, ($out->{arrayDiskChannel}, $out->{arrayDiskEnclosureID},
1305                                  $out->{arrayDiskTargetID});
1306             }
1307             else {
1308                 $id = join q{:}, ($out->{arrayDiskChannel}, $out->{arrayDiskTargetID});
1309             }
1310             $state    = $pdisk_state{$out->{arrayDiskState}};
1311             $status   = $snmp_status{$out->{arrayDiskComponentStatus}};
1312             $fpred    = $out->{arrayDiskSmartAlertIndication} == 2 ? 1 : 0;
1313             $progr    = q{};
1314             $ctrl     = exists $out->{arrayDiskEnclosureConnectionControllerNumber}
1315               ? $out->{arrayDiskEnclosureConnectionControllerNumber} - 1
1316                 : -1;
1317             $nexus    = convert_nexus($out->{arrayDiskNexusID});
1318             $vendor   = $out->{arrayDiskVendor};
1319             $product  = $out->{arrayDiskProductID};
1320             $capacity = $out->{arrayDiskLengthInMB} * 1024**2;
1321         }
1322         else {
1323             $id       = $out->{'ID'};
1324             $name     = $out->{'Name'};
1325             $state    = $out->{'State'};
1326             $status   = $out->{'Status'};
1327             $fpred    = lc($out->{'Failure Predicted'}) eq 'yes' ? 1 : 0;
1328             $progr    = ' [' . $out->{'Progress'} . ']';
1329             $ctrl     = $out->{'ctrl'};
1330             $nexus    = join q{:}, $out->{ctrl}, $id;
1331             $vendor   = $out->{'Vendor ID'};
1332             $product  = $out->{'Product ID'};
1333             $capacity = $out->{'Capacity'};
1334             $capacity =~ s{\A .*? \((\d+) \s bytes\) \z}{$1}xms;
1335         }
1336
1337         next PDISK if blacklisted('pdisk', $nexus);
1338         $count{pdisk}++;
1339
1340         $vendor  =~ s{\s+\z}{}xms; # remove trailing whitespace
1341         $product =~ s{\s+\z}{}xms; # remove trailing whitespace
1342
1343         # Calculate human readable capacity
1344         $capacity = ceil($capacity / 1000**3) >= 1000
1345           ? sprintf '%.1fTB', ($capacity / 1000**4)
1346             : sprintf '%.0fGB', ($capacity / 1000**3);
1347         $capacity = '450GB' if $capacity eq '449GB';  # quick fix for 450GB disks
1348         $capacity = '146GB' if $capacity eq '147GB';  # quick fix for 146GB disks
1349         $capacity = '300GB' if $capacity eq '299GB';  # quick fix for 146GB disks
1350
1351         # Capitalize only the first letter of the vendor name
1352         $vendor = (substr $vendor, 0, 1) . lc (substr $vendor, 1, length $vendor);
1353
1354         # Remove unnecessary trademark rubbish from vendor name
1355         $vendor =~ s{\(tm\)\z}{}xms;
1356
1357         # Special case: Failure predicted
1358         if ($status eq 'Non-Critical' and $fpred) {
1359             my $msg = sprintf '%s [%s %s, %s] on ctrl %d needs attention: Failure Predicted',
1360               $name, $vendor, $product, $capacity, $ctrl;
1361             report('storage', $msg, $E_WARNING, $nexus);
1362         }
1363         # Special case: Rebuilding
1364         elsif ($state eq 'Rebuilding') {
1365             my $msg = sprintf '%s [%s] on ctrl %d is %s%s',
1366               $name, $capacity, $ctrl, $state, $progr;
1367             report('storage', $msg, $E_WARNING, $nexus);
1368         }
1369         # Default
1370         elsif ($status ne 'Ok') {
1371             my $msg =  sprintf '%s [%s %s, %s] on ctrl %d needs attention: %s',
1372               $name, $vendor, $product, $capacity, $ctrl, $state;
1373             report('storage', $msg, $status2nagios{$status}, $nexus);
1374         }
1375         # Ok
1376         else {
1377             my $msg = sprintf '%s [%s] on ctrl %d is %s',
1378               $name, $capacity, $ctrl, $state;
1379             report('storage', $msg, $E_OK, $nexus);
1380         }
1381     }
1382     return;
1383 }
1384
1385
1386 #-----------------------------------------
1387 # STORAGE: Check logical drives
1388 #-----------------------------------------
1389 sub check_virtual_disks {
1390     return if $#controllers == -1;
1391
1392     my $id     = undef;
1393     my $name   = undef;
1394     my $nexus  = undef;
1395     my $dev    = undef;
1396     my $state  = undef;
1397     my $status = undef;
1398     my $layout = undef;
1399     my $size   = undef;
1400     my $progr  = undef;
1401     my $ctrl   = undef;
1402     my @output = ();
1403
1404     if ($snmp) {
1405         my %vdisk_oid
1406           = (
1407              '1.3.6.1.4.1.674.10893.1.20.140.1.1.3'  => 'virtualDiskDeviceName',
1408              '1.3.6.1.4.1.674.10893.1.20.140.1.1.4'  => 'virtualDiskState',
1409              '1.3.6.1.4.1.674.10893.1.20.140.1.1.6'  => 'virtualDiskLengthInMB',
1410              '1.3.6.1.4.1.674.10893.1.20.140.1.1.13' => 'virtualDiskLayout',
1411              '1.3.6.1.4.1.674.10893.1.20.140.1.1.17' => 'virtualDiskTargetID',
1412              '1.3.6.1.4.1.674.10893.1.20.140.1.1.20' => 'virtualDiskComponentStatus',
1413              '1.3.6.1.4.1.674.10893.1.20.140.1.1.21' => 'virtualDiskNexusID',
1414             );
1415         my $result = $snmp_session->get_entries(-columns => [keys %vdisk_oid]);
1416
1417         # No logical drives is OK
1418         return if !defined $result;
1419
1420         @output = @{ get_snmp_output($result, \%vdisk_oid) };
1421     }
1422     else {
1423         foreach my $c (@controllers) {
1424             push @output, @{ run_omreport("storage vdisk controller=$c") };
1425             map_item('ctrl', $c, \@output);
1426         }
1427     }
1428
1429     my %vdisk_state
1430       = (
1431          0  => 'Unknown',
1432          1  => 'Ready',
1433          2  => 'Failed',
1434          3  => 'Online',
1435          4  => 'Offline',
1436          6  => 'Degraded',
1437          15 => 'Resynching',
1438          16 => 'Regenerating',
1439          24 => 'Rebuilding',
1440          26 => 'Formatting',
1441          32 => 'Reconstructing',
1442          35 => 'Initializing',
1443          36 => 'Background Initialization',
1444          38 => 'Resynching Paused',
1445          52 => 'Permanently Degraded',
1446          54 => 'Degraded Redundancy',
1447         );
1448
1449     my %vdisk_layout
1450       = (
1451          1  => 'Concatenated',
1452          2  => 'RAID-0',
1453          3  => 'RAID-1',
1454          7  => 'RAID-5',
1455          8  => 'RAID-6',
1456          10 => 'RAID-10',
1457          12 => 'RAID-50',
1458          19 => 'Concatenated RAID 1',
1459          24 => 'RAID-60',
1460         );
1461
1462     # Check virtual disks on each of the controllers
1463   VDISK:
1464     foreach my $out (@output) {
1465         if ($snmp) {
1466             $id     = $out->{virtualDiskTargetID};
1467             $dev    = $out->{virtualDiskDeviceName};
1468             $state  = $vdisk_state{$out->{virtualDiskState}};
1469             $status = $snmp_status{$out->{virtualDiskComponentStatus}};
1470             $layout = $vdisk_layout{$out->{virtualDiskLayout}};
1471             $size   = sprintf '%.2f GB', $out->{virtualDiskLengthInMB} / 1024;
1472             $progr  = q{};  # can't get this from SNMP(?)
1473             $nexus  = convert_nexus($out->{virtualDiskNexusID});
1474             $ctrl   = $nexus;  # We use the nexus id to get the controller id
1475             $ctrl   =~ s{\A (\d+):\d+ \z}{$1}xms;
1476         }
1477         else {
1478             $id     = $out->{ID};
1479             $dev    = $out->{'Device Name'};
1480             $state  = $out->{State};
1481             $status = $out->{Status};
1482             $layout = $out->{Layout};
1483             $size   = $out->{Size};
1484             $progr  = ' [' . $out->{Progress} . ']';
1485             $size   =~ s{\A (.*GB).* \z}{$1}xms;
1486             $nexus  = join q{:}, $out->{ctrl}, $id;
1487             $ctrl   = $out->{ctrl};
1488         }
1489
1490         next VDISK if blacklisted('vdisk', $nexus);
1491         $count{vdisk}++;
1492
1493         # Special case: Regenerating
1494         if ($state eq 'Regenerating') {
1495             my $msg = sprintf q{Logical drive %d '%s' [%s, %s] on ctrl %d is %s%s},
1496               $id, $dev, $layout, $size, $ctrl, $state, $progr;
1497             report('storage', $msg, $E_WARNING, $nexus);
1498         }
1499         # Default
1500         elsif ($status ne 'Ok') {
1501             my $msg = sprintf q{Logical drive %d '%s' [%s, %s] on ctrl %d needs attention: %s},
1502               $id, $dev, $layout, $size, $ctrl, $state;
1503             report('storage', $msg, $status2nagios{$status}, $nexus);
1504         }
1505         # Ok
1506         else {
1507             my $msg = sprintf q{Logical drive %d '%s' [%s, %s] on ctrl %d is %s},
1508               $id, $dev, $layout, $size, $ctrl, $state;
1509             report('storage', $msg, $E_OK, $nexus);
1510         }
1511     }
1512     return;
1513 }
1514
1515
1516 #-----------------------------------------
1517 # STORAGE: Check cache batteries
1518 #-----------------------------------------
1519 sub check_cache_battery {
1520     return if $#controllers == -1;
1521
1522     my $id     = undef;
1523     my $nexus  = undef;
1524     my $state  = undef;
1525     my $status = undef;
1526     my $ctrl   = undef;
1527     my $learn  = undef; # learn state
1528     my $pred   = undef; # battery's ability to be charged
1529     my @output = ();
1530
1531     if ($snmp) {
1532         my %bat_oid
1533           = (
1534              '1.3.6.1.4.1.674.10893.1.20.130.15.1.4'  => 'batteryState',
1535              '1.3.6.1.4.1.674.10893.1.20.130.15.1.6'  => 'batteryComponentStatus',
1536              '1.3.6.1.4.1.674.10893.1.20.130.15.1.9'  => 'batteryNexusID',
1537              '1.3.6.1.4.1.674.10893.1.20.130.15.1.10' => 'batteryPredictedCapacity',
1538              '1.3.6.1.4.1.674.10893.1.20.130.15.1.12' => 'batteryLearnState',
1539              '1.3.6.1.4.1.674.10893.1.20.130.16.1.5'  => 'batteryConnectionControllerNumber',
1540             );
1541         my $result = $snmp_session->get_entries(-columns => [keys %bat_oid]);
1542
1543         # No cache battery is OK
1544         return if !defined $result;
1545
1546         @output = @{ get_snmp_output($result, \%bat_oid) };
1547     }
1548     else {
1549         foreach my $c (@controllers) {
1550             push @output, @{ run_omreport("storage battery controller=$c") };
1551             map_item('ctrl', $c, \@output);
1552         }
1553     }
1554
1555     my %bat_state
1556       = (
1557          0  => 'Unknown',
1558          1  => 'Ready',
1559          2  => 'Failed',
1560          6  => 'Degraded',
1561          7  => 'Reconditioning',
1562          9  => 'High',
1563          10 => 'Power Low',
1564          12 => 'Charging',
1565          21 => 'Missing',
1566          36 => 'Learning',
1567         );
1568
1569     my %bat_learn_state
1570       = (
1571          1  => 'Failed',
1572          2  => 'Active',
1573          4  => 'Timed out',
1574          8  => 'Requested',
1575          16 => 'Idle',
1576         );
1577
1578     my %bat_pred_cap
1579       = (
1580          1 => 'Failed',  # The battery cannot be charged and needs to be replaced
1581          2 => 'Ready',   # The battery can be charged to full capacity
1582          4 => 'Unknown', # The battery is completing a Learn cycle. The charge capacity of the
1583                          # battery cannot be determined until the Learn cycle is complete
1584         );
1585
1586     # Check battery on each of the controllers
1587   BATTERY:
1588     foreach my $out (@output) {
1589         if ($snmp) {
1590             $state  = $bat_state{$out->{batteryState}};
1591             $status = $snmp_status{$out->{batteryComponentStatus}};
1592             $learn  = exists $out->{batteryLearnState}
1593               ? $bat_learn_state{$out->{batteryLearnState}} : undef;
1594             $pred   = exists $out->{batteryPredictedCapacity}
1595               ? $bat_pred_cap{$out->{batteryPredictedCapacity}} : undef;
1596             $ctrl   = $out->{batteryConnectionControllerNumber} - 1;
1597             $nexus  = convert_nexus($out->{batteryNexusID});
1598             $id     = $nexus;
1599             $id     =~ s{\A \d+:(\d+) \z}{$1}xms;
1600         }
1601         else {
1602             $id     = $out->{'ID'};
1603             $state  = $out->{'State'};
1604             $status = $out->{'Status'};
1605             $learn  = $out->{'Learn State'};
1606             $pred   = $out->{'Predicted Capacity Status'};
1607             $ctrl   = $out->{'ctrl'};
1608             $nexus  = join q{:}, $out->{ctrl}, $id;
1609         }
1610
1611         next BATTERY if blacklisted('bat', $nexus);
1612
1613         # Special case: Charging
1614         if ($state eq 'Charging') {
1615             my $msg = sprintf 'Cache battery %d in controller %d is %s (%s) [probably harmless]',
1616               $id, $ctrl, $state, $pred;
1617             report('storage', $msg, $E_WARNING, $nexus);
1618         }
1619         # Special case: Learning (battery learns its capacity)
1620         elsif ($state eq 'Learning') {
1621             my $msg = sprintf 'Cache battery %d in controller %d is %s (%s) [probably harmless]',
1622               $id, $ctrl, $state, $learn;
1623             report('storage', $msg, $E_WARNING, $nexus);
1624         }
1625         # Special case: Power Low (first part of recharge cycle)
1626         elsif ($state eq 'Power Low') {
1627             my $msg = sprintf 'Cache battery %d in controller %d is %s [probably harmless]',
1628               $id, $ctrl, $state;
1629             report('storage', $msg, $E_WARNING, $nexus);
1630         }
1631         # Default
1632         elsif ($status ne 'Ok') {
1633             my $msg = sprintf 'Cache battery %d in controller %d needs attention: %s (%s)',
1634               $id, $ctrl, $state, $status;
1635             report('storage', $msg, $status2nagios{$status}, $nexus);
1636         }
1637         # Ok
1638         else {
1639             my $msg = sprintf 'Cache battery %d in controller %d is %s',
1640               $id, $ctrl, $state;
1641             report('storage', $msg, $E_OK, $nexus);
1642         }
1643     }
1644     return;
1645 }
1646
1647
1648 #-----------------------------------------
1649 # STORAGE: Check connectors (channels)
1650 #-----------------------------------------
1651 sub check_connectors {
1652     return if $#controllers == -1;
1653
1654     my $id     = undef;
1655     my $nexus  = undef;
1656     my $name   = undef;
1657     my $state  = undef;
1658     my $status = undef;
1659     my $type   = undef;
1660     my $ctrl   = undef;
1661     my @output = ();
1662
1663     if ($snmp) {
1664         my %conn_oid
1665           = (
1666              '1.3.6.1.4.1.674.10893.1.20.130.2.1.1'  => 'channelNumber',
1667              '1.3.6.1.4.1.674.10893.1.20.130.2.1.2'  => 'channelName',
1668              '1.3.6.1.4.1.674.10893.1.20.130.2.1.3'  => 'channelState',
1669              '1.3.6.1.4.1.674.10893.1.20.130.2.1.8'  => 'channelComponentStatus',
1670              '1.3.6.1.4.1.674.10893.1.20.130.2.1.9'  => 'channelNexusID',
1671              '1.3.6.1.4.1.674.10893.1.20.130.2.1.11' => 'channelBusType',
1672             );
1673         my $result = $snmp_session->get_entries(-columns => [keys %conn_oid]);
1674
1675         if (!defined $result) {
1676             printf "SNMP ERROR [storage / channel]: %s.\n", $snmp_session->error;
1677             $snmp_session->close;
1678             exit $E_UNKNOWN;
1679         }
1680
1681         @output = @{ get_snmp_output($result, \%conn_oid) };
1682     }
1683     else {
1684         foreach my $c (@controllers) {
1685             push @output, @{ run_omreport("storage connector controller=$c") };
1686             map_item('ctrl', $c, \@output);
1687         }
1688     }
1689
1690     my %conn_state
1691       = (
1692          0 => 'Unknown',
1693          1 => 'Ready',
1694          2 => 'Failed',
1695          3 => 'Online',
1696          4 => 'Offline',
1697          6 => 'Degraded',
1698         );
1699
1700     my %conn_bustype
1701       = (
1702          1 => 'SCSI',
1703          2 => 'IDE',
1704          3 => 'Fibre Channel',
1705          4 => 'SSA',
1706          6 => 'USB',
1707          7 => 'SATA',
1708          8 => 'SAS',
1709         );
1710
1711     # Check connectors on each of the controllers
1712   CHANNEL:
1713     foreach my $out (@output) {
1714         if ($snmp) {
1715             $id     = $out->{channelNumber} - 1;
1716             $name   = $out->{channelName};
1717             $state  = $conn_state{$out->{channelState}};
1718             $status = $snmp_status{$out->{channelComponentStatus}};
1719             $type   = $conn_bustype{$out->{channelBusType}};
1720             $nexus  = convert_nexus($out->{channelNexusID});
1721             $ctrl   = $nexus;
1722             $ctrl   =~ s{(\d+):\d+}{$1}xms;
1723         }
1724         else {
1725             $id     = $out->{'ID'};
1726             $name   = $out->{'Name'};
1727             $state  = $out->{'State'};
1728             $status = $out->{'Status'};
1729             $type   = $out->{'Connector Type'};
1730             $ctrl   = $out->{ctrl};
1731             $nexus  = join q{:}, $out->{ctrl}, $id;
1732         }
1733
1734         next CHANNEL if blacklisted('conn', $nexus);
1735
1736         my $msg = sprintf '%s [%s] on controller %d is %s',
1737           $name, $type, $ctrl, $state;
1738         report('storage', $msg, $status2nagios{$status}, $nexus);
1739     }
1740     return;
1741 }
1742
1743
1744 #-----------------------------------------
1745 # STORAGE: Check enclosures
1746 #-----------------------------------------
1747 sub check_enclosures {
1748     my $id       = undef;
1749     my $nexus    = undef;
1750     my $name     = undef;
1751     my $state    = undef;
1752     my $status   = undef;
1753     my $firmware = undef;
1754     my $ctrl     = undef;
1755     my @output   = ();
1756
1757     if ($snmp) {
1758         my %encl_oid
1759           = (
1760              '1.3.6.1.4.1.674.10893.1.20.130.3.1.1'  => 'enclosureNumber',
1761              '1.3.6.1.4.1.674.10893.1.20.130.3.1.2'  => 'enclosureName',
1762              '1.3.6.1.4.1.674.10893.1.20.130.3.1.4'  => 'enclosureState',
1763              '1.3.6.1.4.1.674.10893.1.20.130.3.1.19' => 'enclosureChannelNumber',
1764              '1.3.6.1.4.1.674.10893.1.20.130.3.1.24' => 'enclosureComponentStatus',
1765              '1.3.6.1.4.1.674.10893.1.20.130.3.1.25' => 'enclosureNexusID',
1766              '1.3.6.1.4.1.674.10893.1.20.130.3.1.26' => 'enclosureFirmwareVersion',
1767             );
1768         my $result = $snmp_session->get_entries(-columns => [keys %encl_oid]);
1769
1770         # No enclosures is OK
1771         return if !defined $result;
1772
1773         @output = @{ get_snmp_output($result, \%encl_oid) };
1774     }
1775     else {
1776         foreach my $c (@controllers) {
1777             push @output, @{ run_omreport("storage enclosure controller=$c") };
1778             map_item('ctrl', $c, \@output);
1779         }
1780     }
1781
1782     my %encl_state
1783       = (
1784          0 => 'Unknown',
1785          1 => 'Ready',
1786          2 => 'Failed',
1787          3 => 'Online',
1788          4 => 'Offline',
1789          6 => 'Degraded',
1790         );
1791
1792   ENCLOSURE:
1793     foreach my $out (@output) {
1794         if ($snmp) {
1795             $id       = $out->{'enclosureNumber'} - 1;
1796             $name     = $out->{'enclosureName'};
1797             $state    = $encl_state{$out->{'enclosureState'}};
1798             $status   = $snmp_status{$out->{'enclosureComponentStatus'}};
1799             $firmware = exists $out->{enclosureFirmwareVersion}
1800               ? $out->{enclosureFirmwareVersion} : 'N/A';
1801             $nexus    = convert_nexus($out->{enclosureNexusID});
1802             $ctrl     = $nexus;
1803             $ctrl     =~ s{\A (\d+):.* \z}{$1}xms;
1804         }
1805         else {
1806             $id       = $out->{ID};
1807             $name     = $out->{Name};
1808             $state    = $out->{State};
1809             $status   = $out->{Status};
1810             $firmware = $out->{'Firmware Version'} ne 'Not Applicable'
1811               ? $out->{'Firmware Version'} : 'N/A';
1812             $nexus    = join q{:}, $out->{ctrl}, $id;
1813             $ctrl     = $out->{ctrl};
1814         }
1815
1816         $name     =~ s{\s+\z}{}xms; # remove trailing whitespace
1817         $firmware =~ s{\s+\z}{}xms; # remove trailing whitespace
1818
1819         # store enclosure data for future use
1820         push @enclosures, { 'id'    => $id,
1821                             'ctrl'  => $out->{ctrl},
1822                             'name'  => $name };
1823
1824         # Collecting some storage info
1825         $sysinfo{'enclosure'}{$nexus}{'id'}       = $nexus;
1826         $sysinfo{'enclosure'}{$nexus}{'name'}     = $name;
1827         $sysinfo{'enclosure'}{$nexus}{'firmware'} = $firmware;
1828
1829         next ENCLOSURE if blacklisted('encl', $nexus);
1830
1831         my $msg = sprintf 'Enclosure %s [%s] on controller %d is %s',
1832           $nexus, $name, $ctrl, $state;
1833         report('storage', $msg, $status2nagios{$status}, $nexus);
1834     }
1835     return;
1836 }
1837
1838
1839 #-----------------------------------------
1840 # STORAGE: Check enclosure fans
1841 #-----------------------------------------
1842 sub check_enclosure_fans {
1843     return if $#controllers == -1;
1844
1845     my $id        = undef;
1846     my $nexus     = undef;
1847     my $name      = undef;
1848     my $state     = undef;
1849     my $status    = undef;
1850     my $speed     = undef;
1851     my $encl_id   = undef;
1852     my $encl_name = undef;
1853     my @output    = ();
1854
1855     if ($snmp) {
1856         my %fan_oid
1857           = (
1858              '1.3.6.1.4.1.674.10893.1.20.130.7.1.1'  => 'fanNumber',
1859              '1.3.6.1.4.1.674.10893.1.20.130.7.1.2'  => 'fanName',
1860              '1.3.6.1.4.1.674.10893.1.20.130.7.1.4'  => 'fanState',
1861              '1.3.6.1.4.1.674.10893.1.20.130.7.1.11' => 'fanProbeCurrValue',
1862              '1.3.6.1.4.1.674.10893.1.20.130.7.1.15' => 'fanComponentStatus',
1863              '1.3.6.1.4.1.674.10893.1.20.130.7.1.16' => 'fanNexusID',
1864              '1.3.6.1.4.1.674.10893.1.20.130.8.1.4'  => 'fanConnectionEnclosureName',
1865              '1.3.6.1.4.1.674.10893.1.20.130.8.1.5'  => 'fanConnectionEnclosureNumber',
1866             );
1867
1868         my $result = $snmp_session->get_entries(-columns => [keys %fan_oid]);
1869
1870         # No enclosure fans is OK
1871         return if !defined $result;
1872
1873         @output = @{ get_snmp_output($result, \%fan_oid) };
1874     }
1875     else {
1876         foreach my $enc (@enclosures) {
1877             push @output, @{ run_omreport("storage enclosure controller=$enc->{ctrl} enclosure=$enc->{id} info=fans") };
1878             map_item('ctrl', $enc->{ctrl}, \@output);
1879             map_item('encl_id', $enc->{id}, \@output);
1880             map_item('encl_name', $enc->{name}, \@output);
1881         }
1882     }
1883
1884     my %fan_state
1885       = (
1886          0  => 'Unknown',
1887          1  => 'Ready',
1888          2  => 'Failed',
1889          3  => 'Online',
1890          4  => 'Offline',
1891          6  => 'Degraded',
1892          21 => 'Missing',
1893         );
1894
1895     # Check fans on each of the enclosures
1896   FAN:
1897     foreach my $out (@output) {
1898         if ($snmp) {
1899             $id        = $out->{fanNumber} - 1;
1900             $name      = $out->{fanName};
1901             $state     = $fan_state{$out->{fanState}};
1902             $status    = $snmp_status{$out->{fanComponentStatus}};
1903             $speed     = $out->{fanProbeCurrValue};
1904             $encl_id   = $out->{fanConnectionEnclosureNumber} - 1;
1905             $encl_name = $out->{fanConnectionEnclosureName};
1906             $nexus     = convert_nexus($out->{fanNexusID});
1907         }
1908         else {
1909             $id        = $out->{'ID'};
1910             $name      = $out->{'Name'};
1911             $state     = $out->{'State'};
1912             $status    = $out->{'Status'};
1913             $speed     = $out->{'Speed'};
1914             $encl_id   = join q{:}, $out->{ctrl}, $out->{'encl_id'};
1915             $encl_name = $out->{encl_name};
1916             $nexus     = join q{:}, $out->{ctrl}, $out->{'encl_id'}, $id;
1917         }
1918
1919         next FAN if blacklisted('encl_fan', $nexus);
1920
1921         # Default
1922         if ($status ne 'Ok') {
1923             my $msg = sprintf '%s in enclosure %s [%s] needs attention: %s',
1924               $name, $encl_id, $encl_name, $state;
1925             report('storage', $msg, $status2nagios{$status}, $nexus);
1926         }
1927         # Ok
1928         else {
1929             my $msg = sprintf '%s in enclosure %s [%s] is %s (speed=%s)',
1930               $name, $encl_id, $encl_name, $state, $speed;
1931             report('storage', $msg, $E_OK, $nexus);
1932         }
1933     }
1934     return;
1935 }
1936
1937
1938 #-----------------------------------------
1939 # STORAGE: Check enclosure power supplies
1940 #-----------------------------------------
1941 sub check_enclosure_pwr {
1942     return if $#controllers == -1;
1943
1944     my $id        = undef;
1945     my $nexus     = undef;
1946     my $name      = undef;
1947     my $state     = undef;
1948     my $status    = undef;
1949     my $encl_id   = undef;
1950     my $encl_name = undef;
1951     my @output    = ();
1952
1953     if ($snmp) {
1954         my %ps_oid
1955           = (
1956              '1.3.6.1.4.1.674.10893.1.20.130.9.1.1'  => 'powerSupplyNumber',
1957              '1.3.6.1.4.1.674.10893.1.20.130.9.1.2'  => 'powerSupplyName',
1958              '1.3.6.1.4.1.674.10893.1.20.130.9.1.4'  => 'powerSupplyState',
1959              '1.3.6.1.4.1.674.10893.1.20.130.9.1.9'  => 'powerSupplyComponentStatus',
1960              '1.3.6.1.4.1.674.10893.1.20.130.9.1.10' => 'powerSupplyNexusID',
1961              '1.3.6.1.4.1.674.10893.1.20.130.10.1.4' => 'powerSupplyConnectionEnclosureName',
1962              '1.3.6.1.4.1.674.10893.1.20.130.10.1.5' => 'powerSupplyConnectionEnclosureNumber',
1963             );
1964         my $result = $snmp_session->get_entries(-columns => [keys %ps_oid]);
1965
1966         # No enclosure power supplies is OK
1967         return if !defined $result;
1968
1969         @output = @{ get_snmp_output($result, \%ps_oid) };
1970     }
1971     else {
1972         foreach my $enc (@enclosures) {
1973             push @output, @{ run_omreport("storage enclosure controller=$enc->{ctrl} enclosure=$enc->{id} info=pwrsupplies") };
1974             map_item('ctrl', $enc->{ctrl}, \@output);
1975             map_item('encl_id', $enc->{id}, \@output);
1976             map_item('encl_name', $enc->{name}, \@output);
1977         }
1978     }
1979
1980     my %ps_state
1981       = (
1982          0  => 'Unknown',
1983          1  => 'Ready',
1984          2  => 'Failed',
1985          5  => 'Not Installed',
1986          6  => 'Degraded',
1987          11 => 'Removed',
1988          21 => 'Missing',
1989         );
1990
1991     # Check power supplies on each of the enclosures
1992   PS:
1993     foreach my $out (@output) {
1994         if ($snmp) {
1995             $id        = $out->{powerSupplyNumber};
1996             $name      = $out->{powerSupplyName};
1997             $state     = $ps_state{$out->{powerSupplyState}};
1998             $status    = $snmp_status{$out->{powerSupplyComponentStatus}};
1999             $encl_id   = $out->{powerSupplyConnectionEnclosureNumber} - 1;
2000             $encl_name = $out->{powerSupplyConnectionEnclosureName};
2001             $nexus     = convert_nexus($out->{powerSupplyNexusID});
2002         }
2003         else {
2004             $id        = $out->{'ID'};
2005             $name      = $out->{'Name'};
2006             $state     = $out->{'State'};
2007             $status    = $out->{'Status'};
2008             $encl_id   = join q{:}, $out->{ctrl}, $out->{'encl_id'};
2009             $encl_name = $out->{encl_name};
2010             $nexus     = join q{:}, $out->{ctrl}, $out->{'encl_id'}, $id;
2011         }
2012
2013         next PS if blacklisted('encl_ps', $nexus);
2014
2015         # Default
2016         if ($status ne 'Ok') {
2017             my $msg = sprintf '%s in enclosure %s [%s] needs attention: %s',
2018               $name, $encl_id, $encl_name, $state;
2019             report('storage', $msg, $status2nagios{$status}, $nexus);
2020         }
2021         # Ok
2022         else {
2023             my $msg = sprintf '%s in enclosure %s [%s] is %s',
2024               $name, $encl_id, $encl_name, $state;
2025             report('storage', $msg, $E_OK, $nexus);
2026         }
2027     }
2028     return;
2029 }
2030
2031
2032 #-----------------------------------------
2033 # STORAGE: Check enclosure temperatures
2034 #-----------------------------------------
2035 sub check_enclosure_temp {
2036     return if $#controllers == -1;
2037
2038     my $id        = undef;
2039     my $nexus     = undef;
2040     my $name      = undef;
2041     my $state     = undef;
2042     my $status    = undef;
2043     my $reading   = undef;
2044     my $unit      = undef;
2045     my $max_warn  = undef;
2046     my $max_crit  = undef;
2047     my $encl_id   = undef;
2048     my $encl_name = undef;
2049     my @output    = ();
2050
2051     if ($snmp) {
2052         my %temp_oid
2053           = (
2054              '1.3.6.1.4.1.674.10893.1.20.130.11.1.1'  => 'temperatureProbeNumber',
2055              '1.3.6.1.4.1.674.10893.1.20.130.11.1.2'  => 'temperatureProbeName',
2056              '1.3.6.1.4.1.674.10893.1.20.130.11.1.4'  => 'temperatureProbeState',
2057              '1.3.6.1.4.1.674.10893.1.20.130.11.1.6'  => 'temperatureProbeUnit',
2058              '1.3.6.1.4.1.674.10893.1.20.130.11.1.9'  => 'temperatureProbeMaxWarning',
2059              '1.3.6.1.4.1.674.10893.1.20.130.11.1.10' => 'temperatureProbeMaxCritical',
2060              '1.3.6.1.4.1.674.10893.1.20.130.11.1.11' => 'temperatureProbeCurValue',
2061              '1.3.6.1.4.1.674.10893.1.20.130.11.1.13' => 'temperatureProbeComponentStatus',
2062              '1.3.6.1.4.1.674.10893.1.20.130.11.1.14' => 'temperatureProbeNexusID',
2063              '1.3.6.1.4.1.674.10893.1.20.130.12.1.4'  => 'temperatureConnectionEnclosureName',
2064              '1.3.6.1.4.1.674.10893.1.20.130.12.1.5'  => 'temperatureConnectionEnclosureNumber',
2065             );
2066         my $result = $snmp_session->get_entries(-columns => [keys %temp_oid]);
2067
2068         # No enclosure temperature probes is OK
2069         return if !defined $result;
2070
2071         @output = @{ get_snmp_output($result, \%temp_oid) };
2072     }
2073     else {
2074         foreach my $enc (@enclosures) {
2075             push @output, @{ run_omreport("storage enclosure controller=$enc->{ctrl} enclosure=$enc->{id} info=temps") };
2076             map_item('ctrl', $enc->{ctrl}, \@output);
2077             map_item('encl_id', $enc->{id}, \@output);
2078             map_item('encl_name', $enc->{name}, \@output);
2079         }
2080     }
2081
2082     my %temp_state
2083       = (
2084          0  => 'Unknown',
2085          1  => 'Ready',
2086          2  => 'Failed',
2087          4  => 'Offline',
2088          6  => 'Degraded',
2089          9  => 'Inactive',
2090          21 => 'Missing',
2091         );
2092
2093     # Check temperature probes on each of the enclosures
2094   TEMP:
2095     foreach my $out (@output) {
2096         if ($snmp) {
2097             $id        = $out->{temperatureProbeNumber} - 1;
2098             $name      = $out->{temperatureProbeName};
2099             $state     = $temp_state{$out->{temperatureProbeState}};
2100             $status    = $snmp_status{$out->{temperatureProbeComponentStatus}};
2101             $unit      = $out->{temperatureProbeUnit};
2102             $reading   = $out->{temperatureProbeCurValue};
2103             $max_warn  = $out->{temperatureProbeMaxWarning};
2104             $max_crit  = $out->{temperatureProbeMaxCritical};
2105             $encl_id   = $out->{temperatureConnectionEnclosureNumber} - 1;
2106             $encl_name = $out->{temperatureConnectionEnclosureName};
2107             $nexus     = convert_nexus($out->{temperatureProbeNexusID});
2108         }
2109         else {
2110             $id        = $out->{'ID'};
2111             $name      = $out->{'Name'};
2112             $state     = $out->{'State'};
2113             $status    = $out->{'Status'};
2114             $unit      = 'FIXME';
2115             $reading   = $out->{'Reading'}; $reading =~ s{\s*C}{}xms;
2116             $max_warn  = $out->{'Maximum Warning Threshold'}; $max_warn =~ s{\s*C}{}xms;
2117             $max_crit  = $out->{'Maximum Failure Threshold'}; $max_crit =~ s{\s*C}{}xms;
2118             $encl_id   = join q{:}, $out->{ctrl}, $out->{'encl_id'};
2119             $encl_name = $out->{encl_name};
2120             $nexus     = join q{:}, $out->{ctrl}, $out->{'encl_id'}, $id;
2121         }
2122
2123         next TEMP if blacklisted('encl_temp', $nexus);
2124
2125         # Default
2126         if ($status ne 'Ok') {
2127             my $msg = sprintf '%s in enclosure %s [%s] is %s C at %s (%s max)',
2128               $name, $encl_id, $encl_name, $state, $reading, $max_crit;
2129             report('storage', $msg, $status2nagios{$status}, $nexus);
2130         }
2131         # Ok
2132         else {
2133             my $msg = sprintf '%s in enclosure %s [%s]: %s C (%s max)',
2134               $name, $encl_id, $encl_name, $reading, $max_crit;
2135             report('storage', $msg, $E_OK, $nexus);
2136         }
2137
2138         # Collect performance data
2139         if (defined $opt{perfdata}) {
2140             $name =~ s{\A Temperature\sProbe\s(\d+) \z}{temp_$1}gxms;
2141             my $pkey = "enclosure_${encl_id}_${name}";
2142             my $pval = join q{;}, "${reading}C", $max_warn, $max_crit;
2143             $perfdata{$pkey} = $pval;
2144         }
2145     }
2146     return;
2147 }
2148
2149
2150 #-----------------------------------------
2151 # STORAGE: Check enclosure management modules (EMM)
2152 #-----------------------------------------
2153 sub check_enclosure_emms {
2154     return if $#controllers == -1;
2155
2156     my $id        = undef;
2157     my $nexus     = undef;
2158     my $name      = undef;
2159     my $state     = undef;
2160     my $status    = undef;
2161     my $encl_id   = undef;
2162     my $encl_name = undef;
2163     my @output    = ();
2164
2165     if ($snmp) {
2166         my %emms_oid
2167           = (
2168              '1.3.6.1.4.1.674.10893.1.20.130.13.1.1'  => 'enclosureManagementModuleNumber',
2169              '1.3.6.1.4.1.674.10893.1.20.130.13.1.2'  => 'enclosureManagementModuleName',
2170              '1.3.6.1.4.1.674.10893.1.20.130.13.1.4'  => 'enclosureManagementModuleState',
2171              '1.3.6.1.4.1.674.10893.1.20.130.13.1.11' => 'enclosureManagementModuleComponentStatus',
2172              '1.3.6.1.4.1.674.10893.1.20.130.13.1.12' => 'enclosureManagementModuleNexusID',
2173              '1.3.6.1.4.1.674.10893.1.20.130.14.1.4'  => 'enclosureManagementModuleConnectionEnclosureName',
2174              '1.3.6.1.4.1.674.10893.1.20.130.14.1.5'  => 'enclosureManagementModuleConnectionEnclosureNumber',
2175             );
2176         my $result = $snmp_session->get_entries(-columns => [keys %emms_oid]);
2177
2178         # No enclosure EMMs is OK
2179         return if !defined $result;
2180
2181         @output = @{ get_snmp_output($result, \%emms_oid) };
2182     }
2183     else {
2184         foreach my $enc (@enclosures) {
2185             push @output, @{ run_omreport("storage enclosure controller=$enc->{ctrl} enclosure=$enc->{id} info=emms") };
2186             map_item('ctrl', $enc->{ctrl}, \@output);
2187             map_item('encl_id', $enc->{id}, \@output);
2188             map_item('encl_name', $enc->{name}, \@output);
2189         }
2190     }
2191
2192     my %emms_state
2193       = (
2194          0  => 'Unknown',
2195          1  => 'Ready',
2196          2  => 'Failed',
2197          3  => 'Online',
2198          4  => 'Offline',
2199          5  => 'Not Installed',
2200          6  => 'Degraded',
2201          21 => 'Missing',
2202         );
2203
2204     # Check temperature probes on each of the enclosures
2205   EMM:
2206     foreach my $out (@output) {
2207         if ($snmp) {
2208             $id        = $out->{enclosureManagementModuleNumber} - 1;
2209             $name      = $out->{enclosureManagementModuleName};
2210             $state     = $emms_state{$out->{enclosureManagementModuleState}};
2211             $status    = $snmp_status{$out->{enclosureManagementModuleComponentStatus}};
2212             $encl_id   = $out->{enclosureManagementModuleConnectionEnclosureNumber} - 1;
2213             $encl_name = $out->{enclosureManagementModuleConnectionEnclosureName};
2214             $nexus     = convert_nexus($out->{enclosureManagementModuleNexusID});
2215         }
2216         else {
2217             $id        = $out->{'ID'};
2218             $name      = $out->{'Name'};
2219             $state     = $out->{'State'};
2220             $status    = $out->{'Status'};
2221             $encl_id   = join q{:}, $out->{ctrl}, $out->{'encl_id'};
2222             $encl_name = $out->{encl_name};
2223             $nexus     = join q{:}, $out->{ctrl}, $out->{'encl_id'}, $id;
2224         }
2225
2226         next EMM if blacklisted('encl_emm', $nexus);
2227
2228         # Default
2229         if ($status ne 'Ok') {
2230             my $msg = sprintf '%s in enclosure %s [%s] needs attention: %s',
2231               $name, $encl_id, $encl_name, $state;
2232             report('storage', $msg, $status2nagios{$status}, $nexus);
2233         }
2234         # Ok
2235         else {
2236             my $msg = sprintf '%s in enclosure %s [%s] is %s',
2237               $name, $encl_id, $encl_name, $state;
2238             report('storage', $msg, $E_OK, $nexus);
2239         }
2240     }
2241     return;
2242 }
2243
2244
2245 #-----------------------------------------
2246 # CHASSIS: Check memory modules
2247 #-----------------------------------------
2248 sub check_memory {
2249     my $index    = undef;
2250     my $status   = undef;
2251     my $location = undef;
2252     my $size     = undef;
2253     my $modes    = undef;
2254     my @failures = ();
2255     my @output   = ();
2256
2257     if ($snmp) {
2258         my %dimm_oid
2259           = (
2260              '1.3.6.1.4.1.674.10892.1.1100.50.1.2.1'  => 'memoryDeviceIndex',
2261              '1.3.6.1.4.1.674.10892.1.1100.50.1.5.1'  => 'memoryDeviceStatus',
2262              '1.3.6.1.4.1.674.10892.1.1100.50.1.8.1'  => 'memoryDeviceLocationName',
2263              '1.3.6.1.4.1.674.10892.1.1100.50.1.14.1' => 'memoryDeviceSize',
2264              '1.3.6.1.4.1.674.10892.1.1100.50.1.20.1' => 'memoryDeviceFailureModes',
2265             );
2266         my $result = $snmp_session->get_entries(-columns => [keys %dimm_oid]);
2267
2268         if (!defined $result) {
2269             printf "SNMP ERROR [memory]: %s.\n", $snmp_session->error;
2270             $snmp_session->close;
2271             exit $E_UNKNOWN;
2272         }
2273
2274         @output = @{ get_snmp_output($result, \%dimm_oid) };
2275     }
2276     else {
2277         @output = @{ run_omreport("$omopt_chassis memory") };
2278     }
2279
2280     # Note: These values are bit masks, so combination values are
2281     # possible. If value is 0 (zero), memory device has no faults.
2282     my %failure_mode
2283       = (
2284          1  => 'ECC single bit correction warning rate exceeded',
2285          2  => 'ECC single bit correction failure rate exceeded',
2286          4  => 'ECC multibit fault encountered',
2287          8  => 'ECC single bit correction logging disabled',
2288          16 => 'device disabled because of spare activation',
2289         );
2290
2291   DIMM:
2292     foreach my $out (@output) {
2293         @failures = ();  # Initialize
2294         if ($snmp) {
2295             $index    = $out->{memoryDeviceIndex};
2296             $status   = $snmp_status{$out->{memoryDeviceStatus}};
2297             $location = $out->{memoryDeviceLocationName};
2298             $size     = sprintf '%d MB', $out->{memoryDeviceSize}/1024;
2299             $modes    = $out->{memoryDeviceFailureModes};
2300             if ($modes > 0) {
2301                 foreach my $mask (sort keys %failure_mode) {
2302                     if (($modes & $mask) != 0) { push @failures, $failure_mode{$mask}; }
2303                 }
2304             }
2305         }
2306         else {
2307             $index    = $out->{'Type'} eq '[Not Occupied]' ? undef : $out->{'Index'};
2308             $status   = $out->{'Status'};
2309             $location = $out->{'Connector Name'};
2310             $size     = $out->{'Size'};
2311             if (defined $size) {
2312                 $size =~ s{\s\s}{ }gxms;
2313             }
2314             # Run 'omreport chassis memory index=X' to get the failures
2315             if ($status ne 'Ok' && defined $index) {
2316                 foreach (@{ run_command("$omreport $omopt_chassis memory index=$index -fmt ssv") }) {
2317                     if (m/\A Failures; (.+?) \z/xms) {
2318                         chop(my $fail = $1);
2319                         push @failures, split m{\.}xms, $fail;
2320                     }
2321                 }
2322             }
2323         }
2324         $location =~ s{\A \s*(.*?)\s* \z}{$1}xms;
2325
2326         next DIMM if blacklisted('dimm', $index);
2327
2328         # Ignore empty memory slots
2329         next DIMM if !defined $index;
2330         $count{dimm}++;
2331
2332         if ($status ne 'Ok') {
2333             my $msg = undef;
2334             if (scalar @failures == 0) {
2335                 $msg = sprintf 'Memory module %d [%s, %s] needs attention (%s)',
2336                   $index, $location, $size, $status;
2337             }
2338             else {
2339                 $msg = sprintf 'Memory module %d [%s, %s] needs attention: %s',
2340                   $index, $location, $size, (join q{, }, @failures);
2341             }
2342
2343             report('chassis', $msg, $status2nagios{$status}, $index);
2344         }
2345         # Ok
2346         else {
2347             my $msg = sprintf 'Memory module %d [%s, %s] is %s',
2348               $index, $location, $size, $status;
2349             report('chassis', $msg, $E_OK, $index);
2350         }
2351     }
2352     return;
2353 }
2354
2355
2356 #-----------------------------------------
2357 # CHASSIS: Check fans
2358 #-----------------------------------------
2359 sub check_fans {
2360     my $index    = undef;
2361     my $status   = undef;
2362     my $reading  = undef;
2363     my $location = undef;
2364     my $max_crit = undef;
2365     my $max_warn = undef;
2366     my @output   = ();
2367
2368     if ($snmp) {
2369         my %cool_oid
2370           = (
2371              '1.3.6.1.4.1.674.10892.1.700.12.1.2.1'  => 'coolingDeviceIndex',
2372              '1.3.6.1.4.1.674.10892.1.700.12.1.5.1'  => 'coolingDeviceStatus',
2373              '1.3.6.1.4.1.674.10892.1.700.12.1.6.1'  => 'coolingDeviceReading',
2374              '1.3.6.1.4.1.674.10892.1.700.12.1.8.1'  => 'coolingDeviceLocationName',
2375              '1.3.6.1.4.1.674.10892.1.700.12.1.10.1' => 'coolingDeviceUpperCriticalThreshold',
2376              '1.3.6.1.4.1.674.10892.1.700.12.1.11.1' => 'coolingDeviceUpperNonCriticalThreshold',
2377             );
2378         my $result = $snmp_session->get_entries(-columns => [keys %cool_oid]);
2379
2380         if ($blade && !defined $result) {
2381             return 0;
2382         }
2383         elsif (!$blade && !defined $result) {
2384             printf "SNMP ERROR [cooling]: %s.\n", $snmp_session->error;
2385             $snmp_session->close;
2386             exit $E_UNKNOWN;
2387         }
2388
2389         @output = @{ get_snmp_output($result, \%cool_oid) };
2390     }
2391     else {
2392         @output = @{ run_omreport("$omopt_chassis fans") };
2393     }
2394
2395   FAN:
2396     foreach my $out (@output) {
2397         if ($snmp) {
2398             $index    = $out->{coolingDeviceIndex};
2399             $status   = $snmp_probestatus{$out->{coolingDeviceStatus}};
2400             $reading  = $out->{coolingDeviceReading};
2401             $location = $out->{coolingDeviceLocationName};
2402             $max_crit = exists $out->{coolingDeviceUpperCriticalThreshold}
2403               ? $out->{coolingDeviceUpperCriticalThreshold} : 0;
2404             $max_warn = exists $out->{coolingDeviceUpperNonCriticalThreshold}
2405               ? $out->{coolingDeviceUpperNonCriticalThreshold} : 0;
2406         }
2407         else {
2408             $index    = $out->{'Index'};
2409             $status   = $out->{'Status'};
2410             $reading  = $out->{'Reading'};
2411             $location = $out->{'Probe Name'};
2412             $max_crit = $out->{'Maximum Failure Threshold'} ne '[N/A]'
2413               ? $out->{'Maximum Failure Threshold'} : 0;
2414             $max_warn = $out->{'Maximum Warning Threshold'} ne '[N/A]'
2415               ? $out->{'Maximum Warning Threshold'} : 0;
2416             $reading  =~ s{\A (\d+).* \z}{$1}xms;
2417             $max_warn =~ s{\A (\d+).* \z}{$1}xms;
2418             $max_crit =~ s{\A (\d+).* \z}{$1}xms;
2419         }
2420
2421         next FAN if blacklisted('fan', $index);
2422         $count{fan}++;
2423
2424         if ($status ne 'Ok') {
2425             my $msg = sprintf 'Chassis fan %d [%s] needs attention: %s',
2426               $index, $location, $status;
2427             my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2428             report('chassis', $msg, $err, $index);
2429         }
2430         else {
2431             my $msg = sprintf 'Chassis fan %d [%s]: %s',
2432               $index, $location, $reading;
2433             report('chassis', $msg, $E_OK, $index);
2434         }
2435
2436         # Collect performance data
2437         if (defined $opt{perfdata}) {
2438             my $pname = lc $location;
2439             $pname =~ s{\s}{_}gxms;
2440             $pname =~ s{proc_}{cpu#}xms;
2441             my $pkey = join q{_}, 'fan', $index, $pname;
2442             my $pval = join q{;}, "${reading}RPM", $max_warn, $max_crit;
2443             $perfdata{$pkey} = $pval;
2444         }
2445     }
2446     return;
2447 }
2448
2449
2450 #-----------------------------------------
2451 # CHASSIS: Check power supplies
2452 #-----------------------------------------
2453 sub check_powersupplies {
2454     my $index    = undef;
2455     my $status   = undef;
2456     my $type     = undef;
2457     my $err_type = undef;
2458     my $state    = undef;
2459     my @states   = ();
2460     my @output   = ();
2461
2462     if ($snmp) {
2463         my %ps_oid
2464           = (
2465              '1.3.6.1.4.1.674.10892.1.600.12.1.2.1'  => 'powerSupplyIndex',
2466              '1.3.6.1.4.1.674.10892.1.600.12.1.5.1'  => 'powerSupplyStatus',
2467              '1.3.6.1.4.1.674.10892.1.600.12.1.7.1'  => 'powerSupplyType',
2468              '1.3.6.1.4.1.674.10892.1.600.12.1.11.1' => 'powerSupplySensorState',
2469              '1.3.6.1.4.1.674.10892.1.600.12.1.12.1' => 'powerSupplyConfigurationErrorType',
2470             );
2471         my $result = $snmp_session->get_entries(-columns => [keys %ps_oid]);
2472
2473         # No instrumented PSU is OK (blades, low-end servers)
2474         return 0 if !defined $result;
2475
2476         @output = @{ get_snmp_output($result, \%ps_oid) };
2477     }
2478     else {
2479         @output = @{ run_omreport("$omopt_chassis pwrsupplies") };
2480     }
2481
2482     my %ps_type
2483       = (
2484          1  => 'Other',
2485          2  => 'Unknown',
2486          3  => 'Linear',
2487          4  => 'Switching',
2488          5  => 'Battery',
2489          6  => 'Uninterruptible Power Supply',
2490          7  => 'Converter',
2491          8  => 'Regulator',
2492          9  => 'AC',
2493          10 => 'DC',
2494          11 => 'VRM',
2495         );
2496
2497     my %ps_state
2498       = (
2499          1  => 'Presence detected',
2500          2  => 'Failure detected',
2501          4  => 'Predictive Failure',
2502          8  => 'AC lost',
2503          16 => 'AC lost or out-of-range',
2504          32 => 'AC out-of-range but present',
2505          64 => 'Configuration error',
2506         );
2507
2508     my %ps_config_error_type
2509       = (
2510          1 => 'Vendor mismatch',
2511          2 => 'Revision mismatch',
2512          3 => 'Processor missing',
2513         );
2514
2515   PS:
2516     foreach my $out (@output) {
2517         if ($snmp) {
2518             @states = ();  # contains states for the PS
2519
2520             $index    = $out->{powerSupplyIndex} - 1;
2521             $status   = $snmp_status{$out->{powerSupplyStatus}};
2522             $type     = $ps_type{$out->{powerSupplyType}};
2523             $err_type = defined $out->{powerSupplyConfigurationErrorType}
2524               ? $ps_config_error_type{$out->{powerSupplyConfigurationErrorType}} : undef;
2525
2526             # get the combined state from the StatusReading OID
2527             foreach my $mask (sort keys %ps_state) {
2528                 if (($out->{powerSupplySensorState} & $mask) != 0) {
2529                     push @states, $ps_state{$mask};
2530                 }
2531             }
2532
2533             # If configuration error, also include the error type
2534             if (defined $err_type) {
2535                 push @states, $err_type;
2536             }
2537
2538             # Finally, construct the state string
2539             $state = join q{, }, @states;
2540         }
2541         else {
2542             $index  = $out->{'Index'};
2543             $status = $out->{'Status'};
2544             $type   = $out->{'Type'};
2545             $state  = $out->{'Online Status'};
2546         }
2547
2548         next PS if blacklisted('ps', $index);
2549         $count{power}++;
2550
2551         if ($status ne 'Ok') {
2552             my $msg = sprintf 'Power Supply %d [%s] needs attention: %s',
2553               $index, $type, $state;
2554             report('chassis', $msg, $status2nagios{$status}, $index);
2555         }
2556         else {
2557             my $msg = sprintf 'Power Supply %d [%s]: %s',
2558               $index, $type, $state;
2559             report('chassis', $msg, $E_OK, $index);
2560         }
2561     }
2562     return;
2563 }
2564
2565
2566 #-----------------------------------------
2567 # CHASSIS: Check temperatures
2568 #-----------------------------------------
2569 sub check_temperatures {
2570     my $index    = undef;
2571     my $status   = undef;
2572     my $reading  = undef;
2573     my $location = undef;
2574     my $max_crit = undef;
2575     my $max_warn = undef;
2576     my $min_warn = undef;
2577     my $min_crit = undef;
2578     my $type     = undef;
2579     my $discrete = undef;
2580     my @output = ();
2581
2582     # Getting custom temperature thresholds (user option)
2583     my %warn_threshold = %{ custom_temperature_thresholds('w') };
2584     my %crit_threshold = %{ custom_temperature_thresholds('c') };
2585
2586     if ($snmp) {
2587         my %temp_oid
2588           = (
2589              '1.3.6.1.4.1.674.10892.1.700.20.1.2.1'  => 'temperatureProbeIndex',
2590              '1.3.6.1.4.1.674.10892.1.700.20.1.5.1'  => 'temperatureProbeStatus',
2591              '1.3.6.1.4.1.674.10892.1.700.20.1.6.1'  => 'temperatureProbeReading',
2592              '1.3.6.1.4.1.674.10892.1.700.20.1.7.1'  => 'temperatureProbeType',
2593              '1.3.6.1.4.1.674.10892.1.700.20.1.8.1'  => 'temperatureProbeLocationName',
2594              '1.3.6.1.4.1.674.10892.1.700.20.1.10.1' => 'temperatureProbeUpperCriticalThreshold',
2595              '1.3.6.1.4.1.674.10892.1.700.20.1.11.1' => 'temperatureProbeUpperNonCriticalThreshold',
2596              '1.3.6.1.4.1.674.10892.1.700.20.1.12.1' => 'temperatureProbeLowerNonCriticalThreshold',
2597              '1.3.6.1.4.1.674.10892.1.700.20.1.13.1' => 'temperatureProbeLowerCriticalThreshold',
2598              '1.3.6.1.4.1.674.10892.1.700.20.1.16.1' => 'temperatureProbeDiscreteReading',
2599             );
2600         # this didn't work well for some reason
2601         #my $result = $snmp_session->get_entries(-columns => [keys %temp_oid]);
2602
2603         # Getting values using the table
2604         my $temperatureProbeTable = '1.3.6.1.4.1.674.10892.1.700.20';
2605         my $result = $snmp_session->get_table(-baseoid => $temperatureProbeTable);
2606
2607         if (!defined $result) {
2608             printf "SNMP ERROR [temperatures]: %s.\n", $snmp_session->error;
2609             $snmp_session->close;
2610             exit $E_UNKNOWN;
2611         }
2612
2613         @output = @{ get_snmp_output($result, \%temp_oid) };
2614     }
2615     else {
2616         @output = @{ run_omreport("$omopt_chassis temps") };
2617     }
2618
2619     my %probe_type
2620       = (
2621          1  => 'Other',      # type is other than following values
2622          2  => 'Unknown',    # type is unknown
2623          3  => 'AmbientESM', # type is Ambient Embedded Systems Management temperature probe
2624          16 => 'Discrete',   # type is temperature probe with discrete reading
2625         );
2626
2627   TEMP:
2628     foreach my $out (@output) {
2629         if ($snmp) {
2630             $index    = $out->{temperatureProbeIndex} - 1;
2631             $status   = $snmp_probestatus{$out->{temperatureProbeStatus}};
2632             $reading  = $out->{temperatureProbeReading} / 10;
2633             $location = $out->{temperatureProbeLocationName};
2634             $max_crit = $out->{temperatureProbeUpperCriticalThreshold} / 10;
2635             $max_warn = $out->{temperatureProbeUpperNonCriticalThreshold} / 10;
2636             $min_crit = exists $out->{temperatureProbeLowerCriticalThreshold}
2637               ? $out->{temperatureProbeLowerCriticalThreshold} / 10 : '[N/A]';
2638             $min_warn = exists $out->{temperatureProbeLowerNonCriticalThreshold}
2639               ? $out->{temperatureProbeLowerNonCriticalThreshold} / 10 : '[N/A]';
2640             $type     = $probe_type{$out->{temperatureProbeType}};
2641             $discrete = exists $out->{temperatureProbeDiscreteReading}
2642               ? $out->{temperatureProbeDiscreteReading} : undef;
2643         }
2644         else {
2645             $index    = $out->{'Index'};
2646             $status   = $out->{'Status'};
2647             $reading  = $out->{'Reading'}; $reading =~ s{\.0\s+C}{}xms;
2648             $location = $out->{'Probe Name'};
2649             $max_crit = $out->{'Maximum Failure Threshold'}; $max_crit =~ s{\.0\s+C}{}xms;
2650             $max_warn = $out->{'Maximum Warning Threshold'}; $max_warn =~ s{\.0\s+C}{}xms;
2651             $min_crit = $out->{'Minimum Failure Threshold'}; $min_crit =~ s{\.0\s+C}{}xms;
2652             $min_warn = $out->{'Minimum Warning Threshold'}; $min_warn =~ s{\.0\s+C}{}xms;
2653             $type     = $reading =~ m{\A\d+\z}xms ? 'AmbientESM' : 'Discrete';
2654             $discrete = $reading;
2655         }
2656
2657         next TEMP if blacklisted('temp', $index);
2658         $count{temp}++;
2659
2660         if ($type eq 'Discrete') {
2661             my $msg = sprintf 'Temperature probe %d (%s): is %s',
2662               $index, $location, $discrete;
2663             my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2664             report('chassis', $msg, $err, $index);
2665         }
2666         else {
2667             # First check according to custom thresholds
2668             if (exists $crit_threshold{$index}{max} and $reading > $crit_threshold{$index}{max}) {
2669                 # Custom critical MAX
2670                 my $msg = sprintf 'Temperature Probe %d [%s] reads %d C (custom max=%d)',
2671                   $index, $location, $reading, $crit_threshold{$index}{max};
2672                 report('chassis', $msg, $E_CRITICAL, $index);
2673             }
2674             elsif (exists $warn_threshold{$index}{max} and $reading > $warn_threshold{$index}{max}) {
2675                 # Custom warning MAX
2676                 my $msg = sprintf 'Temperature Probe %d [%s] reads %d C (custom max=%d)',
2677                   $index, $location, $reading, $warn_threshold{$index}{max};
2678                 report('chassis', $msg, $E_WARNING, $index);
2679             }
2680             elsif (exists $crit_threshold{$index}{min} and $reading < $crit_threshold{$index}{min}) {
2681                 # Custom critical MIN
2682                 my $msg = sprintf 'Temperature Probe %d [%s] reads %d C (custom min=%d)',
2683                   $index, $location, $reading, $crit_threshold{$index}{min};
2684                 report('chassis', $msg, $E_CRITICAL, $index);
2685             }
2686             elsif (exists $warn_threshold{$index}{min} and $reading < $warn_threshold{$index}{min}) {
2687                 # Custom warning MIN
2688                 my $msg = sprintf 'Temperature Probe %d [%s] reads %d C (custom min=%d)',
2689                   $index, $location, $reading, $warn_threshold{$index}{min};
2690                 report('chassis', $msg, $E_WARNING, $index);
2691             }
2692             elsif ($status ne 'Ok' and $max_crit ne '[N/A]' and $reading > $max_crit) {
2693                 my $msg = sprintf 'Temperature Probe %d [%s] is critically high at %d C',
2694                   $index, $location, $reading;
2695                 my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2696                 report('chassis', $msg, $err, $index);
2697             }
2698             elsif ($status ne 'Ok' and $max_warn ne '[N/A]' and $reading > $max_warn) {
2699                 my $msg = sprintf 'Temperature Probe %d [%s] is too high at %d C',
2700                   $index, $location, $reading;
2701                 my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2702                 report('chassis', $msg, $err, $index);
2703             }
2704             elsif ($status ne 'Ok' and $min_crit ne '[N/A]' and $reading < $min_crit) {
2705                 my $msg = sprintf 'Temperature Probe %d [%s] is critically low at %d C',
2706                   $index, $location, $reading;
2707                 my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2708                 report('chassis', $msg, $err, $index);
2709             }
2710             elsif ($status ne 'Ok' and $min_warn ne '[N/A]' and $reading < $min_warn) {
2711                 my $msg = sprintf 'Temperature Probe %d [%s] is too low at %d C',
2712                   $index, $location, $reading;
2713                 my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2714                 report('chassis', $msg, $err, $index);
2715             }
2716             # Ok
2717             else {
2718                 my $msg = sprintf 'Temperature Probe %d [%s] reads %d C',
2719                   $index, $location, $reading;
2720                 if ($min_warn eq '[N/A]' and $min_crit eq '[N/A]') {
2721                     $msg .= sprintf ' (max=%s/%s)', $max_warn, $max_crit;
2722                 }
2723                 else {
2724                     $msg .= sprintf ' (min=%s/%s, max=%s/%s)',
2725                       $min_warn, $min_crit, $max_warn, $max_crit;
2726                 }                   
2727                 my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2728                 report('chassis', $msg, $err, $index);
2729             }
2730
2731             # Collect performance data
2732             if (defined $opt{perfdata}) {
2733                 my $pname = lc $location;
2734                 $pname =~ s{\s}{_}gxms;
2735                 $pname =~ s{_temp\z}{}xms;
2736                 $pname =~ s{proc_}{cpu#}xms;
2737                 my $pkey = join q{_}, 'temp', $index, $pname;
2738                 my $pval = join q{;}, "${reading}C", $max_warn, $max_crit;
2739                 $perfdata{$pkey} = $pval;
2740             }
2741         }
2742     }
2743     return;
2744 }
2745
2746
2747 #-----------------------------------------
2748 # CHASSIS: Check processors
2749 #-----------------------------------------
2750 sub check_processors {
2751     my $index   = undef;
2752     my $status  = undef;
2753     my $state   = undef;
2754     my $oid_ver = 'new';
2755     my @output  = ();
2756
2757     if ($snmp) {
2758
2759         # NOTE: For some reason, older models don't have the
2760         # "Processor Device Status" OIDs. We first check the newer
2761         # (preferred) OIDs, and if that doesn't work, check the "old"
2762         # OIDs.
2763
2764         my %cpu_oid_new  # for newer models
2765           = (
2766              '1.3.6.1.4.1.674.10892.1.1100.32.1.2.1' => 'processorDeviceStatusIndex',
2767              '1.3.6.1.4.1.674.10892.1.1100.32.1.5.1' => 'processorDeviceStatusStatus',
2768              '1.3.6.1.4.1.674.10892.1.1100.32.1.6.1' => 'processorDeviceStatusReading',
2769             );
2770
2771         my %cpu_oid_old  # for older models
2772           = (
2773              '1.3.6.1.4.1.674.10892.1.1100.30.1.2.1' => 'processorDeviceIndex',
2774              '1.3.6.1.4.1.674.10892.1.1100.30.1.5.1' => 'processorDeviceStatus',
2775              '1.3.6.1.4.1.674.10892.1.1100.30.1.9.1' => 'processorDeviceStatusState',
2776             );
2777
2778         my $result = $snmp_session->get_entries(-columns => [keys %cpu_oid_new]);
2779
2780         if (!defined $result) {
2781             $oid_ver = 'old';
2782             $result = $snmp_session->get_entries(-columns => [keys %cpu_oid_old]);
2783         }
2784
2785         if (!defined $result) {
2786             printf "SNMP ERROR [processors]: %s.\n", $snmp_session->error;
2787             $snmp_session->close;
2788             exit $E_UNKNOWN;
2789         }
2790
2791         if ($oid_ver eq 'new') {
2792             @output = @{ get_snmp_output($result, \%cpu_oid_new) };
2793         }
2794         else {
2795             @output = @{ get_snmp_output($result, \%cpu_oid_old) };
2796         }
2797     }
2798     else {
2799         @output = @{ run_omreport("$omopt_chassis processors") };
2800     }
2801
2802     my %cpu_state
2803       = (
2804          1 => 'Other',         # other than following values
2805          2 => 'Unknown',       # unknown
2806          3 => 'Enabled',       # enabled
2807          4 => 'User Disabled', # disabled by user via BIOS setup
2808          5 => 'BIOS Disabled', # disabled by BIOS (POST error)
2809          6 => 'Idle',          # idle
2810         );
2811
2812     my %cpu_reading
2813       = (
2814          1    => 'Internal Error',      # Internal Error
2815          2    => 'Thermal Trip',        # Thermal Trip
2816          32   => 'Configuration Error', # Configuration Error
2817          128  => 'Present',             # Processor Present
2818          256  => 'Disabled',            # Processor Disabled
2819          512  => 'Terminator Present',  # Terminator Present
2820          1024 => 'Throttled',           # Processor Throttled
2821         );
2822
2823
2824   CPU:
2825     foreach my $out (@output) {
2826         if ($snmp) {
2827             if ($oid_ver eq 'new') {
2828                 my @states  = ();  # contains states for the CPU
2829                 $index  = $out->{processorDeviceStatusIndex} - 1;
2830                 $status = $snmp_status{$out->{processorDeviceStatusStatus}};
2831
2832                 # get the combined state from the StatusReading OID
2833                 foreach my $mask (sort keys %cpu_reading) {
2834                     if (($out->{processorDeviceStatusReading} & $mask) != 0) {
2835                         push @states, $cpu_reading{$mask};
2836                     }
2837                 }
2838
2839                 # Finally, create the state string
2840                 $state = join q{, }, @states;
2841             }
2842             else {
2843                 $index  = $out->{processorDeviceIndex} - 1;
2844                 $status = $snmp_status{$out->{processorDeviceStatus}};
2845                 $state  = $cpu_state{$out->{processorDeviceStatusState}};
2846             }
2847         }
2848         else {
2849             $index  = $out->{'Index'};
2850             $status = $out->{'Status'};
2851             $state  = $out->{'State'};
2852         }
2853
2854         next CPU if blacklisted('cpu', $index);
2855
2856         # Ignore unoccupied CPU slots (omreport)
2857         next CPU if (defined $out->{'Processor Manufacturer'}
2858                      and $out->{'Processor Manufacturer'} eq '[Not Occupied]')
2859           or (defined $out->{'Processor Brand'} and $out->{'Processor Brand'} eq '[Not Occupied]');
2860
2861         # Ignore unoccupied CPU slots (snmp)
2862         if ($snmp and exists $out->{processorDeviceStatusReading}
2863             and $out->{processorDeviceStatusReading} == 0) {
2864             next CPU;
2865         }
2866
2867         $count{cpu}++;
2868
2869         # Default
2870         if ($status ne 'Ok') {
2871             my $msg = sprintf 'CPU %d needs attention: %s',
2872               $index, $state;
2873             report('chassis', $msg, $status2nagios{$status}, $index);
2874         }
2875         # Ok
2876         else {
2877             my $msg = sprintf 'CPU %d is %s',
2878               $index, $state;
2879             report('chassis', $msg, $E_OK, $index);
2880         }
2881     }
2882     return;
2883 }
2884
2885
2886 #-----------------------------------------
2887 # CHASSIS: Check voltage probes
2888 #-----------------------------------------
2889 sub check_volts {
2890     my $index    = undef;
2891     my $status   = undef;
2892     my $reading  = undef;
2893     my $location = undef;
2894     my @output = ();
2895
2896     if ($snmp) {
2897         my %volt_oid
2898           = (
2899              '1.3.6.1.4.1.674.10892.1.600.20.1.2.1'  => 'voltageProbeIndex',
2900              '1.3.6.1.4.1.674.10892.1.600.20.1.5.1'  => 'voltageProbeStatus',
2901              '1.3.6.1.4.1.674.10892.1.600.20.1.6.1'  => 'voltageProbeReading',
2902              '1.3.6.1.4.1.674.10892.1.600.20.1.8.1'  => 'voltageProbeLocationName',
2903              '1.3.6.1.4.1.674.10892.1.600.20.1.16.1' => 'voltageProbeDiscreteReading',
2904             );
2905
2906         my $voltageProbeTable = '1.3.6.1.4.1.674.10892.1.600.20.1';
2907         my $result = $snmp_session->get_table(-baseoid => $voltageProbeTable);
2908
2909         if (!defined $result) {
2910             printf "SNMP ERROR [voltage]: %s.\n", $snmp_session->error;
2911             $snmp_session->close;
2912             exit $E_UNKNOWN;
2913         }
2914
2915         @output = @{ get_snmp_output($result, \%volt_oid) };
2916     }
2917     else {
2918         @output = @{ run_omreport("$omopt_chassis volts") };
2919     }
2920
2921     my %volt_discrete_reading
2922       = (
2923          1 => 'Good',
2924          2 => 'Bad',
2925         );
2926
2927   VOLT:
2928     foreach my $out (@output) {
2929         if ($snmp) {
2930             $index    = $out->{voltageProbeIndex} - 1;
2931             $status   = $snmp_status{$out->{voltageProbeStatus}};
2932             $reading  = exists $out->{voltageProbeReading}
2933               ? sprintf('%.3f V', $out->{voltageProbeReading}/1000)
2934               : $volt_discrete_reading{$out->{voltageProbeDiscreteReading}};
2935             $location = $out->{voltageProbeLocationName};
2936         }
2937         else {
2938             $index    = $out->{'Index'};
2939             $status   = $out->{'Status'};
2940             $reading  = $out->{'Reading'};
2941             $location = $out->{'Probe Name'};
2942         }
2943
2944         next VOLT if blacklisted('volt', $index);
2945         $count{volt}++;
2946
2947         my $msg = sprintf 'Voltage sensor %d [%s] is %s',
2948           $index, $location, $reading;
2949         my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2950         report('chassis', $msg, $err, $index);
2951     }
2952     return;
2953 }
2954
2955
2956 #-----------------------------------------
2957 # CHASSIS: Check batteries
2958 #-----------------------------------------
2959 sub check_batteries {
2960     my $index    = undef;
2961     my $status   = undef;
2962     my $reading  = undef;
2963     my $location = undef;
2964     my @output = ();
2965
2966     if ($snmp) {
2967         my %bat_oid
2968           = (
2969              '1.3.6.1.4.1.674.10892.1.600.50.1.2.1' => 'batteryIndex',
2970              '1.3.6.1.4.1.674.10892.1.600.50.1.5.1' => 'batteryStatus',
2971              '1.3.6.1.4.1.674.10892.1.600.50.1.6.1' => 'batteryReading',
2972              '1.3.6.1.4.1.674.10892.1.600.50.1.7.1' => 'batteryLocationName',
2973             );
2974         my $result = $snmp_session->get_entries(-columns => [keys %bat_oid]);
2975
2976         # No batteries is OK
2977         return 0 if !defined $result;
2978
2979         @output = @{ get_snmp_output($result, \%bat_oid) };
2980     }
2981     else {
2982         @output = @{ run_omreport("$omopt_chassis batteries") };
2983     }
2984
2985     my %bat_reading
2986       = (
2987          1 => 'Predictive Failure',
2988          2 => 'Failed',
2989          4 => 'Presence Detected',
2990         );
2991
2992   BATTERY:
2993     foreach my $out (@output) {
2994         if ($snmp) {
2995             $index    = $out->{batteryIndex} - 1;
2996             $status   = $snmp_status{$out->{batteryStatus}};
2997             $reading  = $bat_reading{$out->{batteryReading}};
2998             $location = $out->{batteryLocationName};
2999         }
3000         else {
3001             $index    = $out->{'Index'};
3002             $status   = $out->{'Status'};
3003             $reading  = $out->{'Reading'};
3004             $location = $out->{'Probe Name'};
3005         }
3006
3007         next BATTERY if blacklisted('bp', $index);
3008         $count{bat}++;
3009
3010         my $msg = sprintf 'Battery probe %d [%s] is %s',
3011           $index, $location, $reading;
3012         report('chassis', $msg, $status2nagios{$status}, $index);
3013     }
3014     return;
3015 }
3016
3017
3018 #-----------------------------------------
3019 # CHASSIS: Check amperage probes (power monitoring)
3020 #-----------------------------------------
3021 sub check_pwrmonitoring {
3022     my $index    = undef;
3023     my $status   = undef;
3024     my $reading  = undef;
3025     my $location = undef;
3026     my $max_crit = undef;
3027     my $max_warn = undef;
3028     my $unit     = undef;
3029     my @output = ();
3030
3031     if ($snmp) {
3032         my %amp_oid
3033           = (
3034              '1.3.6.1.4.1.674.10892.1.600.30.1.2.1'  => 'amperageProbeIndex',
3035              '1.3.6.1.4.1.674.10892.1.600.30.1.5.1'  => 'amperageProbeStatus',
3036              '1.3.6.1.4.1.674.10892.1.600.30.1.6.1'  => 'amperageProbeReading',
3037              '1.3.6.1.4.1.674.10892.1.600.30.1.7.1'  => 'amperageProbeType',
3038              '1.3.6.1.4.1.674.10892.1.600.30.1.8.1'  => 'amperageProbeLocationName',
3039              '1.3.6.1.4.1.674.10892.1.600.30.1.10.1' => 'amperageProbeUpperCriticalThreshold',
3040              '1.3.6.1.4.1.674.10892.1.600.30.1.11.1' => 'amperageProbeUpperNonCriticalThreshold',
3041              '1.3.6.1.4.1.674.10892.1.600.30.1.16.1' => 'amperageProbeDiscreteReading',
3042             );
3043         my $result = $snmp_session->get_entries(-columns => [keys %amp_oid]);
3044
3045         # No pwrmonitoring is OK
3046         return 0 if !defined $result;
3047
3048         @output = @{ get_snmp_output($result, \%amp_oid) };
3049     }
3050     else {
3051         @output = @{ run_omreport("$omopt_chassis pwrmonitoring") };
3052     }
3053
3054     my %amp_type   # Amperage probe types
3055       = (
3056          1  => 'amperageProbeTypeIsOther',            # other than following values
3057          2  => 'amperageProbeTypeIsUnknown',          # unknown
3058          3  => 'amperageProbeTypeIs1Point5Volt',      # 1.5 amperage probe
3059          4  => 'amperageProbeTypeIs3Point3volt',      # 3.3 amperage probe
3060          5  => 'amperageProbeTypeIs5Volt',            # 5 amperage probe
3061          6  => 'amperageProbeTypeIsMinus5Volt',       # -5 amperage probe
3062          7  => 'amperageProbeTypeIs12Volt',           # 12 amperage probe
3063          8  => 'amperageProbeTypeIsMinus12Volt',      # -12 amperage probe
3064          9  => 'amperageProbeTypeIsIO',               # I/O probe
3065          10 => 'amperageProbeTypeIsCore',             # Core probe
3066          11 => 'amperageProbeTypeIsFLEA',             # FLEA (standby) probe
3067          12 => 'amperageProbeTypeIsBattery',          # Battery probe
3068          13 => 'amperageProbeTypeIsTerminator',       # SCSI Termination probe
3069          14 => 'amperageProbeTypeIs2Point5Volt',      # 2.5 amperage probe
3070          15 => 'amperageProbeTypeIsGTL',              # GTL (ground termination logic) probe
3071          16 => 'amperageProbeTypeIsDiscrete',         # amperage probe with discrete reading
3072          23 => 'amperageProbeTypeIsPowerSupplyAmps',  # Power Supply probe with reading in Amps
3073          24 => 'amperageProbeTypeIsPowerSupplyWatts', # Power Supply probe with reading in Watts
3074          25 => 'amperageProbeTypeIsSystemAmps',       # System probe with reading in Amps
3075          26 => 'amperageProbeTypeIsSystemWatts',      # System probe with reading in Watts
3076         );
3077
3078     my %amp_discrete
3079       = (
3080          1 => 'Good',
3081          2 => 'Bad',
3082         );
3083
3084     my %amp_unit
3085       = (
3086          'amperageProbeTypeIsPowerSupplyAmps'  => 'hA',  # tenths of Amps
3087          'amperageProbeTypeIsSystemAmps'       => 'hA',  # tenths of Amps
3088          'amperageProbeTypeIsPowerSupplyWatts' => 'W',   # Watts
3089          'amperageProbeTypeIsSystemWatts'      => 'W',   # Watts
3090          'amperageProbeTypeIsDiscrete'         => q{},   # discrete reading, no unit
3091         );
3092
3093   AMP:
3094     foreach my $out (@output) {
3095         if ($snmp) {
3096             $index    = $out->{amperageProbeIndex} - 1;
3097             $status   = $snmp_status{$out->{amperageProbeStatus}};
3098             $reading  = $amp_type{$out->{amperageProbeType}} eq 'amperageProbeTypeIsDiscrete'
3099               ? $amp_discrete{$out->{amperageProbeDiscreteReading}}
3100                 : $out->{amperageProbeReading};
3101             $location = $out->{amperageProbeLocationName};
3102             $max_crit = exists $out->{amperageProbeUpperCriticalThreshold}
3103               ? $out->{amperageProbeUpperCriticalThreshold} : 0;
3104             $max_warn = exists $out->{amperageProbeUpperNonCriticalThreshold}
3105               ? $out->{amperageProbeUpperNonCriticalThreshold} : 0;
3106             $unit     = exists $amp_unit{$amp_type{$out->{amperageProbeType}}}
3107               ? $amp_unit{$amp_type{$out->{amperageProbeType}}} : 'mA';
3108             if ($unit eq 'hA') {
3109                 $reading  /= 10;
3110                 $max_crit /= 10;
3111                 $max_warn /= 10;
3112                 $unit      = 'A';
3113             }
3114         }
3115         else {
3116             $index    = $out->{'Index'};
3117             next if $index !~ m/^\d+$/x;
3118             $status   = $out->{'Status'};
3119             $reading  = $out->{'Reading'};
3120             $location = $out->{'Probe Name'};
3121             $max_crit = $out->{'Failure Threshold'} ne '[N/A]'
3122               ? $out->{'Failure Threshold'} : 0;
3123             $max_warn = $out->{'Warning Threshold'} ne '[N/A]'
3124               ? $out->{'Warning Threshold'} : 0;
3125             $reading  =~ s{\A (\d+.*?)\s+([a-zA-Z]+) \s*\z}{$1}xms;
3126             $unit     = $2;
3127             $max_warn =~ s{\A (\d+.*?)\s+[a-zA-Z]+ \s*\z}{$1}xms;
3128             $max_crit =~ s{\A (\d+.*?)\s+[a-zA-Z]+ \s*\z}{$1}xms;
3129         }
3130
3131         next AMP if blacklisted('pm', $index);
3132         next AMP if $index !~ m{\A \d+ \z}xms;
3133         $count{amp}++;
3134
3135         my $msg = sprintf 'Amperage probe %d [%s] reads %s %s',
3136           $index, $location, $reading, $unit, $status;
3137         report('chassis', $msg, $status2nagios{$status}, $index);
3138
3139         # Collect performance data
3140         if (defined $opt{perfdata}) {
3141             next AMP if $reading !~ m{\A \d+(\.\d+)? \z}xms; # discrete reading (not number)
3142             my $pname = lc $location;
3143             $pname =~ s{\s}{_}gxms;
3144             my $pkey = join q{_}, 'pwr_mon', $index, $pname;
3145             my $pval = join q{;}, "$reading$unit", $max_warn, $max_crit;
3146             $perfdata{$pkey} = $pval;
3147         }
3148     }
3149
3150     # Collect EXTRA performance data not found at first run. This is a
3151     # rather ugly hack
3152     if (defined $opt{perfdata} && !$snmp) {
3153         my $found = 0;
3154         my $index = 0;
3155         my %used  = ();
3156
3157         # find used indexes
3158         foreach (keys %perfdata) {
3159             if (m/\A pwr_mon_(\d+)/xms) {
3160                 $used{$1} = 1;
3161             }
3162         }
3163
3164       AMP2:
3165         foreach my $line (@{ run_command("$omreport $omopt_chassis pwrmonitoring -fmt ssv") }) {
3166             chop $line;
3167             if ($line eq 'Location;Reading') {
3168                 $found = 1;
3169                 next AMP2;
3170             }
3171             if ($line eq q{}) {
3172                 $found = 0;
3173                 next AMP2;
3174             }
3175             if ($found and $line =~ m/\A ([^;]+?) ; (\d*\.\d+) \s ([AW]) \z/xms) {
3176                 my $aname = lc $1;
3177                 my $aval = $2;
3178                 my $aunit = $3;
3179                 $aname =~ s{\s}{_}gxms;
3180
3181                 # don't use an existing index
3182                 while (exists $used{$index}) { ++$index; }
3183
3184                 $perfdata{"pwr_mon_${index}_${aname}"} = "$aval$aunit;0;0";
3185                 ++$index;
3186             }
3187         }
3188     }
3189
3190     return;
3191 }
3192
3193
3194 #-----------------------------------------
3195 # CHASSIS: Check intrusion
3196 #-----------------------------------------
3197 sub check_intrusion {
3198     my $index    = undef;
3199     my $status   = undef;
3200     my $reading  = undef;
3201     my @output = ();
3202
3203     if ($snmp) {
3204         my %int_oid
3205           = (
3206              '1.3.6.1.4.1.674.10892.1.300.70.1.2.1' => 'intrusionIndex',
3207              '1.3.6.1.4.1.674.10892.1.300.70.1.5.1' => 'intrusionStatus',
3208              '1.3.6.1.4.1.674.10892.1.300.70.1.6.1' => 'intrusionReading',
3209             );
3210         my $result = $snmp_session->get_entries(-columns => [keys %int_oid]);
3211
3212         # No intrusion is OK
3213         return 0 if !defined $result;
3214
3215         @output = @{ get_snmp_output($result, \%int_oid) };
3216     }
3217     else {
3218         @output = @{ run_omreport("$omopt_chassis intrusion") };
3219     }
3220
3221     my %int_reading
3222       = (
3223          1 => 'Not Breached',          # chassis not breached and no uncleared breaches
3224          2 => 'Breached',              # chassis currently breached
3225          3 => 'Breached Prior',        # chassis breached prior to boot and has not been cleared
3226          4 => 'Breach Sensor Failure', # intrusion sensor has failed
3227         );
3228
3229   INTRUSION:
3230     foreach my $out (@output) {
3231         if ($snmp) {
3232             $index    = $out->{intrusionIndex} - 1;
3233             $status   = $snmp_status{$out->{intrusionStatus}};
3234             $reading  = $int_reading{$out->{intrusionReading}};
3235         }
3236         else {
3237             $index    = $out->{'Index'};
3238             $status   = $out->{'Status'};
3239             $reading  = $out->{'State'};
3240         }
3241
3242         next INTRUSION if blacklisted('intr', $index);
3243         $count{intr}++;
3244
3245         if ($status ne 'Ok') {
3246             my $msg = sprintf 'Chassis intrusion %d detected: %s',
3247               $index, $reading;
3248             report('chassis', $msg, $E_WARNING, $index);
3249         }
3250         # Ok
3251         else {
3252             my $msg = sprintf 'Chassis intrusion %d detection: %s (%s)',
3253               $index, $status, $reading;
3254             report('chassis', $msg, $E_OK, $index);
3255         }
3256     }
3257     return;
3258 }
3259
3260
3261 #-----------------------------------------
3262 # CHASSIS: Check alert log
3263 #-----------------------------------------
3264 sub check_alertlog {
3265     return if $snmp; # Not supported with SNMP
3266
3267     my @output = @{ run_omreport("$omopt_system alertlog") };
3268     foreach my $out (@output) {
3269         ++$count{alert}{$out->{Severity}};
3270     }
3271
3272     # Create error messages and set exit value if appropriate
3273     my $err = 0;
3274     if ($count{alert}{'Critical'} > 0)        { $err = $E_CRITICAL; }
3275     elsif ($count{alert}{'Non-Critical'} > 0) { $err = $E_WARNING;  }
3276
3277     my $msg = sprintf 'Alert log content: %d critical, %d non-critical, %d ok',
3278       $count{alert}{'Critical'}, $count{alert}{'Non-Critical'}, $count{alert}{'Ok'};
3279     report('other', $msg, $err);
3280
3281     return;
3282 }
3283
3284 #-----------------------------------------
3285 # CHASSIS: Check ESM log overall health
3286 #-----------------------------------------
3287 sub check_esmlog_health {
3288     my $health = 'Ok';
3289
3290     if ($snmp) {
3291         my $systemStateEventLogStatus = '1.3.6.1.4.1.674.10892.1.200.10.1.41.1';
3292         my $result = $snmp_session->get_request(-varbindlist => [$systemStateEventLogStatus]);
3293         if (!defined $result) {
3294             my $msg = sprintf 'SNMP ERROR [esmhealth]: %s',
3295               $snmp_session->error;
3296             report('other', $msg, $E_UNKNOWN);
3297         }
3298         $health = $snmp_status{$result->{$systemStateEventLogStatus}};
3299     }
3300     else {
3301         foreach (@{ run_command("$omreport $omopt_system esmlog -fmt ssv") }) {
3302             if (m/\A Health;(.+) \z/xms) {
3303                 $health = $1;
3304                 chop $health;
3305                 last;
3306             }
3307         }
3308     }
3309
3310     # If the overall health of the ESM log is other than "Ok", the
3311     # fill grade of the log is more than 80% and the log should be
3312     # cleared
3313     if ($health eq 'Ok') {
3314         my $msg = sprintf 'ESM log health is Ok (less than 80%% full)';
3315         report('other', $msg, $E_OK);
3316     }
3317     elsif ($health eq 'Critical') {
3318         my $msg = sprintf 'ESM log is 100%% full';
3319         report('other', $msg, $status2nagios{$health});
3320     }
3321     else {
3322         my $msg = sprintf 'ESM log is more than 80%% full';
3323         report('other', $msg, $status2nagios{$health});
3324     }
3325
3326     return;
3327 }
3328
3329 #-----------------------------------------
3330 # CHASSIS: Check ESM log
3331 #-----------------------------------------
3332 sub check_esmlog {
3333     my @output = ();
3334
3335     if ($snmp) {
3336         my %esm_oid
3337           = (
3338              '1.3.6.1.4.1.674.10892.1.300.40.1.7.1'  => 'eventLogSeverityStatus',
3339             );
3340         my $result = $snmp_session->get_entries(-columns => [keys %esm_oid]);
3341
3342         # No entries is OK
3343         return if !defined $result;
3344
3345         @output = @{ get_snmp_output($result, \%esm_oid) };
3346         foreach my $out (@output) {
3347             ++$count{esm}{$snmp_status{$out->{eventLogSeverityStatus}}};
3348         }
3349     }
3350     else {
3351         @output = @{ run_omreport("$omopt_system esmlog") };
3352         foreach my $out (@output) {
3353             ++$count{esm}{$out->{Severity}};
3354         }
3355     }
3356
3357     # Create error messages and set exit value if appropriate
3358     my $err = 0;
3359     if ($count{esm}{'Critical'} > 0)        { $err = $E_CRITICAL; }
3360     elsif ($count{esm}{'Non-Critical'} > 0) { $err = $E_WARNING;  }
3361
3362     my $msg = sprintf 'ESM log content: %d critical, %d non-critical, %d ok',
3363       $count{esm}{'Critical'}, $count{esm}{'Non-Critical'}, $count{esm}{'Ok'};
3364     report('other', $msg, $err);
3365
3366     return;
3367 }
3368
3369 #
3370 # Handy function for checking all storage components
3371 #
3372 sub check_storage {
3373     check_controllers();
3374     check_physical_disks();
3375     check_virtual_disks();
3376     check_cache_battery();
3377     check_connectors();
3378     check_enclosures();
3379     check_enclosure_fans();
3380     check_enclosure_pwr();
3381     check_enclosure_temp();
3382     check_enclosure_emms();
3383     return;
3384 }
3385
3386
3387
3388 #---------------------------------------------------------------------
3389 # Info functions
3390 #---------------------------------------------------------------------
3391
3392 #
3393 # Fetch output from 'omreport chassis info', put in sysinfo hash
3394 #
3395 sub get_omreport_chassis_info {
3396     if (open my $INFO, '-|', "$omreport $omopt_chassis info -fmt ssv") {
3397         my @lines = <$INFO>;
3398         close $INFO;
3399         foreach (@lines) {
3400             next if !m/\A (Chassis\sModel|Chassis\sService\sTag|Model|Service\sTag)/xms;
3401             my ($key, $val) = split /;/xms;
3402             $key =~ s{\s+\z}{}xms; # remove trailing whitespace
3403             $val =~ s{\s+\z}{}xms; # remove trailing whitespace
3404             if ($key eq 'Chassis Model' or $key eq 'Model') {
3405                 $sysinfo{model}  = $val;
3406             }
3407             if ($key eq 'Chassis Service Tag' or $key eq 'Service Tag') {
3408                 $sysinfo{serial} = $val;
3409             }
3410         }
3411     }
3412     return;
3413 }
3414
3415 #
3416 # Fetch output from 'omreport chassis bios', put in sysinfo hash
3417 #
3418 sub get_omreport_chassis_bios {
3419     if (open my $BIOS, '-|', "$omreport $omopt_chassis bios -fmt ssv") {
3420         my @lines = <$BIOS>;
3421         close $BIOS;
3422         foreach (@lines) {
3423             next if !m/;/xms;
3424             my ($key, $val) = split /;/xms;
3425             $key =~ s{\s+\z}{}xms; # remove trailing whitespace
3426             $val =~ s{\s+\z}{}xms; # remove trailing whitespace
3427             $sysinfo{bios}     = $val if $key eq 'Version';
3428             $sysinfo{biosdate} = $val if $key eq 'Release Date';
3429         }
3430     }
3431     return;
3432 }
3433
3434 #
3435 # Fetch output from 'omreport system operatingsystem', put in sysinfo hash
3436 #
3437 sub get_omreport_system_operatingsystem {
3438     if (open my $VER, '-|', "$omreport $omopt_system operatingsystem -fmt ssv") {
3439         my @lines = <$VER>;
3440         close $VER;
3441         foreach (@lines) {
3442             next if !m/;/xms;
3443             my ($key, $val) = split /;/xms;
3444             $key =~ s{\s+\z}{}xms; # remove trailing whitespace
3445             $val =~ s{\s+\z}{}xms; # remove trailing whitespace
3446             if ($key eq 'Operating System') {
3447                 $sysinfo{osname} = $val;
3448             }
3449             elsif ($key eq 'Operating System Version') {
3450                 $sysinfo{osver}  = $val;
3451             }
3452         }
3453     }
3454     return;
3455 }
3456
3457 #
3458 # Fetch output from 'omreport about', put in sysinfo hash
3459 #
3460 sub get_omreport_about {
3461     if (open my $OM, '-|', "$omreport about -fmt ssv") {
3462         my @lines = <$OM>;
3463         close $OM;
3464         foreach (@lines) {
3465             if (m/\A Version;(.+) \z/xms) {
3466                 $sysinfo{om} = $1;
3467                 chomp $sysinfo{om};
3468             }
3469         }
3470     }
3471     return;
3472 }
3473
3474 #
3475 # Fetch chassis info via SNMP, put in sysinfo hash
3476 #
3477 sub get_snmp_chassis_info {
3478     my %chassis_oid
3479       = (
3480          '1.3.6.1.4.1.674.10892.1.300.10.1.9.1'  => 'chassisModelName',
3481          '1.3.6.1.4.1.674.10892.1.300.10.1.11.1' => 'chassisServiceTagName',
3482         );
3483
3484     my $chassisInformationTable = '1.3.6.1.4.1.674.10892.1.300.10.1';
3485     my $result = $snmp_session->get_table(-baseoid => $chassisInformationTable);
3486
3487     if (defined $result) {
3488         foreach my $oid (keys %{ $result }) {
3489             if (exists $chassis_oid{$oid} and $chassis_oid{$oid} eq 'chassisModelName') {
3490                 $sysinfo{model} = $result->{$oid};
3491                 $sysinfo{model} =~ s{\s+\z}{}xms; # remove trailing whitespace
3492             }
3493             elsif (exists $chassis_oid{$oid} and $chassis_oid{$oid} eq 'chassisServiceTagName') {
3494                 $sysinfo{serial} = $result->{$oid};
3495             }
3496         }
3497     }
3498     else {
3499         my $msg = sprintf 'SNMP ERROR getting chassis info: %s',
3500           $snmp_session->error;
3501         report('other', $msg, $E_UNKNOWN);
3502     }
3503     return;
3504 }
3505
3506 #
3507 # Fetch BIOS info via SNMP, put in sysinfo hash
3508 #
3509 sub get_snmp_chassis_bios {
3510     my %bios_oid
3511       = (
3512          '1.3.6.1.4.1.674.10892.1.300.50.1.7.1.1' => 'systemBIOSReleaseDateName',
3513          '1.3.6.1.4.1.674.10892.1.300.50.1.8.1.1' => 'systemBIOSVersionName',
3514         );
3515
3516     my $systemBIOSTable = '1.3.6.1.4.1.674.10892.1.300.50.1';
3517     my $result = $snmp_session->get_table(-baseoid => $systemBIOSTable);
3518
3519     if (defined $result) {
3520         foreach my $oid (keys %{ $result }) {
3521             if (exists $bios_oid{$oid} and $bios_oid{$oid} eq 'systemBIOSReleaseDateName') {
3522                 $sysinfo{biosdate} = $result->{$oid};
3523                 $sysinfo{biosdate} =~ s{\A (\d{4})(\d{2})(\d{2}).*}{$2/$3/$1}xms;
3524             }
3525             elsif (exists $bios_oid{$oid} and $bios_oid{$oid} eq 'systemBIOSVersionName') {
3526                 $sysinfo{bios} = $result->{$oid};
3527             }
3528         }
3529     }
3530     else {
3531         my $msg = sprintf 'SNMP ERROR getting BIOS info: %s',
3532           $snmp_session->error;
3533         report('other', $msg, $E_UNKNOWN);
3534     }
3535     return;
3536 }
3537
3538 #
3539 # Fetch OS info via SNMP, put in sysinfo hash
3540 #
3541 sub get_snmp_system_operatingsystem {
3542     my %os_oid
3543       = (
3544          '1.3.6.1.4.1.674.10892.1.400.10.1.6.1' => 'operatingSystemOperatingSystemName',
3545          '1.3.6.1.4.1.674.10892.1.400.10.1.7.1' => 'operatingSystemOperatingSystemVersionName',
3546         );
3547
3548     my $operatingSystemTable = '1.3.6.1.4.1.674.10892.1.400.10.1';
3549     my $result = $snmp_session->get_table(-baseoid => $operatingSystemTable);
3550
3551     if (defined $result) {
3552         foreach my $oid (keys %{ $result }) {
3553             if (exists $os_oid{$oid} and $os_oid{$oid} eq 'operatingSystemOperatingSystemName') {
3554                 $sysinfo{osname} = ($result->{$oid});
3555             }
3556             elsif (exists $os_oid{$oid} and $os_oid{$oid} eq 'operatingSystemOperatingSystemVersionName') {
3557                 $sysinfo{osver} = $result->{$oid};
3558             }
3559         }
3560     }
3561     else {
3562         my $msg = sprintf 'SNMP ERROR getting OS info: %s',
3563           $snmp_session->error;
3564         report('other', $msg, $E_UNKNOWN);
3565     }
3566     return;
3567 }
3568
3569 #
3570 # Fetch OMSA version via SNMP, put in sysinfo hash
3571 #
3572 sub get_snmp_about {
3573     my %omsa_oid
3574       = (
3575          '1.3.6.1.4.1.674.10892.1.100.10.0' => 'systemManagementSoftwareGlobalVersionName',
3576         );
3577     my $systemManagementSoftwareGroup = '1.3.6.1.4.1.674.10892.1.100';
3578     my $result = $snmp_session->get_table(-baseoid => $systemManagementSoftwareGroup);
3579     if (defined $result) {
3580         foreach my $oid (keys %{ $result }) {
3581             if (exists $omsa_oid{$oid} and $omsa_oid{$oid} eq 'systemManagementSoftwareGlobalVersionName') {
3582                 $sysinfo{om} = ($result->{$oid});
3583             }
3584         }
3585     }
3586     else {
3587         my $msg = sprintf 'SNMP ERROR getting OMSA info: %s',
3588           $snmp_session->error;
3589         report('other', $msg, $E_UNKNOWN);
3590     }
3591     return;
3592 }
3593
3594 #
3595 # Collects some information about the system
3596 #
3597 sub get_sysinfo
3598 {
3599     # Get system model and serial number
3600     $snmp ? get_snmp_chassis_info() : get_omreport_chassis_info();
3601
3602     # Get BIOS information. Only if needed
3603     if ( $opt{okinfo} >= 1
3604          or $opt{debug}
3605          or (defined $opt{postmsg} and $opt{postmsg} =~ m/[%][bd]/xms) ) {
3606         $snmp ? get_snmp_chassis_bios() : get_omreport_chassis_bios();
3607     }
3608
3609     # Return now if debug
3610     return if $opt{debug};
3611
3612     # Get OS information. Only if needed
3613     if (defined $opt{postmsg} and $opt{postmsg} =~ m/[%][or]/xms) {
3614         $snmp ? get_snmp_system_operatingsystem() : get_omreport_system_operatingsystem();
3615     }
3616
3617     # Get OMSA information. Only if needed
3618     if ($opt{okinfo} >= 3) {
3619         $snmp ? get_snmp_about() : get_omreport_about();
3620     }
3621
3622     return;
3623 }
3624
3625
3626 # Helper function for running omreport when the results are strictly
3627 # name=value pairs.
3628 sub run_omreport_info {
3629     my $command = shift;
3630     my %output  = ();
3631     my @keys    = ();
3632
3633     # Run omreport and fetch output
3634     my $rawtext = slurp_command("$omreport $command -fmt ssv 2>&1");
3635
3636     # Parse output, store in array
3637     for ((split /\n/xms, $rawtext)) {
3638         if (m/\A Error/xms) {
3639             my $msg = "Problem running 'omreport $command': $_";
3640             report('other', $msg, $E_UNKNOWN);
3641         }
3642         next if !m/;/xms;  # ignore lines with less than two fields
3643         my @vals = split m/;/xms;
3644         $output{$vals[0]} = $vals[1];
3645     }
3646
3647     # Finally, return the collected information
3648     return \%output;
3649 }
3650
3651 # Get various firmware information (BMC, RAC)
3652 sub get_firmware_info {
3653     my @snmp_output = ();
3654     my %nrpe_output = ();
3655
3656     if ($snmp) {
3657         my %fw_oid
3658           = (
3659              '1.3.6.1.4.1.674.10892.1.300.60.1.7.1'  => 'firmwareType',
3660              '1.3.6.1.4.1.674.10892.1.300.60.1.8.1'  => 'firmwareTypeName',
3661              '1.3.6.1.4.1.674.10892.1.300.60.1.11.1' => 'firmwareVersionName',
3662             );
3663
3664         my $firmwareTable = '1.3.6.1.4.1.674.10892.1.300.60.1';
3665         my $result = $snmp_session->get_table(-baseoid => $firmwareTable);
3666
3667         # Some don't have this OID, this is ok
3668         if (!defined $result) {
3669             return;
3670         }
3671
3672         @snmp_output = @{ get_snmp_output($result, \%fw_oid) };
3673     }
3674     else {
3675         %nrpe_output = %{ run_omreport_info("$omopt_chassis info") };
3676     }
3677
3678     my %fw_type  # Firmware types
3679       = (
3680          1  => 'other',                              # other than following values
3681          2  => 'unknown',                            # unknown
3682          3  => 'systemBIOS',                         # System BIOS
3683          4  => 'embeddedSystemManagementController', # Embedded System Management Controller
3684          5  => 'powerSupplyParallelingBoard',        # Power Supply Paralleling Board
3685          6  => 'systemBackPlane',                    # System (Primary) Backplane
3686          7  => 'powerVault2XXSKernel',               # PowerVault 2XXS Kernel
3687          8  => 'powerVault2XXSApplication',          # PowerVault 2XXS Application
3688          9  => 'frontPanel',                         # Front Panel Controller
3689          10 => 'baseboardManagementController',      # Baseboard Management Controller
3690          11 => 'hotPlugPCI',                         # Hot Plug PCI Controller
3691          12 => 'sensorData',                         # Sensor Data Records
3692          13 => 'peripheralBay',                      # Peripheral Bay Backplane
3693          14 => 'secondaryBackPlane',                 # Secondary Backplane for ESM 2 systems
3694          15 => 'secondaryBackPlaneESM3And4',         # Secondary Backplane for ESM 3 and 4 systems
3695          16 => 'rac',                                # Remote Access Controller
3696          17 => 'imc'                                 # Integrated Management Controller
3697         );
3698
3699
3700     if ($snmp) {
3701         foreach my $out (@snmp_output) {
3702             if ($fw_type{$out->{firmwareType}} eq 'baseboardManagementController') {
3703                 $sysinfo{'bmc'} = 1;
3704                 $sysinfo{'bmc_fw'} = $out->{firmwareVersionName};
3705             }
3706             elsif ($fw_type{$out->{firmwareType}} =~ m{\A rac|imc \z}xms) {
3707                 my $name = $out->{firmwareTypeName}; $name =~ s/\s//gxms;
3708                 $sysinfo{'rac'} = 1;
3709                 $sysinfo{'rac_name'} = $name;
3710                 $sysinfo{'rac_fw'} = $out->{firmwareVersionName};
3711             }
3712         }
3713     }
3714     else {
3715         foreach my $key (keys %nrpe_output) {
3716             next if !defined $nrpe_output{$key};
3717             if ($key eq 'BMC Version' or $key eq 'Baseboard Management Controller Version') {
3718                 $sysinfo{'bmc'} = 1;
3719                 $sysinfo{'bmc_fw'} = $nrpe_output{$key};
3720             }
3721             elsif ($key =~ m{\A (i?DRAC)\s*(\d?)\s+Version}xms) {
3722                 my $name = "$1$2";
3723                 $sysinfo{'rac'} = 1;
3724                 $sysinfo{'rac_fw'} = $nrpe_output{$key};
3725                 $sysinfo{'rac_name'} = $name;
3726             }
3727         }
3728     }
3729
3730     return;
3731 }
3732
3733
3734
3735 #=====================================================================
3736 # Main program
3737 #=====================================================================
3738
3739 # Here we do the actual checking of components
3740 # Check global status if applicable
3741 if ($global) {
3742     $globalstatus = check_global();
3743 }
3744
3745 # Do multiple selected checks
3746 if ($check{storage})     { check_storage();       }
3747 if ($check{memory})      { check_memory();        }
3748 if ($check{fans})        { check_fans();          }
3749 if ($check{power})       { check_powersupplies(); }
3750 if ($check{temp})        { check_temperatures();  }
3751 if ($check{cpu})         { check_processors();    }
3752 if ($check{voltage})     { check_volts();         }
3753 if ($check{batteries})   { check_batteries();     }
3754 if ($check{amperage})    { check_pwrmonitoring(); }
3755 if ($check{intrusion})   { check_intrusion();     }
3756 if ($check{alertlog})    { check_alertlog();      }
3757 if ($check{esmlog})      { check_esmlog();        }
3758 if ($check{esmhealth})   { check_esmlog_health(); }
3759
3760
3761 #---------------------------------------------------------------------
3762 # Finish up
3763 #---------------------------------------------------------------------
3764
3765 # Counter variable
3766 %nagios_alert_count
3767   = (
3768      'OK'       => 0,
3769      'WARNING'  => 0,
3770      'CRITICAL' => 0,
3771      'UNKNOWN'  => 0,
3772     );
3773
3774 # Get system information
3775 get_sysinfo();
3776
3777 # Get firmware info if requested via option
3778 if ($opt{okinfo} >= 1) {
3779     get_firmware_info();
3780 }
3781
3782 # Close SNMP session
3783 if ($snmp) {
3784     $snmp_session->close;
3785 }
3786
3787 # Print messages
3788 if ($opt{debug}) {
3789     print "   System:      $sysinfo{model}\n";
3790     print "   ServiceTag:  $sysinfo{serial}\n";
3791     print "   BIOS/date:   $sysinfo{bios} $sysinfo{biosdate}\n";
3792     if ($#report_storage >= 0) {
3793         print "-----------------------------------------------------------------------------\n";
3794         print "   Storage Components                                                        \n";
3795         print "=============================================================================\n";
3796         print "  STATE  |    ID    |  MESSAGE TEXT                                          \n";
3797         print "---------+----------+--------------------------------------------------------\n";
3798         foreach (@report_storage) {
3799             my ($msg, $level, $nexus) = @{$_};
3800             print q{ } x (8 - length $reverse_exitcode{$level}) . "$reverse_exitcode{$level} | "
3801               . q{ } x (8 - length $nexus) . "$nexus | $msg\n";
3802             $nagios_alert_count{$reverse_exitcode{$level}}++;
3803         }
3804     }
3805     if ($#report_chassis >= 0) {
3806         print "-----------------------------------------------------------------------------\n";
3807         print "   Chassis Components                                                        \n";
3808         print "=============================================================================\n";
3809         print "  STATE  |  ID  |  MESSAGE TEXT                                          \n";
3810         print "---------+------+------------------------------------------------------------\n";
3811         foreach (@report_chassis) {
3812             my ($msg, $level, $nexus) = @{$_};
3813             print q{ } x (8 - length $reverse_exitcode{$level}) . "$reverse_exitcode{$level} | "
3814               . q{ } x (4 - length $nexus) . "$nexus | $msg\n";
3815             $nagios_alert_count{$reverse_exitcode{$level}}++;
3816         }
3817     }
3818     if ($#report_other >= 0) {
3819         print "-----------------------------------------------------------------------------\n";
3820         print "   Other messages                                                            \n";
3821         print "=============================================================================\n";
3822         print "  STATE  |  MESSAGE TEXT                                                     \n";
3823         print "---------+-------------------------------------------------------------------\n";
3824         foreach (@report_other) {
3825             my ($msg, $level, $nexus) = @{$_};
3826             print q{ } x (8 - length $reverse_exitcode{$level}) . "$reverse_exitcode{$level} | $msg\n";
3827             $nagios_alert_count{$reverse_exitcode{$level}}++;
3828         }
3829     }
3830 }
3831 else {
3832     my $c = 0;  # counter to determine linebreaks
3833
3834     # Run through each message, sorted by severity level
3835   ALERT:
3836     foreach (sort {$a->[1] < $b->[1]} (@report_storage, @report_chassis, @report_other)) {
3837         my ($msg, $level, $nexus) = @{ $_ };
3838         next ALERT if $level == $E_OK;
3839
3840         if (defined $opt{only}) {
3841             # If user wants only critical alerts
3842             next ALERT if ($opt{only} eq 'critical' and $level == $E_WARNING);
3843
3844             # If user wants only warning alerts
3845             next ALERT if ($opt{only} eq 'warning' and $level == $E_CRITICAL);
3846         }
3847
3848         # Prefix with service tag if specified with option '-i|--info'
3849         if ($opt{info}) {
3850             if (defined $opt{htmlinfo}) {
3851                 $msg = '[<a href="' . warranty_url($sysinfo{serial})
3852                   . "\">$sysinfo{serial}</a>] " . $msg;
3853             }
3854             else {
3855                 $msg = "[$sysinfo{serial}] " . $msg;
3856             }
3857         }
3858
3859         # Prefix with nagios level if specified with option '--state'
3860         $msg = $reverse_exitcode{$level} . ": $msg" if $opt{state};
3861
3862         # Prefix with one-letter nagios level if specified with option '--short-state'
3863         $msg = (substr $reverse_exitcode{$level}, 0, 1) . ": $msg" if $opt{shortstate};
3864
3865         ($c++ == 0) ? print $msg : print $linebreak, $msg;
3866
3867         $nagios_alert_count{$reverse_exitcode{$level}}++;
3868     }
3869 }
3870
3871 # Determine our exit code
3872 $exit_code = $E_OK;
3873 $exit_code = $E_UNKNOWN  if $nagios_alert_count{'UNKNOWN'} > 0;
3874 $exit_code = $E_WARNING  if $nagios_alert_count{'WARNING'} > 0;
3875 $exit_code = $E_CRITICAL if $nagios_alert_count{'CRITICAL'} > 0;
3876
3877 # Global status via SNMP.. extra safety check
3878 if ($globalstatus != $E_OK && $exit_code == $E_OK && !defined $opt{only}) {
3879     print "OOPS! Something is wrong with this server, but I don't know what. ";
3880     print "The global system health status is $reverse_exitcode{$globalstatus}, ";
3881     print "but every component check is OK. This may be a bug in the Nagios plugin, ";
3882     print "please file a bug report.\n";
3883     exit $E_UNKNOWN;
3884 }
3885
3886 # Print OK message
3887 if ($exit_code == $E_OK && defined $opt{only} && $opt{only} !~ m{\A critical|warning|chassis \z}xms && !$opt{debug}) {
3888     my %okmsg
3889       = ( 'storage'     => "STORAGE OK - $count{pdisk} physical drives, $count{vdisk} logical drives",
3890           'fans'        => $count{fan} == 0 && $blade ? 'OK - blade system with no fan probes' : "FANS OK - $count{fan} fan probes checked",
3891           'temp'        => "TEMPERATURES OK - $count{temp} temperature probes checked",
3892           'memory'      => "MEMORY OK - $count{dimm} memory modules checked",
3893           'power'       => $count{power} == 0 ? 'OK - no instrumented power supplies found' : "POWER OK - $count{power} power supplies checked",
3894           'cpu'         => "PROCESSORS OK - $count{cpu} processors checked",
3895           'voltage'     => "VOLTAGE OK - $count{volt} voltage probes checked",
3896           'batteries'   => $count{bat} == 0 ? 'OK - no batteries found' : "BATTERIES OK - $count{bat} batteries checked",
3897           'amperage'    => $count{amp} == 0 ? 'OK - no power monitoring probes found' : "AMPERAGE OK - $count{amp} amperage (power monitoring) probes checked",
3898           'intrusion'   => $count{intr} == 0 ? 'OK - no intrusion detection probes found' : "INTRUSION OK - $count{intr} intrusion detection probes checked",
3899           'alertlog'    => $snmp ? 'OK - not supported via snmp' : "OK - Alert Log content: $count{alert}{Ok} ok, $count{alert}{'Non-Critical'} warning and $count{alert}{Critical} critical",
3900           'esmlog'      => "OK - ESM Log content: $count{esm}{Ok} ok, $count{esm}{'Non-Critical'} warning and $count{esm}{Critical} critical",
3901           'esmhealth'   => "ESM LOG OK - less than 80% used",
3902         );
3903
3904     print $okmsg{$opt{only}};
3905 }
3906 elsif ($exit_code == $E_OK && !$opt{debug}) {
3907     if (defined $opt{htmlinfo}) {
3908         printf q{OK - System: '<a href="%s">%s</a>', SN: '<a href="%s">%s</a>', hardware working fine},
3909           documentation_url($sysinfo{model}), $sysinfo{model},
3910             warranty_url($sysinfo{serial}), $sysinfo{serial};
3911     }
3912     else {
3913         printf q{OK - System: '%s', SN: '%s', hardware working fine},
3914           $sysinfo{model}, $sysinfo{serial};
3915     }
3916
3917     if ($check{storage}) {
3918         printf ', %d logical drives, %d physical drives',
3919           $count{vdisk}, $count{pdisk};
3920     }
3921     else {
3922         print ', not checking storage';
3923     }
3924
3925     if ($opt{okinfo} >= 1) {
3926         print $linebreak;
3927         printf q{----- BIOS='%s %s'}, $sysinfo{bios}, $sysinfo{biosdate};
3928
3929         if ($sysinfo{rac}) {
3930             printf q{, %s='%s'}, $sysinfo{rac_name}, $sysinfo{rac_fw};
3931         }
3932         if ($sysinfo{bmc}) {
3933             printf q{, BMC='%s'}, $sysinfo{bmc_fw};
3934         }
3935     }
3936
3937     if ($opt{okinfo} >= 2) {
3938         if ($check{storage}) {
3939             my @storageprint = ();
3940             foreach my $id (sort keys %{ $sysinfo{controller} }) {
3941                 chomp $sysinfo{controller}{$id}{driver};
3942                 push @storageprint, sprintf q{----- CTRL %s (%s): FW='%s', DR='%s'},
3943                   $sysinfo{controller}{$id}{id}, $sysinfo{controller}{$id}{name},
3944                     $sysinfo{controller}{$id}{firmware}, $sysinfo{controller}{$id}{driver};
3945             }
3946             foreach my $id (sort keys %{ $sysinfo{enclosure} }) {
3947                 push @storageprint, sprintf q{----- ENCL %s (%s): FW='%s'},
3948                   $sysinfo{enclosure}{$id}->{id}, $sysinfo{enclosure}{$id}->{name},
3949                     $sysinfo{enclosure}{$id}->{firmware};
3950             }
3951
3952             # print stuff
3953             foreach my $line (@storageprint) {
3954                 print $linebreak, $line;
3955             }
3956         }
3957     }
3958
3959     if ($opt{okinfo} >= 3) {
3960         print "$linebreak----- OpenManage Server Administrator (OMSA) version: '$sysinfo{om}'";
3961     }
3962
3963 }
3964 else {
3965     if ($opt{extinfo}) {
3966         print $linebreak;
3967         if (defined $opt{htmlinfo}) {
3968             printf '------ SYSTEM: <a href="%s">%s</a>, SN: <a href="%s">%s</a>',
3969               documentation_url($sysinfo{model}), $sysinfo{model},
3970                 warranty_url($sysinfo{serial}), $sysinfo{serial};
3971         }
3972         else {
3973             printf '------ SYSTEM: %s, SN: %s',
3974               $sysinfo{model}, $sysinfo{serial};
3975         }
3976     }
3977     if (defined $opt{postmsg}) {
3978         my $post = undef;
3979         if (-f $opt{postmsg}) {
3980             open my $POST, '<', $opt{postmsg}
3981               or ( print $linebreak
3982                    and print "ERROR: Couldn't open post message file $opt{postmsg}: $!\n"
3983                    and exit $E_UNKNOWN );
3984             $post = <$POST>;
3985             close $POST;
3986             chomp $post;
3987         }
3988         else {
3989             $post = $opt{postmsg};
3990         }
3991         if (defined $post) {
3992             print $linebreak;
3993             $post =~ s{[%]s}{$sysinfo{serial}}gxms;
3994             $post =~ s{[%]m}{$sysinfo{model}}gxms;
3995             $post =~ s{[%]b}{$sysinfo{bios}}gxms;
3996             $post =~ s{[%]d}{$sysinfo{biosdate}}gxms;
3997             $post =~ s{[%]o}{$sysinfo{osname}}gxms;
3998             $post =~ s{[%]r}{$sysinfo{osver}}gxms;
3999             $post =~ s{[%]p}{$count{pdisk}}gxms;
4000             $post =~ s{[%]l}{$count{vdisk}}gxms;
4001             $post =~ s{[%]n}{$linebreak}gxms;
4002             $post =~ s{[%]{2}}{%}gxms;
4003             print $post;
4004         }
4005     }
4006 }
4007
4008 # Print performance data
4009 if (defined $opt{perfdata} && !$opt{debug} && %perfdata) {
4010     my $lb = $opt{perfdata} eq 'multiline' ? "\n" : q{ };  # line break for perfdata
4011     print q{|};
4012
4013     sub perfdata {
4014         my %order
4015           = (
4016              fan       => 0,
4017              pwr       => 1,
4018              temp      => 2,
4019              enclosure => 3,
4020             );
4021         return ($order{(split /_/, $a, 2)[0]} cmp $order{(split /_/, $b, 2)[0]}) || $a cmp $b;
4022     }
4023
4024     print join $lb, map { "'$_'=$perfdata{$_}" } sort perfdata keys %perfdata;
4025 }
4026
4027 # Print a linebreak at the end
4028 print "\n" if !$opt{debug};
4029
4030 # Exit with proper exit code
4031 exit $exit_code;