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