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