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