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