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