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