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