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