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