]> git.uio.no Git - check_openmanage.git/blob - check_openmanage
* version 3.5.7-beta19
[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 %reverse_exitcode %status2nagios
39              %snmp_status %snmp_probestatus %probestatus2nagios %sysinfo
40              %blacklist %nagios_alert_count %count
41              @perl_warnings @controllers @enclosures @perfdata
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-beta19';
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 $label = "enclosure_${encl_id}_${name}";
2329             my $mini = $label;
2330             $mini =~ s{enclosure_(.+?)_temp_(.+?)}{e$1t$2}xms;
2331             push @perfdata, {
2332                              label => $label,
2333                              mini  => $mini,
2334                              value => $reading,
2335                              unit  => '',
2336                              warn  => $max_warn,
2337                              crit  => $max_crit,
2338                             };
2339         }
2340     }
2341     return;
2342 }
2343
2344
2345 #-----------------------------------------
2346 # STORAGE: Check enclosure management modules (EMM)
2347 #-----------------------------------------
2348 sub check_enclosure_emms {
2349     return if $#controllers == -1;
2350     return if blacklisted('encl_emm', 'all');
2351
2352     my $id        = undef;
2353     my $nexus     = undef;
2354     my $name      = undef;
2355     my $state     = undef;
2356     my $status    = undef;
2357     my $encl_id   = undef;
2358     my $encl_name = undef;
2359     my @output    = ();
2360
2361     if ($snmp) {
2362         my %emms_oid
2363           = (
2364              '1.3.6.1.4.1.674.10893.1.20.130.13.1.1'  => 'enclosureManagementModuleNumber',
2365              '1.3.6.1.4.1.674.10893.1.20.130.13.1.2'  => 'enclosureManagementModuleName',
2366              '1.3.6.1.4.1.674.10893.1.20.130.13.1.4'  => 'enclosureManagementModuleState',
2367              '1.3.6.1.4.1.674.10893.1.20.130.13.1.11' => 'enclosureManagementModuleComponentStatus',
2368              '1.3.6.1.4.1.674.10893.1.20.130.13.1.12' => 'enclosureManagementModuleNexusID',
2369              '1.3.6.1.4.1.674.10893.1.20.130.14.1.4'  => 'enclosureManagementModuleConnectionEnclosureName',
2370              '1.3.6.1.4.1.674.10893.1.20.130.14.1.5'  => 'enclosureManagementModuleConnectionEnclosureNumber',
2371             );
2372         my $result = undef;
2373         if ($opt{use_get_table}) {
2374             my $enclosureManagementModuleTable = '1.3.6.1.4.1.674.10893.1.20.130.13';
2375             my $enclosureManagementModuleConnectionTable = '1.3.6.1.4.1.674.10893.1.20.130.14';
2376
2377             $result = $snmp_session->get_table(-baseoid => $enclosureManagementModuleTable);
2378             my $ext = $snmp_session->get_table(-baseoid => $enclosureManagementModuleConnectionTable);
2379
2380             if (defined $result) {
2381                 defined $ext && map { $$result{$_} = $$ext{$_} } keys %{ $ext };
2382             }
2383         }
2384         else {
2385             $result = $snmp_session->get_entries(-columns => [keys %emms_oid]);
2386         }
2387
2388         # No enclosure EMMs is OK
2389         return if !defined $result;
2390
2391         @output = @{ get_snmp_output($result, \%emms_oid) };
2392     }
2393     else {
2394         foreach my $enc (@enclosures) {
2395             push @output, @{ run_omreport("storage enclosure controller=$enc->{ctrl} enclosure=$enc->{id} info=emms") };
2396             map_item('ctrl', $enc->{ctrl}, \@output);
2397             map_item('encl_id', $enc->{id}, \@output);
2398             map_item('encl_name', $enc->{name}, \@output);
2399         }
2400     }
2401
2402     my %emms_state
2403       = (
2404          0  => 'Unknown',
2405          1  => 'Ready',
2406          2  => 'Failed',
2407          3  => 'Online',
2408          4  => 'Offline',
2409          5  => 'Not Installed',
2410          6  => 'Degraded',
2411          21 => 'Missing',
2412         );
2413
2414     # Check temperature probes on each of the enclosures
2415   EMM:
2416     foreach my $out (@output) {
2417         if ($snmp) {
2418             $id        = $out->{enclosureManagementModuleNumber} - 1;
2419             $name      = $out->{enclosureManagementModuleName};
2420             $state     = get_hashval($out->{enclosureManagementModuleState}, \%emms_state);
2421             $status    = $snmp_status{$out->{enclosureManagementModuleComponentStatus}};
2422             $encl_id   = $out->{enclosureManagementModuleConnectionEnclosureNumber} - 1;
2423             $encl_name = $out->{enclosureManagementModuleConnectionEnclosureName};
2424             $nexus     = convert_nexus($out->{enclosureManagementModuleNexusID});
2425         }
2426         else {
2427             $id        = $out->{'ID'};
2428             $name      = $out->{'Name'};
2429             $state     = $out->{'State'};
2430             $status    = $out->{'Status'};
2431             $encl_id   = join q{:}, $out->{ctrl}, $out->{'encl_id'};
2432             $encl_name = $out->{encl_name};
2433             $nexus     = join q{:}, $out->{ctrl}, $out->{'encl_id'}, $id;
2434         }
2435
2436         next EMM if blacklisted('encl_emm', $nexus);
2437
2438         # Default
2439         if ($status ne 'Ok') {
2440             my $msg = sprintf '%s in enclosure %s [%s] needs attention: %s',
2441               $name, $encl_id, $encl_name, $state;
2442             report('storage', $msg, $status2nagios{$status}, $nexus);
2443         }
2444         # Ok
2445         else {
2446             my $msg = sprintf '%s in enclosure %s [%s] is %s',
2447               $name, $encl_id, $encl_name, $state;
2448             report('storage', $msg, $E_OK, $nexus);
2449         }
2450     }
2451     return;
2452 }
2453
2454
2455 #-----------------------------------------
2456 # CHASSIS: Check memory modules
2457 #-----------------------------------------
2458 sub check_memory {
2459     return if blacklisted('dimm', 'all');
2460
2461     my $index    = undef;
2462     my $status   = undef;
2463     my $location = undef;
2464     my $size     = undef;
2465     my $modes    = undef;
2466     my @failures = ();
2467     my @output   = ();
2468
2469     if ($snmp) {
2470         my %dimm_oid
2471           = (
2472              '1.3.6.1.4.1.674.10892.1.1100.50.1.2.1'  => 'memoryDeviceIndex',
2473              '1.3.6.1.4.1.674.10892.1.1100.50.1.5.1'  => 'memoryDeviceStatus',
2474              '1.3.6.1.4.1.674.10892.1.1100.50.1.8.1'  => 'memoryDeviceLocationName',
2475              '1.3.6.1.4.1.674.10892.1.1100.50.1.14.1' => 'memoryDeviceSize',
2476              '1.3.6.1.4.1.674.10892.1.1100.50.1.20.1' => 'memoryDeviceFailureModes',
2477             );
2478         my $result = undef;
2479         if ($opt{use_get_table}) {
2480             my $memoryDeviceTable = '1.3.6.1.4.1.674.10892.1.1100.50.1';
2481             $result = $snmp_session->get_table(-baseoid => $memoryDeviceTable);
2482         }
2483         else {
2484             $result = $snmp_session->get_entries(-columns => [keys %dimm_oid]);
2485         }
2486
2487         if (!defined $result) {
2488             printf "SNMP ERROR [memory]: %s.\n", $snmp_session->error;
2489             $snmp_session->close;
2490             exit $E_UNKNOWN;
2491         }
2492
2493         @output = @{ get_snmp_output($result, \%dimm_oid) };
2494     }
2495     else {
2496         @output = @{ run_omreport("$omopt_chassis memory") };
2497     }
2498
2499     # Note: These values are bit masks, so combination values are
2500     # possible. If value is 0 (zero), memory device has no faults.
2501     my %failure_mode
2502       = (
2503          1  => 'ECC single bit correction warning rate exceeded',
2504          2  => 'ECC single bit correction failure rate exceeded',
2505          4  => 'ECC multibit fault encountered',
2506          8  => 'ECC single bit correction logging disabled',
2507          16 => 'device disabled because of spare activation',
2508         );
2509
2510   DIMM:
2511     foreach my $out (@output) {
2512         @failures = ();  # Initialize
2513         if ($snmp) {
2514             $index    = $out->{memoryDeviceIndex};
2515             $status   = $snmp_status{$out->{memoryDeviceStatus}};
2516             $location = $out->{memoryDeviceLocationName};
2517             $size     = sprintf '%d MB', $out->{memoryDeviceSize}/1024;
2518             $modes    = $out->{memoryDeviceFailureModes};
2519             if ($modes > 0) {
2520                 foreach my $mask (sort keys %failure_mode) {
2521                     if (($modes & $mask) != 0) { push @failures, $failure_mode{$mask}; }
2522                 }
2523             }
2524         }
2525         else {
2526             $index    = $out->{'Type'} eq '[Not Occupied]' ? undef : $out->{'Index'};
2527             $status   = $out->{'Status'};
2528             $location = $out->{'Connector Name'};
2529             $size     = $out->{'Size'};
2530             if (defined $size) {
2531                 $size =~ s{\s\s}{ }gxms;
2532             }
2533             # Run 'omreport chassis memory index=X' to get the failures
2534             if ($status ne 'Ok' && defined $index) {
2535                 foreach (@{ run_command("$omreport $omopt_chassis memory index=$index -fmt ssv") }) {
2536                     if (m/\A Failures; (.+?) \z/xms) {
2537                         chop(my $fail = $1);
2538                         push @failures, split m{\.}xms, $fail;
2539                     }
2540                 }
2541             }
2542         }
2543         $location =~ s{\A \s*(.*?)\s* \z}{$1}xms;
2544
2545         next DIMM if blacklisted('dimm', $index);
2546
2547         # Ignore empty memory slots
2548         next DIMM if !defined $index;
2549         $count{dimm}++;
2550
2551         if ($status ne 'Ok') {
2552             my $msg = undef;
2553             if (scalar @failures == 0) {
2554                 $msg = sprintf 'Memory module %d [%s, %s] needs attention (%s)',
2555                   $index, $location, $size, $status;
2556             }
2557             else {
2558                 $msg = sprintf 'Memory module %d [%s, %s] needs attention: %s',
2559                   $index, $location, $size, (join q{, }, @failures);
2560             }
2561
2562             report('chassis', $msg, $status2nagios{$status}, $index);
2563         }
2564         # Ok
2565         else {
2566             my $msg = sprintf 'Memory module %d [%s, %s] is %s',
2567               $index, $location, $size, $status;
2568             report('chassis', $msg, $E_OK, $index);
2569         }
2570     }
2571     return;
2572 }
2573
2574
2575 #-----------------------------------------
2576 # CHASSIS: Check fans
2577 #-----------------------------------------
2578 sub check_fans {
2579     return if blacklisted('fan', 'all');
2580
2581     my $index    = undef;
2582     my $status   = undef;
2583     my $reading  = undef;
2584     my $location = undef;
2585     my $max_crit = undef;
2586     my $max_warn = undef;
2587     my @output   = ();
2588
2589     if ($snmp) {
2590         my %cool_oid
2591           = (
2592              '1.3.6.1.4.1.674.10892.1.700.12.1.2.1'  => 'coolingDeviceIndex',
2593              '1.3.6.1.4.1.674.10892.1.700.12.1.5.1'  => 'coolingDeviceStatus',
2594              '1.3.6.1.4.1.674.10892.1.700.12.1.6.1'  => 'coolingDeviceReading',
2595              '1.3.6.1.4.1.674.10892.1.700.12.1.8.1'  => 'coolingDeviceLocationName',
2596              '1.3.6.1.4.1.674.10892.1.700.12.1.10.1' => 'coolingDeviceUpperCriticalThreshold',
2597              '1.3.6.1.4.1.674.10892.1.700.12.1.11.1' => 'coolingDeviceUpperNonCriticalThreshold',
2598             );
2599         my $result = undef;
2600         if ($opt{use_get_table}) {
2601             my $coolingDeviceTable = '1.3.6.1.4.1.674.10892.1.700.12.1';
2602             $result = $snmp_session->get_table(-baseoid => $coolingDeviceTable);
2603         }
2604         else {
2605             $result = $snmp_session->get_entries(-columns => [keys %cool_oid]);
2606         }
2607
2608         if ($blade && !defined $result) {
2609             return 0;
2610         }
2611         elsif (!$blade && !defined $result) {
2612             printf "SNMP ERROR [cooling]: %s.\n", $snmp_session->error;
2613             $snmp_session->close;
2614             exit $E_UNKNOWN;
2615         }
2616
2617         @output = @{ get_snmp_output($result, \%cool_oid) };
2618     }
2619     else {
2620         @output = @{ run_omreport("$omopt_chassis fans") };
2621     }
2622
2623   FAN:
2624     foreach my $out (@output) {
2625         if ($snmp) {
2626             $index    = $out->{coolingDeviceIndex};
2627             $status   = $snmp_probestatus{$out->{coolingDeviceStatus}};
2628             $reading  = $out->{coolingDeviceReading};
2629             $location = $out->{coolingDeviceLocationName};
2630             $max_crit = exists $out->{coolingDeviceUpperCriticalThreshold}
2631               ? $out->{coolingDeviceUpperCriticalThreshold} : 0;
2632             $max_warn = exists $out->{coolingDeviceUpperNonCriticalThreshold}
2633               ? $out->{coolingDeviceUpperNonCriticalThreshold} : 0;
2634         }
2635         else {
2636             $index    = $out->{'Index'};
2637             $status   = $out->{'Status'};
2638             $reading  = $out->{'Reading'};
2639             $location = $out->{'Probe Name'};
2640             $max_crit = $out->{'Maximum Failure Threshold'} ne '[N/A]'
2641               ? $out->{'Maximum Failure Threshold'} : 0;
2642             $max_warn = $out->{'Maximum Warning Threshold'} ne '[N/A]'
2643               ? $out->{'Maximum Warning Threshold'} : 0;
2644             $reading  =~ s{\A (\d+).* \z}{$1}xms;
2645             $max_warn =~ s{\A (\d+).* \z}{$1}xms;
2646             $max_crit =~ s{\A (\d+).* \z}{$1}xms;
2647         }
2648
2649         next FAN if blacklisted('fan', $index);
2650         $count{fan}++;
2651
2652         if ($status ne 'Ok') {
2653             my $msg = sprintf 'Chassis fan %d [%s] needs attention: %s',
2654               $index, $location, $status;
2655             my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2656             report('chassis', $msg, $err, $index);
2657         }
2658         else {
2659             my $msg = sprintf 'Chassis fan %d [%s]: %s',
2660               $index, $location, $reading;
2661             report('chassis', $msg, $E_OK, $index);
2662         }
2663
2664         # Collect performance data
2665         if (defined $opt{perfdata}) {
2666             my $pname = lc $location;
2667             $pname =~ s{\s}{_}gxms;
2668             $pname =~ s{proc_}{cpu#}xms;
2669             my $pkey = join q{_}, 'fan', $index, $pname;
2670             push @perfdata, {
2671                              label => $pkey,
2672                              mini  => "f$index",
2673                              value => $reading,
2674                              unit  => '',
2675                              warn  => $max_warn,
2676                              crit  => $max_crit,
2677                             };
2678         }
2679     }
2680     return;
2681 }
2682
2683
2684 #-----------------------------------------
2685 # CHASSIS: Check power supplies
2686 #-----------------------------------------
2687 sub check_powersupplies {
2688     return if blacklisted('ps', 'all');
2689
2690     my $index    = undef;
2691     my $status   = undef;
2692     my $type     = undef;
2693     my $err_type = undef;
2694     my $state    = undef;
2695     my @states   = ();
2696     my @output   = ();
2697
2698     if ($snmp) {
2699         my %ps_oid
2700           = (
2701              '1.3.6.1.4.1.674.10892.1.600.12.1.2.1'  => 'powerSupplyIndex',
2702              '1.3.6.1.4.1.674.10892.1.600.12.1.5.1'  => 'powerSupplyStatus',
2703              '1.3.6.1.4.1.674.10892.1.600.12.1.7.1'  => 'powerSupplyType',
2704              '1.3.6.1.4.1.674.10892.1.600.12.1.11.1' => 'powerSupplySensorState',
2705              '1.3.6.1.4.1.674.10892.1.600.12.1.12.1' => 'powerSupplyConfigurationErrorType',
2706             );
2707         my $result = undef;
2708         if ($opt{use_get_table}) {
2709             my $powerDeviceTable = '1.3.6.1.4.1.674.10892.1.600.12.1';
2710             $result = $snmp_session->get_table(-baseoid => $powerDeviceTable);
2711         }
2712         else {
2713             $result = $snmp_session->get_entries(-columns => [keys %ps_oid]);
2714         }
2715
2716         # No instrumented PSU is OK (blades, low-end servers)
2717         return 0 if !defined $result;
2718
2719         @output = @{ get_snmp_output($result, \%ps_oid) };
2720     }
2721     else {
2722         @output = @{ run_omreport("$omopt_chassis pwrsupplies") };
2723     }
2724
2725     my %ps_type
2726       = (
2727          1  => 'Other',
2728          2  => 'Unknown',
2729          3  => 'Linear',
2730          4  => 'Switching',
2731          5  => 'Battery',
2732          6  => 'Uninterruptible Power Supply',
2733          7  => 'Converter',
2734          8  => 'Regulator',
2735          9  => 'AC',
2736          10 => 'DC',
2737          11 => 'VRM',
2738         );
2739
2740     my %ps_state
2741       = (
2742          1  => 'Presence detected',
2743          2  => 'Failure detected',
2744          4  => 'Predictive Failure',
2745          8  => 'AC lost',
2746          16 => 'AC lost or out-of-range',
2747          32 => 'AC out-of-range but present',
2748          64 => 'Configuration error',
2749         );
2750
2751     my %ps_config_error_type
2752       = (
2753          1 => 'Vendor mismatch',
2754          2 => 'Revision mismatch',
2755          3 => 'Processor missing',
2756         );
2757
2758   PS:
2759     foreach my $out (@output) {
2760         if ($snmp) {
2761             @states = ();  # contains states for the PS
2762
2763             $index    = $out->{powerSupplyIndex} - 1;
2764             $status   = $snmp_status{$out->{powerSupplyStatus}};
2765             $type     = get_hashval($out->{powerSupplyType}, \%ps_type);
2766             $err_type = defined $out->{powerSupplyConfigurationErrorType}
2767               ? $ps_config_error_type{$out->{powerSupplyConfigurationErrorType}} : undef;
2768
2769             # get the combined state from the StatusReading OID
2770             foreach my $mask (sort keys %ps_state) {
2771                 if (($out->{powerSupplySensorState} & $mask) != 0) {
2772                     push @states, $ps_state{$mask};
2773                 }
2774             }
2775
2776             # If configuration error, also include the error type
2777             if (defined $err_type) {
2778                 push @states, $err_type;
2779             }
2780
2781             # Finally, construct the state string
2782             $state = join q{, }, @states;
2783         }
2784         else {
2785             $index  = $out->{'Index'};
2786             $status = $out->{'Status'};
2787             $type   = $out->{'Type'};
2788             $state  = $out->{'Online Status'};
2789         }
2790
2791         next PS if blacklisted('ps', $index);
2792         $count{power}++;
2793
2794         if ($status ne 'Ok') {
2795             my $msg = sprintf 'Power Supply %d [%s] needs attention: %s',
2796               $index, $type, $state;
2797             report('chassis', $msg, $status2nagios{$status}, $index);
2798         }
2799         else {
2800             my $msg = sprintf 'Power Supply %d [%s]: %s',
2801               $index, $type, $state;
2802             report('chassis', $msg, $E_OK, $index);
2803         }
2804     }
2805     return;
2806 }
2807
2808
2809 #-----------------------------------------
2810 # CHASSIS: Check temperatures
2811 #-----------------------------------------
2812 sub check_temperatures {
2813     return if blacklisted('temp', 'all');
2814
2815     my $index    = undef;
2816     my $status   = undef;
2817     my $reading  = undef;
2818     my $location = undef;
2819     my $max_crit = undef;
2820     my $max_warn = undef;
2821     my $min_warn = undef;
2822     my $min_crit = undef;
2823     my $type     = undef;
2824     my $discrete = undef;
2825     my @output = ();
2826
2827     # Getting custom temperature thresholds (user option)
2828     my %warn_threshold = %{ custom_temperature_thresholds('w') };
2829     my %crit_threshold = %{ custom_temperature_thresholds('c') };
2830
2831     if ($snmp) {
2832         my %temp_oid
2833           = (
2834              '1.3.6.1.4.1.674.10892.1.700.20.1.2.1'  => 'temperatureProbeIndex',
2835              '1.3.6.1.4.1.674.10892.1.700.20.1.5.1'  => 'temperatureProbeStatus',
2836              '1.3.6.1.4.1.674.10892.1.700.20.1.6.1'  => 'temperatureProbeReading',
2837              '1.3.6.1.4.1.674.10892.1.700.20.1.7.1'  => 'temperatureProbeType',
2838              '1.3.6.1.4.1.674.10892.1.700.20.1.8.1'  => 'temperatureProbeLocationName',
2839              '1.3.6.1.4.1.674.10892.1.700.20.1.10.1' => 'temperatureProbeUpperCriticalThreshold',
2840              '1.3.6.1.4.1.674.10892.1.700.20.1.11.1' => 'temperatureProbeUpperNonCriticalThreshold',
2841              '1.3.6.1.4.1.674.10892.1.700.20.1.12.1' => 'temperatureProbeLowerNonCriticalThreshold',
2842              '1.3.6.1.4.1.674.10892.1.700.20.1.13.1' => 'temperatureProbeLowerCriticalThreshold',
2843              '1.3.6.1.4.1.674.10892.1.700.20.1.16.1' => 'temperatureProbeDiscreteReading',
2844             );
2845         # this didn't work well for some reason
2846         #my $result = $snmp_session->get_entries(-columns => [keys %temp_oid]);
2847
2848         # Getting values using the table
2849         my $temperatureProbeTable = '1.3.6.1.4.1.674.10892.1.700.20';
2850         my $result = $snmp_session->get_table(-baseoid => $temperatureProbeTable);
2851
2852         if (!defined $result) {
2853             printf "SNMP ERROR [temperatures]: %s.\n", $snmp_session->error;
2854             $snmp_session->close;
2855             exit $E_UNKNOWN;
2856         }
2857
2858         @output = @{ get_snmp_output($result, \%temp_oid) };
2859     }
2860     else {
2861         @output = @{ run_omreport("$omopt_chassis temps") };
2862     }
2863
2864     my %probe_type
2865       = (
2866          1  => 'Other',      # type is other than following values
2867          2  => 'Unknown',    # type is unknown
2868          3  => 'AmbientESM', # type is Ambient Embedded Systems Management temperature probe
2869          16 => 'Discrete',   # type is temperature probe with discrete reading
2870         );
2871
2872   TEMP:
2873     foreach my $out (@output) {
2874         if ($snmp) {
2875             $index    = $out->{temperatureProbeIndex} - 1;
2876             $status   = $snmp_probestatus{$out->{temperatureProbeStatus}};
2877             $reading  = $out->{temperatureProbeReading} / 10;
2878             $location = $out->{temperatureProbeLocationName};
2879             $max_crit = $out->{temperatureProbeUpperCriticalThreshold} / 10;
2880             $max_warn = $out->{temperatureProbeUpperNonCriticalThreshold} / 10;
2881             $min_crit = exists $out->{temperatureProbeLowerCriticalThreshold}
2882               ? $out->{temperatureProbeLowerCriticalThreshold} / 10 : '[N/A]';
2883             $min_warn = exists $out->{temperatureProbeLowerNonCriticalThreshold}
2884               ? $out->{temperatureProbeLowerNonCriticalThreshold} / 10 : '[N/A]';
2885             $type     = get_hashval($out->{temperatureProbeType}, \%probe_type);
2886             $discrete = exists $out->{temperatureProbeDiscreteReading}
2887               ? $out->{temperatureProbeDiscreteReading} : undef;
2888         }
2889         else {
2890             $index    = $out->{'Index'};
2891             $status   = $out->{'Status'};
2892             $reading  = $out->{'Reading'}; $reading =~ s{\.0\s+C}{}xms;
2893             $location = $out->{'Probe Name'};
2894             $max_crit = $out->{'Maximum Failure Threshold'}; $max_crit =~ s{\.0\s+C}{}xms;
2895             $max_warn = $out->{'Maximum Warning Threshold'}; $max_warn =~ s{\.0\s+C}{}xms;
2896             $min_crit = $out->{'Minimum Failure Threshold'}; $min_crit =~ s{\.0\s+C}{}xms;
2897             $min_warn = $out->{'Minimum Warning Threshold'}; $min_warn =~ s{\.0\s+C}{}xms;
2898             $type     = $reading =~ m{\A\d+\z}xms ? 'AmbientESM' : 'Discrete';
2899             $discrete = $reading;
2900         }
2901
2902         next TEMP if blacklisted('temp', $index);
2903         $count{temp}++;
2904
2905         if ($type eq 'Discrete') {
2906             my $msg = sprintf 'Temperature probe %d (%s): is %s',
2907               $index, $location, $discrete;
2908             my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2909             report('chassis', $msg, $err, $index);
2910         }
2911         else {
2912             # First check according to custom thresholds
2913             if (exists $crit_threshold{$index}{max} and $reading > $crit_threshold{$index}{max}) {
2914                 # Custom critical MAX
2915                 my $msg = sprintf 'Temperature Probe %d [%s] reads %d C (custom max=%d)',
2916                   $index, $location, $reading, $crit_threshold{$index}{max};
2917                 report('chassis', $msg, $E_CRITICAL, $index);
2918             }
2919             elsif (exists $warn_threshold{$index}{max} and $reading > $warn_threshold{$index}{max}) {
2920                 # Custom warning MAX
2921                 my $msg = sprintf 'Temperature Probe %d [%s] reads %d C (custom max=%d)',
2922                   $index, $location, $reading, $warn_threshold{$index}{max};
2923                 report('chassis', $msg, $E_WARNING, $index);
2924             }
2925             elsif (exists $crit_threshold{$index}{min} and $reading < $crit_threshold{$index}{min}) {
2926                 # Custom critical MIN
2927                 my $msg = sprintf 'Temperature Probe %d [%s] reads %d C (custom min=%d)',
2928                   $index, $location, $reading, $crit_threshold{$index}{min};
2929                 report('chassis', $msg, $E_CRITICAL, $index);
2930             }
2931             elsif (exists $warn_threshold{$index}{min} and $reading < $warn_threshold{$index}{min}) {
2932                 # Custom warning MIN
2933                 my $msg = sprintf 'Temperature Probe %d [%s] reads %d C (custom min=%d)',
2934                   $index, $location, $reading, $warn_threshold{$index}{min};
2935                 report('chassis', $msg, $E_WARNING, $index);
2936             }
2937             elsif ($status ne 'Ok' and $max_crit ne '[N/A]' and $reading > $max_crit) {
2938                 my $msg = sprintf 'Temperature Probe %d [%s] is critically high at %d C',
2939                   $index, $location, $reading;
2940                 my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2941                 report('chassis', $msg, $err, $index);
2942             }
2943             elsif ($status ne 'Ok' and $max_warn ne '[N/A]' and $reading > $max_warn) {
2944                 my $msg = sprintf 'Temperature Probe %d [%s] is too high at %d C',
2945                   $index, $location, $reading;
2946                 my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2947                 report('chassis', $msg, $err, $index);
2948             }
2949             elsif ($status ne 'Ok' and $min_crit ne '[N/A]' and $reading < $min_crit) {
2950                 my $msg = sprintf 'Temperature Probe %d [%s] is critically low at %d C',
2951                   $index, $location, $reading;
2952                 my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2953                 report('chassis', $msg, $err, $index);
2954             }
2955             elsif ($status ne 'Ok' and $min_warn ne '[N/A]' and $reading < $min_warn) {
2956                 my $msg = sprintf 'Temperature Probe %d [%s] is too low at %d C',
2957                   $index, $location, $reading;
2958                 my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2959                 report('chassis', $msg, $err, $index);
2960             }
2961             # Ok
2962             else {
2963                 my $msg = sprintf 'Temperature Probe %d [%s] reads %d C',
2964                   $index, $location, $reading;
2965                 if ($min_warn eq '[N/A]' and $min_crit eq '[N/A]') {
2966                     $msg .= sprintf ' (max=%s/%s)', $max_warn, $max_crit;
2967                 }
2968                 else {
2969                     $msg .= sprintf ' (min=%s/%s, max=%s/%s)',
2970                       $min_warn, $min_crit, $max_warn, $max_crit;
2971                 }
2972                 my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
2973                 report('chassis', $msg, $err, $index);
2974             }
2975
2976             # Collect performance data
2977             if (defined $opt{perfdata}) {
2978                 my $pname = lc $location;
2979                 $pname =~ s{\s}{_}gxms;
2980                 $pname =~ s{_temp\z}{}xms;
2981                 $pname =~ s{proc_}{cpu#}xms;
2982                 my $pkey = join q{_}, 'temp', $index, $pname;
2983                 push @perfdata, {
2984                                  label => $pkey,
2985                                  mini  => "t$index",
2986                                  value => $reading,
2987                                  unit  => '',
2988                                  warn  => $max_warn,
2989                                  crit  => $max_crit,
2990                                 };
2991             }
2992         }
2993     }
2994     return;
2995 }
2996
2997
2998 #-----------------------------------------
2999 # CHASSIS: Check processors
3000 #-----------------------------------------
3001 sub check_processors {
3002     return if blacklisted('cpu', 'all');
3003
3004     my $index   = undef;
3005     my $status  = undef;
3006     my $state   = undef;
3007     my $brand   = undef;
3008     my $family  = undef;
3009     my $man     = undef;
3010     my $speed   = undef;
3011     my @output = ();
3012
3013     if ($snmp) {
3014
3015         # NOTE: For some reason, older models don't have the
3016         # "Processor Device Status" OIDs. We check both the newer
3017         # (preferred) OIDs and the old ones.
3018
3019         my %cpu_oid
3020           = (
3021              '1.3.6.1.4.1.674.10892.1.1100.30.1.2.1'  => 'processorDeviceIndex',
3022              '1.3.6.1.4.1.674.10892.1.1100.30.1.5.1'  => 'processorDeviceStatus',
3023              '1.3.6.1.4.1.674.10892.1.1100.30.1.8.1'  => 'processorDeviceManufacturerName',
3024              '1.3.6.1.4.1.674.10892.1.1100.30.1.9.1'  => 'processorDeviceStatusState',
3025              '1.3.6.1.4.1.674.10892.1.1100.30.1.10.1' => 'processorDeviceFamily',
3026              '1.3.6.1.4.1.674.10892.1.1100.30.1.12.1' => 'processorDeviceCurrentSpeed',
3027              '1.3.6.1.4.1.674.10892.1.1100.30.1.23.1' => 'processorDeviceBrandName',
3028              '1.3.6.1.4.1.674.10892.1.1100.32.1.2.1'  => 'processorDeviceStatusIndex',
3029              '1.3.6.1.4.1.674.10892.1.1100.32.1.5.1'  => 'processorDeviceStatusStatus',
3030              '1.3.6.1.4.1.674.10892.1.1100.32.1.6.1'  => 'processorDeviceStatusReading',
3031             );
3032         my $result = undef;
3033         if ($opt{use_get_table}) {
3034             my $processorDeviceTable = '1.3.6.1.4.1.674.10892.1.1100.30.1';
3035             my $processorDeviceStatusTable = '1.3.6.1.4.1.674.10892.1.1100.32.1';
3036
3037             $result = $snmp_session->get_table(-baseoid => $processorDeviceTable);
3038             my $ext = $snmp_session->get_table(-baseoid => $processorDeviceStatusTable);
3039
3040             defined $ext && map { $$result{$_} = $$ext{$_} } keys %{ $ext };
3041         }
3042         else {
3043             $result = $snmp_session->get_entries(-columns => [keys %cpu_oid]);
3044         }
3045
3046         if (!defined $result) {
3047             printf "SNMP ERROR [processors]: %s.\n", $snmp_session->error;
3048             $snmp_session->close;
3049             exit $E_UNKNOWN;
3050         }
3051
3052         @output = @{ get_snmp_output($result, \%cpu_oid) };
3053     }
3054     else {
3055         @output = @{ run_omreport("$omopt_chassis processors") };
3056     }
3057
3058     my %cpu_state
3059       = (
3060          1 => 'Other',         # other than following values
3061          2 => 'Unknown',       # unknown
3062          3 => 'Enabled',       # enabled
3063          4 => 'User Disabled', # disabled by user via BIOS setup
3064          5 => 'BIOS Disabled', # disabled by BIOS (POST error)
3065          6 => 'Idle',          # idle
3066         );
3067
3068     my %cpu_reading
3069       = (
3070          1    => 'Internal Error',      # Internal Error
3071          2    => 'Thermal Trip',        # Thermal Trip
3072          32   => 'Configuration Error', # Configuration Error
3073          128  => 'Present',             # Processor Present
3074          256  => 'Disabled',            # Processor Disabled
3075          512  => 'Terminator Present',  # Terminator Present
3076          1024 => 'Throttled',           # Processor Throttled
3077         );
3078
3079     # Mapping between family numbers from SNMP and actual CPU family
3080     my %cpu_family
3081       = (
3082          1   => 'Other',                                2   => 'Unknown',
3083          3   => '8086',                                 4   => '80286',
3084          5   => '386',                                  6   => '486',
3085          7   => '8087',                                 8   => '80287',
3086          9   => '80387',                                10  => '80487',
3087          11  => 'Pentium',                              12  => 'Pentium Pro',
3088          13  => 'Pentium II',                           14  => 'Pentium with MMX',
3089          15  => 'Celeron',                              16  => 'Pentium II Xeon',
3090          17  => 'Pentium III',                          18  => 'Pentium III Xeon',
3091          19  => 'Pentium III',                          20  => 'Itanium',
3092          21  => 'Xeon',                                 22  => 'Pentium 4',
3093          23  => 'Xeon MP',                              24  => 'Itanium 2',
3094          25  => 'K5',                                   26  => 'K6',
3095          27  => 'K6-2',                                 28  => 'K6-3',
3096          29  => 'Athlon',                               30  => 'AMD2900',
3097          31  => 'K6-2+',                                32  => 'Power PC',
3098          33  => 'Power PC 601',                         34  => 'Power PC 603',
3099          35  => 'Power PC 603+',                        36  => 'Power PC 604',
3100          37  => 'Power PC 620',                         38  => 'Power PC x704',
3101          39  => 'Power PC 750',                         40  => 'Core Duo',
3102          41  => 'Core Duo mobile',                      42  => 'Core Solo mobile',
3103          43  => 'Intel Atom',                           44  => undef,
3104          45  => undef,                                  46  => undef,
3105          47  => undef,                                  48  => 'Alpha',
3106          49  => 'Alpha 21064',                          50  => 'Alpha 21066',
3107          51  => 'Alpha 21164',                          52  => 'Alpha 21164PC',
3108          53  => 'Alpha 21164a',                         54  => 'Alpha 21264',
3109          55  => 'Alpha 21364',                          56  => 'Turion II Ultra Dual-Core Mobile M',
3110          57  => 'Turion II Dual-Core Mobile M',         58  => 'Athlon II Dual-Core Mobile M ',
3111          59  => 'Opteron 6100',                         60  => undef,
3112          61  => undef,                                  62  => undef,
3113          63  => undef,                                  64  => 'MIPS',
3114          65  => 'MIPS R4000',                           66  => 'MIPS R4200',
3115          67  => 'MIPS R4400',                           68  => 'MIPS R4600',
3116          69  => 'MIPS R10000',                          70  => undef,
3117          71  => undef,                                  72  => undef,
3118          73  => undef,                                  74  => undef,
3119          75  => undef,                                  76  => undef,
3120          77  => undef,                                  78  => undef,
3121          79  => undef,                                  80  => 'SPARC',
3122          81  => 'SuperSPARC',                           82  => 'microSPARC II',
3123          83  => 'microSPARC IIep',                      84  => 'UltraSPARC',
3124          85  => 'UltraSPARC II',                        86  => 'UltraSPARC IIi',
3125          87  => 'UltraSPARC III',                       88  => 'UltraSPARC IIIi',
3126          89  => undef,                                  90  => undef,
3127          91  => undef,                                  92  => undef,
3128          93  => undef,                                  94  => undef,
3129          95  => undef,                                  96  => '68040',
3130          97  => '68xxx',                                98  => '68000',
3131          99  => '68010',                                100 => '68020',
3132          101 => '68030',                                102 => undef,
3133          103 => undef,                                  104 => undef,
3134          105 => undef,                                  106 => undef,
3135          107 => undef,                                  108 => undef,
3136          109 => undef,                                  110 => undef,
3137          111 => undef,                                  112 => 'Hobbit',
3138          113 => undef,                                  114 => undef,
3139          115 => undef,                                  116 => undef,
3140          117 => undef,                                  118 => undef,
3141          119 => undef,                                  120 => 'Crusoe TM5000',
3142          121 => 'Crusoe TM3000',                        122 => 'Efficeon TM8000',
3143          123 => undef,                                  124 => undef,
3144          125 => undef,                                  126 => undef,
3145          127 => undef,                                  128 => 'Weitek',
3146          129 => undef,                                  130 => 'Celeron M',
3147          131 => 'Athlon 64',                            132 => 'Opteron',
3148          133 => 'Sempron',                              134 => 'Turion 64 Mobile',
3149          135 => 'Dual-Core Opteron',                    136 => 'Athlon 64 X2 DC',
3150          137 => 'Turion 64 X2 M',                       138 => 'Quad-Core Opteron',
3151          139 => '3rd gen Opteron',                      140 => 'AMD Phenom FX Quad-Core',
3152          141 => 'AMD Phenom X4 Quad-Core',              142 => 'AMD Phenom X2 Dual-Core',
3153          143 => 'AMD Athlon X2 Dual-Core',              144 => 'PA-RISC',
3154          145 => 'PA-RISC 8500',                         146 => 'PA-RISC 8000',
3155          147 => 'PA-RISC 7300LC',                       148 => 'PA-RISC 7200',
3156          149 => 'PA-RISC 7100LC',                       150 => 'PA-RISC 7100',
3157          151 => undef,                                  152 => undef,
3158          153 => undef,                                  154 => undef,
3159          155 => undef,                                  156 => undef,
3160          157 => undef,                                  158 => undef,
3161          159 => undef,                                  160 => 'V30',
3162          161 => 'Quad-Core Xeon 3200',                  162 => 'Dual-Core Xeon 3000',
3163          163 => 'Quad-Core Xeon 5300',                  164 => 'Dual-Core Xeon 5100',
3164          165 => 'Dual-Core Xeon 5000',                  166 => 'Dual-Core Xeon LV',
3165          167 => 'Dual-Core Xeon ULV',                   168 => 'Dual-Core Xeon 7100',
3166          169 => 'Quad-Core Xeon 5400',                  170 => 'Quad-Core Xeon',
3167          171 => 'Dual-Core Xeon 5200',                  172 => 'Dual-Core Xeon 7200',
3168          173 => 'Quad-Core Xeon 7300',                  174 => 'Quad-Core Xeon 7400',
3169          175 => 'Multi-Core Xeon 7400',                 176 => 'M1',
3170          177 => 'M2',                                   178 => undef,
3171          179 => 'Pentium 4 HT',                         180 => 'AS400',
3172          181 => undef,                                  182 => 'Athlon XP',
3173          183 => 'Athlon MP',                            184 => 'Duron',
3174          185 => 'Pentium M',                            186 => 'Celeron D',
3175          187 => 'Pentium D',                            188 => 'Pentium Extreme',
3176          189 => 'Core Solo',                            190 => 'Core2',
3177          191 => 'Core2 Duo',                            192 => 'Core2 Solo',
3178          193 => 'Core2 Extreme',                        194 => 'Core2 Quad',
3179          195 => 'Core2 Extreme mobile',                 196 => 'Core2 Duo mobile',
3180          197 => 'Core2 Solo mobile',                    198 => 'Core i7',
3181          199 => 'Dual-Core Celeron',                    200 => 'IBM390',
3182          201 => 'G4',                                   202 => 'G5',
3183          203 => 'ESA/390 G6',                           204 => 'z/Architectur',
3184          205 => 'Core i5',                              206 => undef,
3185          207 => undef,                                  208 => undef,
3186          209 => undef,                                  210 => 'C7-M',
3187          211 => 'C7-D',                                 212 => 'C7',
3188          213 => 'Eden',                                 214 => 'Multi-Core Xeon',
3189          215 => 'Dual-Core Xeon 3xxx',                  216 => 'Quad-Core Xeon 3xxx',
3190          217 => undef,                                  218 => 'Dual-Core Xeon 5xxx',
3191          219 => 'Quad-Core Xeon 5xxx',                  220 => undef,
3192          221 => 'Dual-Core Xeon 7xxx',                  222 => 'Quad-Core Xeon 7xxx',
3193          223 => 'Multi-Core Xeon 7xxx',                 224 => undef,
3194          225 => undef,                                  226 => undef,
3195          227 => undef,                                  228 => undef,
3196          229 => undef,                                  230 => 'Embedded AMD Opteron Quad-Core',
3197          231 => 'AMD Phenom Triple-Core',               232 => 'AMD Turion Ultra Dual-Core Mobile',
3198          233 => 'AMD Turion Dual-Core Mobile',          234 => 'AMD Athlon Dual-Core',
3199          235 => 'AMD Sempron SI',                       236 => 'AMD Phenom II',
3200          237 => 'AMD Athlon II',                        238 => 'Six-Core AMD Opteron',
3201          239 => 'AMD Sempron M',                        240 => undef,
3202          241 => undef,                                  242 => undef,
3203          243 => undef,                                  244 => undef,
3204          245 => undef,                                  246 => undef,
3205          247 => undef,                                  248 => undef,
3206          249 => undef,                                  250 => 'i860',
3207          251 => 'i960',
3208         );
3209
3210   CPU:
3211     foreach my $out (@output) {
3212         if ($snmp) {
3213             $index  = exists $out->{processorDeviceStatusIndex}
3214               ? $out->{processorDeviceStatusIndex} - 1
3215                 : $out->{processorDeviceIndex} - 1;
3216             $status = exists $out->{processorDeviceStatusStatus}
3217               ? $snmp_status{$out->{processorDeviceStatusStatus}}
3218                 : $snmp_status{$out->{processorDeviceStatus}};
3219             if (exists $out->{processorDeviceStatusReading}) {
3220                 my @states  = ();  # contains states for the CPU
3221
3222                 # get the combined state from the StatusReading OID
3223                 foreach my $mask (sort keys %cpu_reading) {
3224                     if (($out->{processorDeviceStatusReading} & $mask) != 0) {
3225                         push @states, $cpu_reading{$mask};
3226                     }
3227                 }
3228
3229                 # Finally, create the state string
3230                 $state = join q{, }, @states;
3231             }
3232             else {
3233                 $state  = get_hashval($out->{processorDeviceStatusState}, \%cpu_state);
3234             }
3235             $man    = $out->{processorDeviceManufacturerName};
3236             $family = (exists $out->{processorDeviceFamily}
3237                        and exists $cpu_family{$out->{processorDeviceFamily}})
3238               ? $cpu_family{$out->{processorDeviceFamily}} : undef;
3239             $speed  = $out->{processorDeviceCurrentSpeed};
3240             $brand  = $out->{processorDeviceBrandName};
3241         }
3242         else {
3243             $index  = $out->{'Index'};
3244             $status = $out->{'Status'};
3245             $state  = $out->{'State'};
3246             $brand  = exists $out->{'Processor Brand'} ? $out->{'Processor Brand'} : undef;
3247             $family = exists $out->{'Processor Family'} ? $out->{'Processor Family'} : undef;
3248             $man    = exists $out->{'Processor Manufacturer'} ? $out->{'Processor Manufacturer'} : undef;
3249             $speed  = exists $out->{'Current Speed'} ? $out->{'Current Speed'} : undef;
3250         }
3251
3252         next CPU if blacklisted('cpu', $index);
3253
3254         # Ignore unoccupied CPU slots (omreport)
3255         next CPU if (defined $out->{'Processor Manufacturer'}
3256                      and $out->{'Processor Manufacturer'} eq '[Not Occupied]')
3257           or (defined $out->{'Processor Brand'} and $out->{'Processor Brand'} eq '[Not Occupied]');
3258
3259         # Ignore unoccupied CPU slots (snmp)
3260         if ($snmp and exists $out->{processorDeviceStatusReading}
3261             and $out->{processorDeviceStatusReading} == 0) {
3262             next CPU;
3263         }
3264
3265         $count{cpu}++;
3266
3267         if (defined $brand) {
3268             $brand =~ s{\s\s+}{ }gxms;
3269             $brand =~ s{\((R|tm)\)}{}gxms;
3270             $brand =~ s{\s(CPU|Processor)}{}xms;
3271             $brand =~ s{\s\@}{}xms;
3272         }
3273         elsif (defined $family and defined $man and defined $speed) {
3274             $speed =~ s{\A (\d+) .*}{$1}xms;
3275             $brand = sprintf '%s %s %.2fGHz', $man, $family, $speed / 1000;
3276         }
3277         else {
3278             $brand = "unknown";
3279         }
3280
3281         # Default
3282         if ($status ne 'Ok') {
3283             my $msg = sprintf 'Processor %d [%s] needs attention: %s',
3284               $index, $brand, $state;
3285             report('chassis', $msg, $status2nagios{$status}, $index);
3286         }
3287         # Ok
3288         else {
3289             my $msg = sprintf 'Processor %d [%s] is %s',
3290               $index, $brand, $state;
3291             report('chassis', $msg, $E_OK, $index);
3292         }
3293     }
3294     return;
3295 }
3296
3297
3298 #-----------------------------------------
3299 # CHASSIS: Check voltage probes
3300 #-----------------------------------------
3301 sub check_volts {
3302     return if blacklisted('volt', 'all');
3303
3304     my $index    = undef;
3305     my $status   = undef;
3306     my $reading  = undef;
3307     my $location = undef;
3308     my @output = ();
3309
3310     if ($snmp) {
3311         my %volt_oid
3312           = (
3313              '1.3.6.1.4.1.674.10892.1.600.20.1.2.1'  => 'voltageProbeIndex',
3314              '1.3.6.1.4.1.674.10892.1.600.20.1.5.1'  => 'voltageProbeStatus',
3315              '1.3.6.1.4.1.674.10892.1.600.20.1.6.1'  => 'voltageProbeReading',
3316              '1.3.6.1.4.1.674.10892.1.600.20.1.8.1'  => 'voltageProbeLocationName',
3317              '1.3.6.1.4.1.674.10892.1.600.20.1.16.1' => 'voltageProbeDiscreteReading',
3318             );
3319
3320         my $voltageProbeTable = '1.3.6.1.4.1.674.10892.1.600.20.1';
3321         my $result = $snmp_session->get_table(-baseoid => $voltageProbeTable);
3322
3323         if (!defined $result) {
3324             printf "SNMP ERROR [voltage]: %s.\n", $snmp_session->error;
3325             $snmp_session->close;
3326             exit $E_UNKNOWN;
3327         }
3328
3329         @output = @{ get_snmp_output($result, \%volt_oid) };
3330     }
3331     else {
3332         @output = @{ run_omreport("$omopt_chassis volts") };
3333     }
3334
3335     my %volt_discrete_reading
3336       = (
3337          1 => 'Good',
3338          2 => 'Bad',
3339         );
3340
3341   VOLT:
3342     foreach my $out (@output) {
3343         if ($snmp) {
3344             $index    = $out->{voltageProbeIndex} - 1;
3345             $status   = $snmp_probestatus{$out->{voltageProbeStatus}};
3346             $reading  = exists $out->{voltageProbeReading}
3347               ? sprintf('%.3f V', $out->{voltageProbeReading}/1000)
3348                 : get_hashval($out->{voltageProbeDiscreteReading}, \%volt_discrete_reading);
3349             $location = $out->{voltageProbeLocationName};
3350         }
3351         else {
3352             $index    = $out->{'Index'};
3353             $status   = $out->{'Status'};
3354             $reading  = $out->{'Reading'};
3355             $location = $out->{'Probe Name'};
3356         }
3357
3358         next VOLT if blacklisted('volt', $index);
3359         $count{volt}++;
3360
3361         my $msg = sprintf 'Voltage sensor %d [%s] is %s',
3362           $index, $location, $reading;
3363         my $err = $snmp ? $probestatus2nagios{$status} : $status2nagios{$status};
3364         report('chassis', $msg, $err, $index);
3365     }
3366     return;
3367 }
3368
3369
3370 #-----------------------------------------
3371 # CHASSIS: Check batteries
3372 #-----------------------------------------
3373 sub check_batteries {
3374     return if blacklisted('bp', 'all');
3375
3376     my $index    = undef;
3377     my $status   = undef;
3378     my $reading  = undef;
3379     my $location = undef;
3380     my @output = ();
3381
3382     if ($snmp) {
3383         my %bat_oid
3384           = (
3385              '1.3.6.1.4.1.674.10892.1.600.50.1.2.1' => 'batteryIndex',
3386              '1.3.6.1.4.1.674.10892.1.600.50.1.5.1' => 'batteryStatus',
3387              '1.3.6.1.4.1.674.10892.1.600.50.1.6.1' => 'batteryReading',
3388              '1.3.6.1.4.1.674.10892.1.600.50.1.7.1' => 'batteryLocationName',
3389             );
3390         my $result = undef;
3391         if ($opt{use_get_table}) {
3392             my $batteryTable = '1.3.6.1.4.1.674.10892.1.600.50.1';
3393             $result = $snmp_session->get_table(-baseoid => $batteryTable);
3394         }
3395         else {
3396             $result = $snmp_session->get_entries(-columns => [keys %bat_oid]);
3397         }
3398
3399         # No batteries is OK
3400         return 0 if !defined $result;
3401
3402         @output = @{ get_snmp_output($result, \%bat_oid) };
3403     }
3404     else {
3405         @output = @{ run_omreport("$omopt_chassis batteries") };
3406     }
3407
3408     my %bat_reading
3409       = (
3410          1 => 'Predictive Failure',
3411          2 => 'Failed',
3412          4 => 'Presence Detected',
3413         );
3414
3415   BATTERY:
3416     foreach my $out (@output) {
3417         if ($snmp) {
3418             $index    = $out->{batteryIndex} - 1;
3419             $status   = $snmp_status{$out->{batteryStatus}};
3420             $reading  = get_hashval($out->{batteryReading}, \%bat_reading);
3421             $location = $out->{batteryLocationName};
3422         }
3423         else {
3424             $index    = $out->{'Index'};
3425             $status   = $out->{'Status'};
3426             $reading  = $out->{'Reading'};
3427             $location = $out->{'Probe Name'};
3428         }
3429
3430         next BATTERY if blacklisted('bp', $index);
3431         $count{bat}++;
3432
3433         my $msg = sprintf 'Battery probe %d [%s] is %s',
3434           $index, $location, $reading;
3435         report('chassis', $msg, $status2nagios{$status}, $index);
3436     }
3437     return;
3438 }
3439
3440
3441 #-----------------------------------------
3442 # CHASSIS: Check amperage probes (power monitoring)
3443 #-----------------------------------------
3444 sub check_pwrmonitoring {
3445     return if blacklisted('amp', 'all');
3446
3447     my $index    = undef;
3448     my $status   = undef;
3449     my $reading  = undef;
3450     my $location = undef;
3451     my $max_crit = undef;
3452     my $max_warn = undef;
3453     my $unit     = undef;
3454     my @output = ();
3455
3456     if ($snmp) {
3457         my %amp_oid
3458           = (
3459              '1.3.6.1.4.1.674.10892.1.600.30.1.2.1'  => 'amperageProbeIndex',
3460              '1.3.6.1.4.1.674.10892.1.600.30.1.5.1'  => 'amperageProbeStatus',
3461              '1.3.6.1.4.1.674.10892.1.600.30.1.6.1'  => 'amperageProbeReading',
3462              '1.3.6.1.4.1.674.10892.1.600.30.1.7.1'  => 'amperageProbeType',
3463              '1.3.6.1.4.1.674.10892.1.600.30.1.8.1'  => 'amperageProbeLocationName',
3464              '1.3.6.1.4.1.674.10892.1.600.30.1.10.1' => 'amperageProbeUpperCriticalThreshold',
3465              '1.3.6.1.4.1.674.10892.1.600.30.1.11.1' => 'amperageProbeUpperNonCriticalThreshold',
3466              '1.3.6.1.4.1.674.10892.1.600.30.1.16.1' => 'amperageProbeDiscreteReading',
3467             );
3468         my $result = undef;
3469         if ($opt{use_get_table}) {
3470             my $amperageProbeTable = '1.3.6.1.4.1.674.10892.1.600.30.1';
3471             $result = $snmp_session->get_table(-baseoid => $amperageProbeTable);
3472         }
3473         else {
3474             $result = $snmp_session->get_entries(-columns => [keys %amp_oid]);
3475         }
3476
3477         # No pwrmonitoring is OK
3478         return 0 if !defined $result;
3479
3480         @output = @{ get_snmp_output($result, \%amp_oid) };
3481     }
3482     else {
3483         @output = @{ run_omreport("$omopt_chassis pwrmonitoring") };
3484     }
3485
3486     my %amp_type   # Amperage probe types
3487       = (
3488          1  => 'amperageProbeTypeIsOther',            # other than following values
3489          2  => 'amperageProbeTypeIsUnknown',          # unknown
3490          3  => 'amperageProbeTypeIs1Point5Volt',      # 1.5 amperage probe
3491          4  => 'amperageProbeTypeIs3Point3volt',      # 3.3 amperage probe
3492          5  => 'amperageProbeTypeIs5Volt',            # 5 amperage probe
3493          6  => 'amperageProbeTypeIsMinus5Volt',       # -5 amperage probe
3494          7  => 'amperageProbeTypeIs12Volt',           # 12 amperage probe
3495          8  => 'amperageProbeTypeIsMinus12Volt',      # -12 amperage probe
3496          9  => 'amperageProbeTypeIsIO',               # I/O probe
3497          10 => 'amperageProbeTypeIsCore',             # Core probe
3498          11 => 'amperageProbeTypeIsFLEA',             # FLEA (standby) probe
3499          12 => 'amperageProbeTypeIsBattery',          # Battery probe
3500          13 => 'amperageProbeTypeIsTerminator',       # SCSI Termination probe
3501          14 => 'amperageProbeTypeIs2Point5Volt',      # 2.5 amperage probe
3502          15 => 'amperageProbeTypeIsGTL',              # GTL (ground termination logic) probe
3503          16 => 'amperageProbeTypeIsDiscrete',         # amperage probe with discrete reading
3504          23 => 'amperageProbeTypeIsPowerSupplyAmps',  # Power Supply probe with reading in Amps
3505          24 => 'amperageProbeTypeIsPowerSupplyWatts', # Power Supply probe with reading in Watts
3506          25 => 'amperageProbeTypeIsSystemAmps',       # System probe with reading in Amps
3507          26 => 'amperageProbeTypeIsSystemWatts',      # System probe with reading in Watts
3508         );
3509
3510     my %amp_discrete
3511       = (
3512          1 => 'Good',
3513          2 => 'Bad',
3514         );
3515
3516     my %amp_unit
3517       = (
3518          'amperageProbeTypeIsPowerSupplyAmps'  => 'hA',  # tenths of Amps
3519          'amperageProbeTypeIsSystemAmps'       => 'hA',  # tenths of Amps
3520          'amperageProbeTypeIsPowerSupplyWatts' => 'W',   # Watts
3521          'amperageProbeTypeIsSystemWatts'      => 'W',   # Watts
3522          'amperageProbeTypeIsDiscrete'         => q{},   # discrete reading, no unit
3523         );
3524
3525   AMP:
3526     foreach my $out (@output) {
3527         if ($snmp) {
3528             $index    = $out->{amperageProbeIndex} - 1;
3529             $status   = $snmp_status{$out->{amperageProbeStatus}};
3530             $reading  = get_hashval($out->{amperageProbeType}, \%amp_type) eq 'amperageProbeTypeIsDiscrete'
3531               ? get_hashval($out->{amperageProbeDiscreteReading}, \%amp_discrete)
3532                 : $out->{amperageProbeReading};
3533             $location = $out->{amperageProbeLocationName};
3534             $max_crit = exists $out->{amperageProbeUpperCriticalThreshold}
3535               ? $out->{amperageProbeUpperCriticalThreshold} : 0;
3536             $max_warn = exists $out->{amperageProbeUpperNonCriticalThreshold}
3537               ? $out->{amperageProbeUpperNonCriticalThreshold} : 0;
3538             $unit     = exists $amp_unit{$amp_type{$out->{amperageProbeType}}}
3539               ? $amp_unit{$amp_type{$out->{amperageProbeType}}} : 'mA';
3540             if ($unit eq 'hA') {
3541                 $reading  /= 10;
3542                 $max_crit /= 10;
3543                 $max_warn /= 10;
3544                 $unit      = 'A';
3545             }
3546         }
3547         else {
3548             $index    = $out->{'Index'};
3549             next AMP if (!defined $index || $index !~ m/^\d+$/x);
3550             $status   = $out->{'Status'};
3551             $reading  = $out->{'Reading'};
3552             $location = $out->{'Probe Name'};
3553             $max_crit = $out->{'Failure Threshold'} ne '[N/A]'
3554               ? $out->{'Failure Threshold'} : 0;
3555             $max_warn = $out->{'Warning Threshold'} ne '[N/A]'
3556               ? $out->{'Warning Threshold'} : 0;
3557             $reading  =~ s{\A (\d+.*?)\s+([a-zA-Z]+) \s*\z}{$1}xms;
3558             $unit     = $2;
3559             $max_warn =~ s{\A (\d+.*?)\s+[a-zA-Z]+ \s*\z}{$1}xms;
3560             $max_crit =~ s{\A (\d+.*?)\s+[a-zA-Z]+ \s*\z}{$1}xms;
3561         }
3562
3563         next AMP if blacklisted('amp', $index);
3564         next AMP if $index !~ m{\A \d+ \z}xms;
3565         $count{amp}++;
3566
3567         my $msg = sprintf 'Amperage probe %d [%s] reads %s %s',
3568           $index, $location, $reading, $unit, $status;
3569         report('chassis', $msg, $status2nagios{$status}, $index);
3570
3571         # Collect performance data
3572         if (defined $opt{perfdata}) {
3573             next AMP if $reading !~ m{\A \d+(\.\d+)? \z}xms; # discrete reading (not number)
3574             my $label = join q{_}, 'pwr_mon', $index, lc $location;
3575             $label =~ s{\s}{_}gxms;
3576             push @perfdata, {
3577                              label => $label,
3578                              mini  => "p$index",
3579                              value => $reading,
3580                              unit  => '',
3581                              warn  => $max_warn,
3582                              crit  => $max_crit,
3583                             };
3584         }
3585     }
3586
3587     # Collect EXTRA performance data not found at first run. This is a
3588     # rather ugly hack
3589     if (defined $opt{perfdata} && !$snmp) {
3590         my $found = 0;
3591         my $index = 0;
3592         my %used  = ();
3593
3594         # find used indexes
3595         foreach (@perfdata) {
3596             if ($_->{label} =~ m/\A pwr_mon_(\d+)/xms) {
3597                 $used{$1} = 1;
3598             }
3599         }
3600
3601       AMP2:
3602         foreach my $line (@{ run_command("$omreport $omopt_chassis pwrmonitoring -fmt ssv") }) {
3603             chop $line;
3604             if ($line eq 'Location;Reading') {
3605                 $found = 1;
3606                 next AMP2;
3607             }
3608             if ($line eq q{}) {
3609                 $found = 0;
3610                 next AMP2;
3611             }
3612             if ($found and $line =~ m/\A ([^;]+?) ; (\d*\.\d+) \s [AW] \z/xms) {
3613                 my $aname = lc $1;
3614                 my $aval = $2;
3615                 $aname =~ s{\s}{_}gxms;
3616
3617                 # don't use an existing index
3618                 while (exists $used{$index}) { ++$index; }
3619
3620                 push @perfdata, {
3621                                  label => "pwr_mon_${index}_${aname}",
3622                                  mini  => "p$index",
3623                                  value => $aval,
3624                                  unit  => '',
3625                                  warn  => 0,
3626                                  crit  => 0,
3627                                 };
3628                 ++$index;
3629             }
3630         }
3631     }
3632
3633     return;
3634 }
3635
3636
3637 #-----------------------------------------
3638 # CHASSIS: Check intrusion
3639 #-----------------------------------------
3640 sub check_intrusion {
3641     return if blacklisted('intr', 'all');
3642
3643     my $index    = undef;
3644     my $status   = undef;
3645     my $reading  = undef;
3646     my @output = ();
3647
3648     if ($snmp) {
3649         my %int_oid
3650           = (
3651              '1.3.6.1.4.1.674.10892.1.300.70.1.2.1' => 'intrusionIndex',
3652              '1.3.6.1.4.1.674.10892.1.300.70.1.5.1' => 'intrusionStatus',
3653              '1.3.6.1.4.1.674.10892.1.300.70.1.6.1' => 'intrusionReading',
3654             );
3655         my $result = undef;
3656         if ($opt{use_get_table}) {
3657             my $intrusionTable = '1.3.6.1.4.1.674.10892.1.300.70.1';
3658             $result = $snmp_session->get_table(-baseoid => $intrusionTable);
3659         }
3660         else {
3661             $result = $snmp_session->get_entries(-columns => [keys %int_oid]);
3662         }
3663
3664         # No intrusion is OK
3665         return 0 if !defined $result;
3666
3667         @output = @{ get_snmp_output($result, \%int_oid) };
3668     }
3669     else {
3670         @output = @{ run_omreport("$omopt_chassis intrusion") };
3671     }
3672
3673     my %int_reading
3674       = (
3675          1 => 'Not Breached',          # chassis not breached and no uncleared breaches
3676          2 => 'Breached',              # chassis currently breached
3677          3 => 'Breached Prior',        # chassis breached prior to boot and has not been cleared
3678          4 => 'Breach Sensor Failure', # intrusion sensor has failed
3679         );
3680
3681   INTRUSION:
3682     foreach my $out (@output) {
3683         if ($snmp) {
3684             $index    = $out->{intrusionIndex} - 1;
3685             $status   = $snmp_status{$out->{intrusionStatus}};
3686             $reading  = get_hashval($out->{intrusionReading}, \%int_reading);
3687         }
3688         else {
3689             $index    = $out->{'Index'};
3690             $status   = $out->{'Status'};
3691             $reading  = $out->{'State'};
3692         }
3693
3694         next INTRUSION if blacklisted('intr', $index);
3695         $count{intr}++;
3696
3697         if ($status ne 'Ok') {
3698             my $msg = sprintf 'Chassis intrusion %d detected: %s',
3699               $index, $reading;
3700             report('chassis', $msg, $E_WARNING, $index);
3701         }
3702         # Ok
3703         else {
3704             my $msg = sprintf 'Chassis intrusion %d detection: %s (%s)',
3705               $index, $status, $reading;
3706             report('chassis', $msg, $E_OK, $index);
3707         }
3708     }
3709     return;
3710 }
3711
3712
3713 #-----------------------------------------
3714 # CHASSIS: Check alert log
3715 #-----------------------------------------
3716 sub check_alertlog {
3717     return if $snmp; # Not supported with SNMP
3718
3719     my @output = @{ run_omreport("$omopt_system alertlog") };
3720     foreach my $out (@output) {
3721         ++$count{alert}{$out->{Severity}};
3722     }
3723
3724     # Create error messages and set exit value if appropriate
3725     my $err = 0;
3726     if ($count{alert}{'Critical'} > 0)        { $err = $E_CRITICAL; }
3727     elsif ($count{alert}{'Non-Critical'} > 0) { $err = $E_WARNING;  }
3728
3729     my $msg = sprintf 'Alert log content: %d critical, %d non-critical, %d ok',
3730       $count{alert}{'Critical'}, $count{alert}{'Non-Critical'}, $count{alert}{'Ok'};
3731     report('other', $msg, $err);
3732
3733     return;
3734 }
3735
3736 #-----------------------------------------
3737 # CHASSIS: Check ESM log overall health
3738 #-----------------------------------------
3739 sub check_esmlog_health {
3740     my $health = 'Ok';
3741
3742     if ($snmp) {
3743         my $systemStateEventLogStatus = '1.3.6.1.4.1.674.10892.1.200.10.1.41.1';
3744         my $result = $snmp_session->get_request(-varbindlist => [$systemStateEventLogStatus]);
3745         if (!defined $result) {
3746             my $msg = sprintf 'SNMP ERROR [esmhealth]: %s',
3747               $snmp_session->error;
3748             report('other', $msg, $E_UNKNOWN);
3749         }
3750         $health = $snmp_status{$result->{$systemStateEventLogStatus}};
3751     }
3752     else {
3753         foreach (@{ run_command("$omreport $omopt_system esmlog -fmt ssv") }) {
3754             if (m/\A Health;(.+) \z/xms) {
3755                 $health = $1;
3756                 chop $health;
3757                 last;
3758             }
3759         }
3760     }
3761
3762     # If the overall health of the ESM log is other than "Ok", the
3763     # fill grade of the log is more than 80% and the log should be
3764     # cleared
3765     if ($health eq 'Ok') {
3766         my $msg = sprintf 'ESM log health is Ok (less than 80%% full)';
3767         report('other', $msg, $E_OK);
3768     }
3769     elsif ($health eq 'Critical') {
3770         my $msg = sprintf 'ESM log is 100%% full';
3771         report('other', $msg, $status2nagios{$health});
3772     }
3773     else {
3774         my $msg = sprintf 'ESM log is more than 80%% full';
3775         report('other', $msg, $status2nagios{$health});
3776     }
3777
3778     return;
3779 }
3780
3781 #-----------------------------------------
3782 # CHASSIS: Check ESM log
3783 #-----------------------------------------
3784 sub check_esmlog {
3785     my @output = ();
3786
3787     if ($snmp) {
3788         my %esm_oid
3789           = (
3790              '1.3.6.1.4.1.674.10892.1.300.40.1.7.1'  => 'eventLogSeverityStatus',
3791             );
3792         my $result = $snmp_session->get_entries(-columns => [keys %esm_oid]);
3793
3794         # No entries is OK
3795         return if !defined $result;
3796
3797         @output = @{ get_snmp_output($result, \%esm_oid) };
3798         foreach my $out (@output) {
3799             ++$count{esm}{$snmp_status{$out->{eventLogSeverityStatus}}};
3800         }
3801     }
3802     else {
3803         @output = @{ run_omreport("$omopt_system esmlog") };
3804         foreach my $out (@output) {
3805             ++$count{esm}{$out->{Severity}};
3806         }
3807     }
3808
3809     # Create error messages and set exit value if appropriate
3810     my $err = 0;
3811     if ($count{esm}{'Critical'} > 0)        { $err = $E_CRITICAL; }
3812     elsif ($count{esm}{'Non-Critical'} > 0) { $err = $E_WARNING;  }
3813
3814     my $msg = sprintf 'ESM log content: %d critical, %d non-critical, %d ok',
3815       $count{esm}{'Critical'}, $count{esm}{'Non-Critical'}, $count{esm}{'Ok'};
3816     report('other', $msg, $err);
3817
3818     return;
3819 }
3820
3821 #
3822 # Handy function for checking all storage components
3823 #
3824 sub check_storage {
3825     check_controllers();
3826     check_physical_disks();
3827     check_virtual_disks();
3828     check_cache_battery();
3829     check_connectors();
3830     check_enclosures();
3831     check_enclosure_fans();
3832     check_enclosure_pwr();
3833     check_enclosure_temp();
3834     check_enclosure_emms();
3835     return;
3836 }
3837
3838
3839
3840 #---------------------------------------------------------------------
3841 # Info functions
3842 #---------------------------------------------------------------------
3843
3844 #
3845 # Fetch output from 'omreport chassis info', put in sysinfo hash
3846 #
3847 sub get_omreport_chassis_info {
3848     if (open my $INFO, '-|', "$omreport $omopt_chassis info -fmt ssv") {
3849         my @lines = <$INFO>;
3850         close $INFO;
3851         foreach (@lines) {
3852             next if !m/\A (Chassis\sModel|Chassis\sService\sTag|Model|Service\sTag)/xms;
3853             my ($key, $val) = split /;/xms;
3854             $key =~ s{\s+\z}{}xms; # remove trailing whitespace
3855             $val =~ s{\s+\z}{}xms; # remove trailing whitespace
3856             if ($key eq 'Chassis Model' or $key eq 'Model') {
3857                 $sysinfo{model}  = $val;
3858             }
3859             if ($key eq 'Chassis Service Tag' or $key eq 'Service Tag') {
3860                 $sysinfo{serial} = $val;
3861             }
3862         }
3863     }
3864     return;
3865 }
3866
3867 #
3868 # Fetch output from 'omreport chassis bios', put in sysinfo hash
3869 #
3870 sub get_omreport_chassis_bios {
3871     if (open my $BIOS, '-|', "$omreport $omopt_chassis bios -fmt ssv") {
3872         my @lines = <$BIOS>;
3873         close $BIOS;
3874         foreach (@lines) {
3875             next if !m/;/xms;
3876             my ($key, $val) = split /;/xms;
3877             $key =~ s{\s+\z}{}xms; # remove trailing whitespace
3878             $val =~ s{\s+\z}{}xms; # remove trailing whitespace
3879             $sysinfo{bios}     = $val if $key eq 'Version';
3880             $sysinfo{biosdate} = $val if $key eq 'Release Date';
3881         }
3882     }
3883     return;
3884 }
3885
3886 #
3887 # Fetch output from 'omreport system operatingsystem', put in sysinfo hash
3888 #
3889 sub get_omreport_system_operatingsystem {
3890     if (open my $VER, '-|', "$omreport $omopt_system operatingsystem -fmt ssv") {
3891         my @lines = <$VER>;
3892         close $VER;
3893         foreach (@lines) {
3894             next if !m/;/xms;
3895             my ($key, $val) = split /;/xms;
3896             $key =~ s{\s+\z}{}xms; # remove trailing whitespace
3897             $val =~ s{\s+\z}{}xms; # remove trailing whitespace
3898             if ($key eq 'Operating System') {
3899                 $sysinfo{osname} = $val;
3900             }
3901             elsif ($key eq 'Operating System Version') {
3902                 $sysinfo{osver}  = $val;
3903             }
3904         }
3905     }
3906     return;
3907 }
3908
3909 #
3910 # Fetch output from 'omreport about', put in sysinfo hash
3911 #
3912 sub get_omreport_about {
3913     if (open my $OM, '-|', "$omreport about -fmt ssv") {
3914         my @lines = <$OM>;
3915         close $OM;
3916         foreach (@lines) {
3917             if (m/\A Version;(.+) \z/xms) {
3918                 $sysinfo{om} = $1;
3919                 chomp $sysinfo{om};
3920             }
3921         }
3922     }
3923     return;
3924 }
3925
3926 #
3927 # Fetch chassis info via SNMP, put in sysinfo hash
3928 #
3929 sub get_snmp_chassis_info {
3930     my %chassis_oid
3931       = (
3932          '1.3.6.1.4.1.674.10892.1.300.10.1.9.1'  => 'chassisModelName',
3933          '1.3.6.1.4.1.674.10892.1.300.10.1.11.1' => 'chassisServiceTagName',
3934         );
3935
3936     my $chassisInformationTable = '1.3.6.1.4.1.674.10892.1.300.10.1';
3937     my $result = $snmp_session->get_table(-baseoid => $chassisInformationTable);
3938
3939     if (defined $result) {
3940         foreach my $oid (keys %{ $result }) {
3941             if (exists $chassis_oid{$oid} and $chassis_oid{$oid} eq 'chassisModelName') {
3942                 $sysinfo{model} = $result->{$oid};
3943                 $sysinfo{model} =~ s{\s+\z}{}xms; # remove trailing whitespace
3944             }
3945             elsif (exists $chassis_oid{$oid} and $chassis_oid{$oid} eq 'chassisServiceTagName') {
3946                 $sysinfo{serial} = $result->{$oid};
3947             }
3948         }
3949     }
3950     else {
3951         my $msg = sprintf 'SNMP ERROR getting chassis info: %s',
3952           $snmp_session->error;
3953         report('other', $msg, $E_UNKNOWN);
3954     }
3955     return;
3956 }
3957
3958 #
3959 # Fetch BIOS info via SNMP, put in sysinfo hash
3960 #
3961 sub get_snmp_chassis_bios {
3962     my %bios_oid
3963       = (
3964          '1.3.6.1.4.1.674.10892.1.300.50.1.7.1.1' => 'systemBIOSReleaseDateName',
3965          '1.3.6.1.4.1.674.10892.1.300.50.1.8.1.1' => 'systemBIOSVersionName',
3966         );
3967
3968     my $systemBIOSTable = '1.3.6.1.4.1.674.10892.1.300.50.1';
3969     my $result = $snmp_session->get_table(-baseoid => $systemBIOSTable);
3970
3971     if (defined $result) {
3972         foreach my $oid (keys %{ $result }) {
3973             if (exists $bios_oid{$oid} and $bios_oid{$oid} eq 'systemBIOSReleaseDateName') {
3974                 $sysinfo{biosdate} = $result->{$oid};
3975                 $sysinfo{biosdate} =~ s{\A (\d{4})(\d{2})(\d{2}).*}{$2/$3/$1}xms;
3976             }
3977             elsif (exists $bios_oid{$oid} and $bios_oid{$oid} eq 'systemBIOSVersionName') {
3978                 $sysinfo{bios} = $result->{$oid};
3979             }
3980         }
3981     }
3982     else {
3983         my $msg = sprintf 'SNMP ERROR getting BIOS info: %s',
3984           $snmp_session->error;
3985         report('other', $msg, $E_UNKNOWN);
3986     }
3987     return;
3988 }
3989
3990 #
3991 # Fetch OS info via SNMP, put in sysinfo hash
3992 #
3993 sub get_snmp_system_operatingsystem {
3994     my %os_oid
3995       = (
3996          '1.3.6.1.4.1.674.10892.1.400.10.1.6.1' => 'operatingSystemOperatingSystemName',
3997          '1.3.6.1.4.1.674.10892.1.400.10.1.7.1' => 'operatingSystemOperatingSystemVersionName',
3998         );
3999
4000     my $operatingSystemTable = '1.3.6.1.4.1.674.10892.1.400.10.1';
4001     my $result = $snmp_session->get_table(-baseoid => $operatingSystemTable);
4002
4003     if (defined $result) {
4004         foreach my $oid (keys %{ $result }) {
4005             if (exists $os_oid{$oid} and $os_oid{$oid} eq 'operatingSystemOperatingSystemName') {
4006                 $sysinfo{osname} = ($result->{$oid});
4007             }
4008             elsif (exists $os_oid{$oid} and $os_oid{$oid} eq 'operatingSystemOperatingSystemVersionName') {
4009                 $sysinfo{osver} = $result->{$oid};
4010             }
4011         }
4012     }
4013     else {
4014         my $msg = sprintf 'SNMP ERROR getting OS info: %s',
4015           $snmp_session->error;
4016         report('other', $msg, $E_UNKNOWN);
4017     }
4018     return;
4019 }
4020
4021 #
4022 # Fetch OMSA version via SNMP, put in sysinfo hash
4023 #
4024 sub get_snmp_about {
4025     my %omsa_oid
4026       = (
4027          '1.3.6.1.4.1.674.10892.1.100.10.0' => 'systemManagementSoftwareGlobalVersionName',
4028         );
4029     my $systemManagementSoftwareGroup = '1.3.6.1.4.1.674.10892.1.100';
4030     my $result = $snmp_session->get_table(-baseoid => $systemManagementSoftwareGroup);
4031     if (defined $result) {
4032         foreach my $oid (keys %{ $result }) {
4033             if (exists $omsa_oid{$oid} and $omsa_oid{$oid} eq 'systemManagementSoftwareGlobalVersionName') {
4034                 $sysinfo{om} = ($result->{$oid});
4035             }
4036         }
4037     }
4038     else {
4039         my $msg = sprintf 'SNMP ERROR getting OMSA info: %s',
4040           $snmp_session->error;
4041         report('other', $msg, $E_UNKNOWN);
4042     }
4043     return;
4044 }
4045
4046 #
4047 # Collects some information about the system
4048 #
4049 sub get_sysinfo
4050 {
4051     # Get system model and serial number
4052     $snmp ? get_snmp_chassis_info() : get_omreport_chassis_info();
4053
4054     # Get BIOS information. Only if needed
4055     if ( $opt{okinfo} >= 1
4056          or $opt{debug}
4057          or (defined $opt{postmsg} and $opt{postmsg} =~ m/[%][bd]/xms) ) {
4058         $snmp ? get_snmp_chassis_bios() : get_omreport_chassis_bios();
4059     }
4060
4061     # Get OMSA information. Only if needed
4062     if ($opt{okinfo} >= 3 or $opt{debug}) {
4063         $snmp ? get_snmp_about() : get_omreport_about();
4064     }
4065
4066     # Return now if debug
4067     return if $opt{debug};
4068
4069     # Get OS information. Only if needed
4070     if (defined $opt{postmsg} and $opt{postmsg} =~ m/[%][or]/xms) {
4071         $snmp ? get_snmp_system_operatingsystem() : get_omreport_system_operatingsystem();
4072     }
4073
4074     return;
4075 }
4076
4077
4078 # Helper function for running omreport when the results are strictly
4079 # name=value pairs.
4080 sub run_omreport_info {
4081     my $command = shift;
4082     my %output  = ();
4083     my @keys    = ();
4084
4085     # Run omreport and fetch output
4086     my $rawtext = slurp_command("$omreport $command -fmt ssv 2>&1");
4087
4088     # Parse output, store in array
4089     for ((split /\n/xms, $rawtext)) {
4090         if (m/\A Error/xms) {
4091             my $msg = "Problem running 'omreport $command': $_";
4092             report('other', $msg, $E_UNKNOWN);
4093         }
4094         next if !m/;/xms;  # ignore lines with less than two fields
4095         my @vals = split m/;/xms;
4096         $output{$vals[0]} = $vals[1];
4097     }
4098
4099     # Finally, return the collected information
4100     return \%output;
4101 }
4102
4103 # Get various firmware information (BMC, RAC)
4104 sub get_firmware_info {
4105     my @snmp_output = ();
4106     my %nrpe_output = ();
4107
4108     if ($snmp) {
4109         my %fw_oid
4110           = (
4111              '1.3.6.1.4.1.674.10892.1.300.60.1.7.1'  => 'firmwareType',
4112              '1.3.6.1.4.1.674.10892.1.300.60.1.8.1'  => 'firmwareTypeName',
4113              '1.3.6.1.4.1.674.10892.1.300.60.1.11.1' => 'firmwareVersionName',
4114             );
4115
4116         my $firmwareTable = '1.3.6.1.4.1.674.10892.1.300.60.1';
4117         my $result = $snmp_session->get_table(-baseoid => $firmwareTable);
4118
4119         # Some don't have this OID, this is ok
4120         if (!defined $result) {
4121             return;
4122         }
4123
4124         @snmp_output = @{ get_snmp_output($result, \%fw_oid) };
4125     }
4126     else {
4127         %nrpe_output = %{ run_omreport_info("$omopt_chassis info") };
4128     }
4129
4130     my %fw_type  # Firmware types
4131       = (
4132          1  => 'other',                              # other than following values
4133          2  => 'unknown',                            # unknown
4134          3  => 'systemBIOS',                         # System BIOS
4135          4  => 'embeddedSystemManagementController', # Embedded System Management Controller
4136          5  => 'powerSupplyParallelingBoard',        # Power Supply Paralleling Board
4137          6  => 'systemBackPlane',                    # System (Primary) Backplane
4138          7  => 'powerVault2XXSKernel',               # PowerVault 2XXS Kernel
4139          8  => 'powerVault2XXSApplication',          # PowerVault 2XXS Application
4140          9  => 'frontPanel',                         # Front Panel Controller
4141          10 => 'baseboardManagementController',      # Baseboard Management Controller
4142          11 => 'hotPlugPCI',                         # Hot Plug PCI Controller
4143          12 => 'sensorData',                         # Sensor Data Records
4144          13 => 'peripheralBay',                      # Peripheral Bay Backplane
4145          14 => 'secondaryBackPlane',                 # Secondary Backplane for ESM 2 systems
4146          15 => 'secondaryBackPlaneESM3And4',         # Secondary Backplane for ESM 3 and 4 systems
4147          16 => 'rac',                                # Remote Access Controller
4148          17 => 'imc'                                 # Integrated Management Controller
4149         );
4150
4151
4152     if ($snmp) {
4153         foreach my $out (@snmp_output) {
4154             if ($fw_type{$out->{firmwareType}} eq 'baseboardManagementController') {
4155                 $sysinfo{'bmc'} = 1;
4156                 $sysinfo{'bmc_fw'} = $out->{firmwareVersionName};
4157             }
4158             elsif ($fw_type{$out->{firmwareType}} =~ m{\A rac|imc \z}xms) {
4159                 my $name = $out->{firmwareTypeName}; $name =~ s/\s//gxms;
4160                 $sysinfo{'rac'} = 1;
4161                 $sysinfo{'rac_name'} = $name;
4162                 $sysinfo{'rac_fw'} = $out->{firmwareVersionName};
4163             }
4164         }
4165     }
4166     else {
4167         foreach my $key (keys %nrpe_output) {
4168             next if !defined $nrpe_output{$key};
4169             if ($key eq 'BMC Version' or $key eq 'Baseboard Management Controller Version') {
4170                 $sysinfo{'bmc'} = 1;
4171                 $sysinfo{'bmc_fw'} = $nrpe_output{$key};
4172             }
4173             elsif ($key =~ m{\A (i?DRAC)\s*(\d?)\s+Version}xms) {
4174                 my $name = "$1$2";
4175                 $sysinfo{'rac'} = 1;
4176                 $sysinfo{'rac_fw'} = $nrpe_output{$key};
4177                 $sysinfo{'rac_name'} = $name;
4178             }
4179         }
4180     }
4181
4182     return;
4183 }
4184
4185
4186
4187 #=====================================================================
4188 # Main program
4189 #=====================================================================
4190
4191 # Here we do the actual checking of components
4192 # Check global status if applicable
4193 if ($global) {
4194     $globalstatus = check_global();
4195 }
4196
4197 # Do multiple selected checks
4198 if ($check{storage})     { check_storage();       }
4199 if ($check{memory})      { check_memory();        }
4200 if ($check{fans})        { check_fans();          }
4201 if ($check{power})       { check_powersupplies(); }
4202 if ($check{temp})        { check_temperatures();  }
4203 if ($check{cpu})         { check_processors();    }
4204 if ($check{voltage})     { check_volts();         }
4205 if ($check{batteries})   { check_batteries();     }
4206 if ($check{amperage})    { check_pwrmonitoring(); }
4207 if ($check{intrusion})   { check_intrusion();     }
4208 if ($check{alertlog})    { check_alertlog();      }
4209 if ($check{esmlog})      { check_esmlog();        }
4210 if ($check{esmhealth})   { check_esmlog_health(); }
4211
4212
4213 #---------------------------------------------------------------------
4214 # Finish up
4215 #---------------------------------------------------------------------
4216
4217 # Counter variable
4218 %nagios_alert_count
4219   = (
4220      'OK'       => 0,
4221      'WARNING'  => 0,
4222      'CRITICAL' => 0,
4223      'UNKNOWN'  => 0,
4224     );
4225
4226 # Get system information
4227 get_sysinfo();
4228
4229 # Get firmware info if requested via option
4230 if ($opt{okinfo} >= 1) {
4231     get_firmware_info();
4232 }
4233
4234 # Close SNMP session
4235 if ($snmp) {
4236     $snmp_session->close;
4237 }
4238
4239 # Print messages
4240 if ($opt{debug}) {
4241     print "   System:      $sysinfo{model}\n";
4242     print "   ServiceTag:  $sysinfo{serial}";
4243     print q{ } x (25 - length $sysinfo{serial}), "OMSA version:    $sysinfo{om}\n";
4244     print "   BIOS/date:   $sysinfo{bios} $sysinfo{biosdate}";
4245     print q{ } x (25 - length "$sysinfo{bios} $sysinfo{biosdate}"), "Plugin version:  $VERSION\n";
4246     if ($#report_storage >= 0) {
4247         print "-----------------------------------------------------------------------------\n";
4248         print "   Storage Components                                                        \n";
4249         print "=============================================================================\n";
4250         print "  STATE  |    ID    |  MESSAGE TEXT                                          \n";
4251         print "---------+----------+--------------------------------------------------------\n";
4252         foreach (@report_storage) {
4253             my ($msg, $level, $nexus) = @{$_};
4254             print q{ } x (8 - length $reverse_exitcode{$level}) . "$reverse_exitcode{$level} | "
4255               . q{ } x (8 - length $nexus) . "$nexus | $msg\n";
4256             $nagios_alert_count{$reverse_exitcode{$level}}++;
4257         }
4258     }
4259     if ($#report_chassis >= 0) {
4260         print "-----------------------------------------------------------------------------\n";
4261         print "   Chassis Components                                                        \n";
4262         print "=============================================================================\n";
4263         print "  STATE  |  ID  |  MESSAGE TEXT                                              \n";
4264         print "---------+------+------------------------------------------------------------\n";
4265         foreach (@report_chassis) {
4266             my ($msg, $level, $nexus) = @{$_};
4267             print q{ } x (8 - length $reverse_exitcode{$level}) . "$reverse_exitcode{$level} | "
4268               . q{ } x (4 - length $nexus) . "$nexus | $msg\n";
4269             $nagios_alert_count{$reverse_exitcode{$level}}++;
4270         }
4271     }
4272     if ($#report_other >= 0) {
4273         print "-----------------------------------------------------------------------------\n";
4274         print "   Other messages                                                            \n";
4275         print "=============================================================================\n";
4276         print "  STATE  |  MESSAGE TEXT                                                     \n";
4277         print "---------+-------------------------------------------------------------------\n";
4278         foreach (@report_other) {
4279             my ($msg, $level, $nexus) = @{$_};
4280             print q{ } x (8 - length $reverse_exitcode{$level}) . "$reverse_exitcode{$level} | $msg\n";
4281             $nagios_alert_count{$reverse_exitcode{$level}}++;
4282         }
4283     }
4284 }
4285 else {
4286     my $c = 0;  # counter to determine linebreaks
4287
4288     # Run through each message, sorted by severity level
4289   ALERT:
4290     foreach (sort {$a->[1] < $b->[1]} (@report_storage, @report_chassis, @report_other)) {
4291         my ($msg, $level, $nexus) = @{ $_ };
4292         next ALERT if $level == $E_OK;
4293
4294         if (defined $opt{only}) {
4295             # If user wants only critical alerts
4296             next ALERT if ($opt{only} eq 'critical' and $level == $E_WARNING);
4297
4298             # If user wants only warning alerts
4299             next ALERT if ($opt{only} eq 'warning' and $level == $E_CRITICAL);
4300         }
4301
4302         # Prefix with service tag if specified with option '-i|--info'
4303         if ($opt{info}) {
4304             if (defined $opt{htmlinfo}) {
4305                 $msg = '[<a href="' . warranty_url($sysinfo{serial})
4306                   . "\">$sysinfo{serial}</a>] " . $msg;
4307             }
4308             else {
4309                 $msg = "[$sysinfo{serial}] " . $msg;
4310             }
4311         }
4312
4313         # Prefix with nagios level if specified with option '--state'
4314         $msg = $reverse_exitcode{$level} . ": $msg" if $opt{state};
4315
4316         # Prefix with one-letter nagios level if specified with option '--short-state'
4317         $msg = (substr $reverse_exitcode{$level}, 0, 1) . ": $msg" if $opt{shortstate};
4318
4319         ($c++ == 0) ? print $msg : print $linebreak, $msg;
4320
4321         $nagios_alert_count{$reverse_exitcode{$level}}++;
4322     }
4323 }
4324
4325 # Determine our exit code
4326 $exit_code = $E_OK;
4327 $exit_code = $E_UNKNOWN  if $nagios_alert_count{'UNKNOWN'} > 0;
4328 $exit_code = $E_WARNING  if $nagios_alert_count{'WARNING'} > 0;
4329 $exit_code = $E_CRITICAL if $nagios_alert_count{'CRITICAL'} > 0;
4330
4331 # Global status via SNMP.. extra safety check
4332 if ($globalstatus != $E_OK && $exit_code == $E_OK && !defined $opt{only}) {
4333     print "OOPS! Something is wrong with this server, but I don't know what. ";
4334     print "The global system health status is $reverse_exitcode{$globalstatus}, ";
4335     print "but every component check is OK. This may be a bug in the Nagios plugin, ";
4336     print "please file a bug report.\n";
4337     exit $E_UNKNOWN;
4338 }
4339
4340 # Print OK message
4341 if ($exit_code == $E_OK && defined $opt{only} && $opt{only} !~ m{\A critical|warning|chassis \z}xms && !$opt{debug}) {
4342     my %okmsg
4343       = ( 'storage'     => "STORAGE OK - $count{pdisk} physical drives, $count{vdisk} logical drives",
4344           'fans'        => $count{fan} == 0 && $blade ? 'OK - blade system with no fan probes' : "FANS OK - $count{fan} fan probes checked",
4345           'temp'        => "TEMPERATURES OK - $count{temp} temperature probes checked",
4346           'memory'      => "MEMORY OK - $count{dimm} memory modules checked",
4347           'power'       => $count{power} == 0 ? 'OK - no instrumented power supplies found' : "POWER OK - $count{power} power supplies checked",
4348           'cpu'         => "PROCESSORS OK - $count{cpu} processors checked",
4349           'voltage'     => "VOLTAGE OK - $count{volt} voltage probes checked",
4350           'batteries'   => $count{bat} == 0 ? 'OK - no batteries found' : "BATTERIES OK - $count{bat} batteries checked",
4351           'amperage'    => $count{amp} == 0 ? 'OK - no power monitoring probes found' : "AMPERAGE OK - $count{amp} amperage (power monitoring) probes checked",
4352           'intrusion'   => $count{intr} == 0 ? 'OK - no intrusion detection probes found' : "INTRUSION OK - $count{intr} intrusion detection probes checked",
4353           '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",
4354           'esmlog'      => "OK - ESM Log content: $count{esm}{Ok} ok, $count{esm}{'Non-Critical'} warning and $count{esm}{Critical} critical",
4355           'esmhealth'   => "ESM LOG OK - less than 80% used",
4356         );
4357
4358     print $okmsg{$opt{only}};
4359 }
4360 elsif ($exit_code == $E_OK && !$opt{debug}) {
4361     if (defined $opt{htmlinfo}) {
4362         printf q{OK - System: '<a href="%s">%s</a>', SN: '<a href="%s">%s</a>', hardware working fine},
4363           documentation_url($sysinfo{model}), $sysinfo{model},
4364             warranty_url($sysinfo{serial}), $sysinfo{serial};
4365     }
4366     else {
4367         printf q{OK - System: '%s', SN: '%s', hardware working fine},
4368           $sysinfo{model}, $sysinfo{serial};
4369     }
4370
4371     if ($check{storage}) {
4372         printf ', %d logical drives, %d physical drives',
4373           $count{vdisk}, $count{pdisk};
4374     }
4375     else {
4376         print ', not checking storage';
4377     }
4378
4379     if ($opt{okinfo} >= 1) {
4380         print $linebreak;
4381         printf q{----- BIOS='%s %s'}, $sysinfo{bios}, $sysinfo{biosdate};
4382
4383         if ($sysinfo{rac}) {
4384             printf q{, %s='%s'}, $sysinfo{rac_name}, $sysinfo{rac_fw};
4385         }
4386         if ($sysinfo{bmc}) {
4387             printf q{, BMC='%s'}, $sysinfo{bmc_fw};
4388         }
4389     }
4390
4391     if ($opt{okinfo} >= 2) {
4392         if ($check{storage}) {
4393             my @storageprint = ();
4394             foreach my $id (sort keys %{ $sysinfo{controller} }) {
4395                 chomp $sysinfo{controller}{$id}{driver};
4396                 my $msg = sprintf q{----- Ctrl %s [%s]: Fw='%s', Dr='%s'},
4397                   $sysinfo{controller}{$id}{id}, $sysinfo{controller}{$id}{name},
4398                     $sysinfo{controller}{$id}{firmware}, $sysinfo{controller}{$id}{driver};
4399                 if (defined $sysinfo{controller}{$id}{storport}) {
4400                     $msg .= sprintf q{, Storport: '%s'}, $sysinfo{controller}{$id}{storport};
4401                 }
4402                 push @storageprint, $msg;
4403             }
4404             foreach my $id (sort keys %{ $sysinfo{enclosure} }) {
4405                 push @storageprint, sprintf q{----- Encl %s [%s]: Fw='%s'},
4406                   $sysinfo{enclosure}{$id}->{id}, $sysinfo{enclosure}{$id}->{name},
4407                     $sysinfo{enclosure}{$id}->{firmware};
4408             }
4409
4410             # print stuff
4411             foreach my $line (@storageprint) {
4412                 print $linebreak, $line;
4413             }
4414         }
4415     }
4416
4417     if ($opt{okinfo} >= 3) {
4418         print "$linebreak----- OpenManage Server Administrator (OMSA) version: '$sysinfo{om}'";
4419     }
4420
4421 }
4422 else {
4423     if ($opt{extinfo}) {
4424         print $linebreak;
4425         if (defined $opt{htmlinfo}) {
4426             printf '------ SYSTEM: <a href="%s">%s</a>, SN: <a href="%s">%s</a>',
4427               documentation_url($sysinfo{model}), $sysinfo{model},
4428                 warranty_url($sysinfo{serial}), $sysinfo{serial};
4429         }
4430         else {
4431             printf '------ SYSTEM: %s, SN: %s',
4432               $sysinfo{model}, $sysinfo{serial};
4433         }
4434     }
4435     if (defined $opt{postmsg}) {
4436         my $post = undef;
4437         if (-f $opt{postmsg}) {
4438             open my $POST, '<', $opt{postmsg}
4439               or ( print $linebreak
4440                    and print "ERROR: Couldn't open post message file $opt{postmsg}: $!\n"
4441                    and exit $E_UNKNOWN );
4442             $post = <$POST>;
4443             close $POST;
4444             chomp $post;
4445         }
4446         else {
4447             $post = $opt{postmsg};
4448         }
4449         if (defined $post) {
4450             print $linebreak;
4451             $post =~ s{[%]s}{$sysinfo{serial}}gxms;
4452             $post =~ s{[%]m}{$sysinfo{model}}gxms;
4453             $post =~ s{[%]b}{$sysinfo{bios}}gxms;
4454             $post =~ s{[%]d}{$sysinfo{biosdate}}gxms;
4455             $post =~ s{[%]o}{$sysinfo{osname}}gxms;
4456             $post =~ s{[%]r}{$sysinfo{osver}}gxms;
4457             $post =~ s{[%]p}{$count{pdisk}}gxms;
4458             $post =~ s{[%]l}{$count{vdisk}}gxms;
4459             $post =~ s{[%]n}{$linebreak}gxms;
4460             $post =~ s{[%]{2}}{%}gxms;
4461             print $post;
4462         }
4463     }
4464 }
4465
4466 # Reset the WARN signal
4467 $SIG{__WARN__} = 'DEFAULT';
4468
4469 # Print any perl warnings that have occured
4470 if (@perl_warnings) {
4471     foreach (@perl_warnings) {
4472         chop @$_;
4473         print "${linebreak}INTERNAL ERROR: @$_";
4474     }
4475     $exit_code = $E_UNKNOWN;
4476 }
4477
4478 # Print performance data
4479 if (defined $opt{perfdata} && !$opt{debug} && @perfdata) {
4480     my $lb = $opt{perfdata} eq 'multiline' ? "\n" : q{ };  # line break for perfdata
4481     print q{|};
4482
4483     # Sort routine for performance data
4484     sub perfsort {
4485         my %order = ( fan => 0, pwr => 1, tem => 2, enc => 3, );
4486         return ($order{(substr $a->{label}, 0, 3)} cmp $order{(substr $b->{label}, 0, 3)}) ||
4487           $a->{label} cmp $b->{label};
4488     }
4489
4490     # Print performance data sorted
4491     my $type = $opt{perfdata} eq 'minimal' ? 'mini' : 'label';
4492     print join $lb, map { "$_->{$type}=$_->{value}$_->{unit};$_->{warn};$_->{crit}" } sort perfsort @perfdata;
4493 }
4494
4495 # Print a linebreak at the end
4496 print "\n" if !$opt{debug};
4497
4498 # Exit with proper exit code
4499 exit $exit_code;