Debian Codegraph @

check_smart_attributes

raw
1 #!/usr/bin/perl -w
2
3 use strict;
4 use warnings;
5 use Getopt::Long qw(:config no_ignore_case);
6 use JSON;
7 use Storable qw(dclone);
8
9 our $VERSION = "1.6";
10 our $VERBOSITY = 0;
11
12 use constant {
13 STATE_OK => 0,
14 STATE_WARNING => 1,
15 STATE_CRITICAL => 2,
16 STATE_UNKNOWN => 3,
17 };
18
19 our @hdrmap_a = ('ID#','ATTRIBUTE_NAME','FLAG','VALUE','WORST','THRESH',
20 'TYPE','UPDATED','WHEN_FAILED','RAW_VALUE');
21
22 our %hdrmap_nvme = (
23 'Critical Warning' => 0,
24 'Temperature' => 1,
25 'Available Spare' => 2,
26 'Available Spare Threshold' => 3,
27 'Percentage Used' => 4,
28 'Data Units Read' => 5,
29 'Data Units Written' => 6,
30 'Host Read Commands' => 7,
31 'Host Write Commands' => 8,
32 'Controller Busy Time' => 9,
33 'Power Cycles' => 10,
34 'Power On Hours' => 11,
35 'Unsafe Shutdowns' => 12,
36 'Media and Data Integrity Errors' => 13,
37 'Error Information Log Entries' => 14,
38 'Warning Comp. Temperature Time' => 15,
39 'Critical Comp. Temperature Time' => 16
40 );
41
42 our %hdrmap_sas = (
43 'Elements in grown defect list' => 0,
44 'read' => [
45 'Read errors corrected by ECC (fast)',
46 'Read errors corrected by ECC (delayed)',
47 'Read errors corrected by ECC (reread)',
48 'Total read errors corrected',
49 'Total read correction algorithm invocations',
50 'Total read gigabytes processed',
51 'Total uncorrected read errors'
52 ],
53 'write' => [
54 'Write errors corrected by ECC (fast)',
55 'Write errors corrected by ECC (delayed)',
56 'Write errors corrected by ECC (rewrite)',
57 'Total write errors corrected',
58 'Total write correction algorithm invocations',
59 'Total write gigabytes processed',
60 'Total uncorrected write errors'
61 ]
62 );
63
64 sub getVersionString{
65 return "check_smart_values version $VERSION 20190208
66 Copyright (C) 2019 Thomas-Krenn.AG (written by Georg Schönberger)
67 Current updates available via git repository https://github.com/thomas-krenn/\n";
68 }
69
70 sub getUsageString{
71 return "Usage:
72 sudo check_smart_values -dbj <smartdb json file> -d <device path> [-d <device path>]
73 [-r <regex pattern to find devices>] [-ucfgj <user config json file>]
74 [-p <path to smartctl>] [-nosudo] [-cu] [-ap] [-s]
75 [-O <extra options>][ -v|-vv|-vvv] [-h] [-V]\n";
76 }
77
78 sub getHelpString{
79 return "
80 [-p|--path <path to smartctl]
81 Specify the path at which the smartctl binary can be found. Per
82 default /usr/sbin/smartctl is taken.
83 [-d|--device <path to device being checked>]
84 Specify the device being monitored. If a regex pattern should be
85 used to find devices don't use '-d' but '-r' with a given device
86 pattern (cf. '-r' help text below).
87 If multiple devices should be checked with '-d' use the option
88 multiple times:
89 -d /dev/sda -d /dev/sdb
90 For devices behind LSI RAID controllers the megaraid number must be
91 used.
92 There are different ways to specify the device, the correct one must be
93 tested with the corresponding RAID controller in use, e.g.:
94 -d megaraid6,/dev/sda
95 -d megaraid6,/dev/sda -O 'sat+'
96 Use storcli to find out the corresponding device numbers.
97 For devices behind Adaptec RAID controllers on Linux specify
98 '/dev/sg<X>' where <X> is the number for your device. Use e.g. sg_scan
99 to find the device.
100 You must also use '-O sat' or '-O scsi' according to the device
101 interface. This are extra options only necessary for '/dev/sg<X>'
102 devices.
103 As an alternative for Adaptec RAID controllers on Windows or Linux
104 you can specify 'aacraid,H,L,ID' where <H> is the Host number and <L>
105 is the LUN.
106 The <ID> can be found by executing 'arcconf getconfig <CONTROLLER-ID>'.
107 Sample output for <CONTROLLER-ID>=1:
108 '...Reported Channel,Device(T:L): 0,4(4:0)...'
109 Configuration would be '-d aacraid,0,0,4'
110 For devices behind hpsa/cciss based RAID controller, you'll mostly find in
111 HP Hardware, you can use 'cciss,<N>_/dev/sg<X>' for hpsa or
112 'cciss,<N>_/dev/cciss/c<X>d<N>' for cciss where <N> is the number
113 of the device and <X> the RAID controller. You'll find a sg<X>
114 for every Logical Drive.
115 For devices behind 3ware RAID controllers, the 3ware device ID must be
116 used with the corresponding tw device, e.g.:
117 -d 3ware,8,/dev/twa0
118 For devices behind Areca RAID controllers, the Areca device IDs must be
119 used with the corresponding areca device, e.g.:
120 -d areca1/1,/dev/sg0
121 For NVMe devices just use '/dev/nvme[a-z0-9]+'. As attributes with NVMe
122 are not model specific the generic NVMe entry in the smartdb JSON file
123 is used.
124 [-r|--regex]
125 If no devices are specified by '-d' use a regular expression to find
126 devices. The regular expression string is passed to the find command
127 which searches in '/dev' for the regex in combination with the find
128 types f (files), l (links) and b (block devices).
129 Note that find always returns the full path with '-regex' therefore
130 found matches always will start with '/dev' as this is the base search
131 path. The used regex type by find is 'egrep'.
132 Examples:
133 -r '.*sdc.*'
134 -r \'/dev/sd[c,d]\$\'
135 -r \'/dev/sd[a-z]\$\'
136 -r \'/dev/.*INTEL.*\'
137 [-dbj|--dbjson <path to smartdb JSON file>]
138 Specify the path at which the JSON smart db can be found. The JSON file
139 defines which parameter (VALUE or RAW_VALUE) must be taken for a
140 sensor. In order to interpret a sensor it is necessary to know which
141 value to take. As this mapping can be different for device models a
142 database is needed for a device.
143 Attributes for NVMe devives are not model specific, therefore only one
144 generic NMVe entry is present in the smart db. If the device is set up
145 as 'nvme[a-z0-9]+' then NVMe specific parsing of attributes
146 is done. The generic entry is necessary to enable default thresholds and
147 performance values for NVMe devices. Moreover now with the generic entry
148 users can still override the smart db entry with 'ucfgj'. This is way
149 better than having hardcoded parsing of NVMe attributes in the plugin.
150 [-ucfgj|--ucfgjson <path to user config JSON file>]
151 Specify the path at which the JSON user config file can be found.
152 The user config can be used to override thresholds and performance values
153 in the base config. This can be useful if the thresholds for a specific
154 device must be changed (e.g. showing up a non-critical error). If a value
155 is defined in the user config it overrides its corresponding value in
156 the base config. The override is only taken for the specific value, for
157 the other ones the base config is still valid.
158 Attention: If megaraid devices are used, the path must be set as
159 '/dev/megaraidID'. This is necessary for the internal naming convention
160 the plugin uses.
161 Attention: If 3ware devices are used, the path must be set as
162 '/dev/3wareID'. This is necessary for the internal naming convention
163 the plugin uses.
164 Attention: If Areca devices are used, the path must be set as
165 '/dev/areca_ID_ID'. this is necessary for the internal naming convention
166 the plugin uses.
167 [-cu|--critical_on_unknown]
168 Show critical if the device was not found in database.
169 [-nosudo]
170 Disable the usage of sudo for smartctl. This is handy if a system is
171 used where sudo is not available.
172 [-ap|--allperfs]
173 Get performance data for all monitor-able smart attributes and don't
174 limit performance data to the 'Perfs' section in the smartdb.json.
175 [-s|--ssdonly]
176 Check SSDs only, even if more devices are given. Checks if the smartctl
177 output contains 'Solid State Device' in the method 'checkWhichDevice'.
178 If yes, the device is skipped even if it is found in the smartdb.json.
179 [-O|--options <extra options>]
180 Currently the extra options 'sat' or 'scsi' are possible for Adaptec
181 controllers. For megaraid devices 'sat+' is allowed.
182 The options are only used if a device of type sg<X> or
183 megaraid<X>,/dev/sdX is given.
184 [-v|-vv|-vvv]
185 be verbose
186 (no -v) .. single line output
187 -v ....... single line output with additional details for warnings
188 -vv ...... multi line output, also with additional details for warnings
189 -vvv ..... normal output, then debugging output
190 [-h|--help]
191 show this help
192 [-V|--version]
193 show version information\n";
194 }
195
196 sub readUCfgJSON{
197 my $uCfgJSON = shift;
198 my $file_content = do { open my $fh, '<', $uCfgJSON; local $/; <$fh> };
199 return(decode_json($file_content));
200 }
201
202 sub readDbJSON{
203 my $dbJSON = shift;
204 my $file_content = do { open my $fh, '<', $dbJSON; local $/; <$fh> };
205 return(decode_json($file_content));
206 }
207
208 sub parseMegaraidRegex{
209 my $devicepattern = shift;
210 my @megadevs;
211 if($devicepattern =~ /^megaraid\[([0-9]+)\-([0-9]+)\],(\/dev\/[a-zA-Z]+)$/){
212 for(my $id = $1; $id <= $2; $id++) {
213 my $megadev = "megaraid" . $id . "," . $3;
214 push @megadevs, $megadev;
215 }
216 }
217 return @megadevs;
218 }
219
220 sub genAttributeName{
221 my $device = shift;
222 my $attributeName= shift;
223
224 # Parse device for prepending attribute name with device
225 my $currDevice;
226 if($device =~ m/(nvme[a-z0-9])+$/){
227 $currDevice = $1;
228 }
229 elsif($device =~ m/^\/dev\/(?:disk\/by-(?:id|label)\/)?([A-Za-z0-9_\-,\.\:]+)$/){
230 $currDevice = $1;
231 }
232 $attributeName = $currDevice.'_'.$attributeName;
233 # Replace characters not valid in sensor names
234 $attributeName =~ s/\s/_/g;
235 $attributeName =~ s/[\(\)]//g;
236 return $attributeName;
237 }
238
239 sub findDevicesByRegex{
240 my $devicepattern = shift;
241 my @founddevices;
242 if($devicepattern =~ /^megaraid\[([0-9]+)\-([0-9]+)\],(\/dev\/[a-zA-Z]+)$/){
243 @founddevices = parseMegaraidRegex($devicepattern);
244 }
245 else{
246 my $findcmd;
247 chomp($findcmd = `which find`);
248 if(! -x $findcmd){
249 print "Error: cannot find find executable.\n";
250 exit(STATE_UNKNOWN);
251 }
252 # Since older versions of find don't support multiple types, loop over each type separately
253 my @findtypes_a = ('f','b','l','c');
254 foreach my $type (@findtypes_a){
255 my @founddevices_tmp;
256 @founddevices_tmp = `$findcmd /dev -regextype egrep -regex $devicepattern -type $type`;
257 if(($? >> 8) != 0){
258 print "Error: find command with regex returned an error.\n";
259 print "The used command was:\n";
260 print "$findcmd /dev -regextype egrep -regex $devicepattern -type $type\n";
261 exit(STATE_UNKNOWN);
262 }
263 else{
264 push @founddevices, @founddevices_tmp;
265 }
266 }
267 }
268 chomp(@founddevices);
269 my @devices_without_parts;
270 foreach my $device (@founddevices){
271 if($device =~ /\-part[0-9]+$/){
272 next;
273 }
274 else{
275 push @devices_without_parts, $device;
276 }
277 }
278 return @devices_without_parts;
279 }
280
281 sub getSmartctl{
282 my $smartctl = shift;
283 my @devicesToCheck_a = @{(shift)};
284 my $extraOpts = shift;
285 #a hash of all devices with their corresponding output
286 my %output_h;
287 my %command_h;
288
289 foreach my $device (@devicesToCheck_a){
290 my @output;
291 my $usedCommand;
292 # Check if a /dev/disk/by-* device is used
293 if($device =~ /^\/dev\/disk\/by\-[a-zA-Z]+\/(.*)$/){
294 # smartctl can directly read this device links
295 $usedCommand = $smartctl.' -a '.$device;
296 if(defined($extraOpts)){
297 $usedCommand .= ' -d '.$extraOpts;
298 }
299 @output = `$usedCommand`;
300 }
301 # Check if a megaraid device is used
302 elsif($device =~ /^(megaraid[0-9]+),(\/dev\/[a-zA-Z]+)$/){
303 my $megaDevice = $1;
304 my $devicePath = $2;
305 # Insert a ',' after 'megaraid'
306 substr($megaDevice,8,0,',');
307 my $megaDeviceOptions = $megaDevice;
308 # Device path and megaraid device are used together to
309 # check the attributes with smartctl
310 if(defined($extraOpts)){
311 if($extraOpts ne 'sat+'){
312 print "Error: please use 'sat+' as extra options for megaraid devices!\n";
313 print getUsageString();
314 exit(STATE_UNKNOWN);
315 }
316 $megaDeviceOptions = $extraOpts.$megaDevice
317 }
318 $usedCommand = $smartctl.' -a -d '.$megaDeviceOptions.' '.$devicePath;
319 @output = `$usedCommand`;
320 # From now on we use only e.g. megaraid6 as device
321 $megaDevice =~ s/,//;
322 $device = '/dev/'.$megaDevice;
323 }
324 # Check if an Adaptec sg device is used
325 elsif($device =~ /^\/dev\/sg[0-9]+/ && defined($extraOpts)){
326 if($extraOpts ne 'sat' && $extraOpts ne 'scsi'){
327 print "Error: please use 'sat' or 'scsi' as options for Adaptec sg devices!\n";
328 print getUsageString();
329 exit(STATE_UNKNOWN);
330 }
331 # Call smartctl with extra options for Adaptec sg device
332 $usedCommand = $smartctl.' -a -d '.$extraOpts.' '.$device;
333 @output = `$usedCommand`;
334 }
335 # Check if Adaptec aacraid format is used
336 elsif($device =~ /^(aacraid),([0-9]+),([0-9]+),([0-9]+),(\/dev\/[a-zA-Z]+)$/){
337 my $aacDevice = $1 . "," . $2 . "," . $3 . "," .$4;
338 my $devicePath = $5;
339 $usedCommand = $smartctl.' -a -d '.$aacDevice.' '.$devicePath;
340 @output = `$usedCommand`;
341 # From now on we use only e.g. aacraid_0_0_4 as device
342 $aacDevice =~ s/,/_/g;
343 $device = '/dev/'.$aacDevice;
344 }
345 # Check if a cciss device is used
346 elsif($device =~ /^(cciss,[0-9]+)[\s_]+(\/dev\/cciss\/c[0-9]+d[0-9]+|\/dev\/sg[0-9]+)$/){
347 my $ccissDevice = $1;
348 my $devicePath = $2;
349 my @controller = split(/\//,$devicePath);
350 $usedCommand = $smartctl.' -a -d '.$ccissDevice.' '.$devicePath;
351 @output = `$usedCommand`;
352 $ccissDevice =~ s/,/_/g;
353 $device = '/dev/'.$ccissDevice."_".$controller[-1];
354 }
355 # Check if 3ware format is used
356 elsif($device =~ /^(3ware,[0-9]+),(\/dev\/tw[a-z0-9]+)$/){
357 my $twDevice = $1;
358 my $devicePath = $2;
359 $usedCommand = $smartctl.' -a -d '.$twDevice.' '.$devicePath;
360 @output = `$usedCommand`;
361 # From now on we use only e.g. 3ware8 as device
362 $twDevice =~ s/,//;
363 $device = '/dev/'.$twDevice;
364 }
365 # Check if Areca format is used
366 elsif($device =~ /^(areca),([0-9]+)\/([0-9]+),(\/dev\/sg[0-9]+)$/){
367 my $arecaDevice = $1 . "," . $2 . "/" . $3;
368 my $devicePath = $4;
369 $usedCommand = $smartctl.' -a -d '.$arecaDevice.' '.$devicePath;
370 @output = `$usedCommand`;
371 # From now on we use only e.g. areca_1_1 as device
372 $arecaDevice =~ s/,/_/g;
373 $arecaDevice =~ s/\//_/g;
374 $device = '/dev/'.$arecaDevice;
375 }
376 else{
377 # If the device is a symlink, simply follow it
378 if(-l $device){
379 use Cwd qw(abs_path);
380 $device = abs_path(readlink $device);
381 }
382 $usedCommand = $smartctl.' -a '.$device;
383 @output = `$usedCommand`;
384 }
385 if(($? >> 8) & 2){
386 print "Error: smartctl returned \"No such device\" for device $device.\n";
387 exit(STATE_UNKNOWN);
388 }
389 $output_h{$device} = \@output;
390 $command_h{$device} = $usedCommand;
391 }
392 return (\%output_h, \%command_h);
393 }
394
395 sub checkWhichDevice{
396 my $dbConfig = shift;
397 my $uCfgJSON = shift;
398 my $ssdonly = shift;
399 my %smartctlOut_h = %{(shift)};;
400 # Array of found device hashes
401 my @devices_a;
402 my @devices_missing_a;
403
404 # Fetch the device JSON hash
405 my $devices_h = $dbConfig->{'Devices'};
406
407 # If given, fetch the user config for the devices
408 my $uCfgDevices_h;
409 if(defined($uCfgJSON)){
410 $uCfgDevices_h = $uCfgJSON->{'Devices'};
411 }
412
413 # Check each device whose smartvalues are present
414 foreach my $device (keys %smartctlOut_h){
415 my @smartctlOut = @{$smartctlOut_h{$device}};
416 if(defined($ssdonly)){
417 if($ssdonly & !grep { /Solid State Device/i } @smartctlOut){ next }
418 }
419 my @model = grep { /Model Family/i || /Device Model/i || /^Product:/i } @smartctlOut;
420 my @transport = grep { /^Transport protocol:/i } @smartctlOut;
421 # NVMe devices don't require a database entry, use the generic NVMe one
422 if (($device =~ /nvme[a-z0-9]+$/) || ($device =~ /\/dev\/disk\/by-id\/nvme-[A-Za-z0-9_\-,\.\:]+$/)) {
423 @model = ('Generic NVMe');
424 }
425 # SAS devices don't require a database entry, use the generic SAS one
426 elsif (@transport && $transport[0] =~ /SAS/) {
427 @model = ('Generic SAS');
428 }
429 my $found = 0;# We have not found the device yet
430 foreach my $currModel (@model){
431 # Check all models in the db
432 foreach my $key (keys %$devices_h){
433 # Search for the model in the smart DB
434 foreach (@{$devices_h->{$key}->{'Device'}}){
435 # If the model matches we have found the correct db entry
436 if($currModel =~ /$_$/){
437 $found=1;
438 }
439 # For NVMe we don't have a specific model, but we use the smartdb's generic NVMe entry
440 if(($currModel =~ /NVMe/) && ($currModel =~ /$_/)){
441 $found=1;
442 }
443 if(($currModel =~ /Generic SAS/) && ($currModel =~ /$_/)){
444 $found =1;
445 }
446 if($found == 1){
447 my %foundDevice_h;
448 # Clone the values from the JSON smart db, ensure to not work
449 # with the same reference every time
450 $foundDevice_h{'Path'} = $device;
451 $foundDevice_h{'Device'} = dclone $devices_h->{$key}->{'Device'};
452 $foundDevice_h{'ID#'} = dclone $devices_h->{$key}->{'ID#'};
453 $foundDevice_h{'Threshs'} = dclone $devices_h->{$key}->{'Threshs'};
454 $foundDevice_h{'Perfs'} = dclone $devices_h->{$key}->{'Perfs'};
455 # Tresholds and perf variables are defined in the user cfg
456 if(defined($uCfgDevices_h->{$device})){
457 if(defined($uCfgDevices_h->{$device}->{'Threshs'})){
458 # A defined user config sensor overwrites the values from the json db
459 my %threshs_h = %{$uCfgDevices_h->{$device}->{'Threshs'}};
460 foreach my $ID (keys %threshs_h){
461 $foundDevice_h{'Threshs'}->{$ID} = $threshs_h{$ID};
462 }
463 }
464 # A defined Perfs array overwrites the json db one
465 if(defined($uCfgDevices_h->{$device}->{'Perfs'})){
466 $foundDevice_h{'Perfs'} = $uCfgDevices_h->{$device}->{'Perfs'};
467 }
468 }
469 push @devices_a, \%foundDevice_h;
470 last;
471 }
472 }
473 # Finish searching for the model in the smart DB
474 if($found){last;}
475 }
476 # Finish the current device models, one model already matched
477 if($found){last;}
478 }
479 # The device was not found in the smartdb
480 if(!$found){
481 push @devices_missing_a, $device;
482 }
483 }
484 return (\@devices_a, \@devices_missing_a);
485 }
486
487 sub parseSmartctlOut{
488 my %smartctlOut_h = %{(shift)};
489 # A hash with the parsed smart values for all devices
490 my %smartValues_h;
491
492 foreach my $device (keys %smartctlOut_h){
493 my @smartctlOut = @{$smartctlOut_h{$device}};
494 # Check for smart value lines
495 my @smartValues;
496 my @splittedLine;
497 my @transport = grep { /^Transport protocol:/i } @smartctlOut;
498 foreach my $line (@smartctlOut) {
499 if($line =~ /\d+\s+[A-Za-z0-9_\/]+\s+0[xX][0-9a-fA-F]+\s+\d+\s+\d+\s+[0-9\-]+\s+\w+/){
500 $line =~ s/^\s+|\s+$//g;
501 # Split the found line, and map its elements
502 # The header map defines the keys for the hash
503 @splittedLine = map { s/^\s*//; s/\s*$//; $_; } split(/\s+/,$line);
504 my %lineValues_h;
505 for(my $i = 0; $i < @hdrmap_a; $i++){
506 # Prepend the attribute name with the device name
507 if($hdrmap_a[$i] eq 'ATTRIBUTE_NAME'){
508 $lineValues_h{$hdrmap_a[$i]} = genAttributeName($device, $splittedLine[$i]);
509 }
510 else{
511 $lineValues_h{$hdrmap_a[$i]} = $splittedLine[$i];
512 }
513 }
514 push @smartValues, \%lineValues_h;
515 }
516 # Parse smart value lines for NVMe output
517 elsif((($device =~ /nvme[a-z0-9]+$/) || ($device =~ /\/dev\/disk\/by-id\/nvme-[A-Za-z0-9_\-,\.\:]+$/)) && $line =~ /([A-Za-z\s]+)\:\s+(.+)$/){
518 if(exists $hdrmap_nvme{$1}){
519 my %lineValues_h;
520 $lineValues_h{'ATTRIBUTE_NAME'} = $1;
521 $lineValues_h{'ID#'} = $hdrmap_nvme{$1};
522 $lineValues_h{'RAW_VALUE'} = $2;
523 # Remove whitespace , . in units read/written and any percentage and celsius suffix
524 $lineValues_h{'RAW_VALUE'} =~ s/[\s\%\,\.]|Celsius//g;
525 # NVMe's Critical Warning Attribute is hex, convert it to decimal
526 if($lineValues_h{'ATTRIBUTE_NAME'} eq "Critical Warning"){
527 $lineValues_h{'RAW_VALUE'} = hex($2);
528 }
529 # Data units are presented as 1000 512bytes, convert it
530 if($lineValues_h{'ATTRIBUTE_NAME'} eq "Data Units Read" ||
531 $lineValues_h{'ATTRIBUTE_NAME'} eq "Data Units Written"){
532 $lineValues_h{'RAW_VALUE'} =~ m/^(\d+)\[?/;
533 $lineValues_h{'RAW_VALUE'} = ($1*512000)/(1000**3);
534 }
535 $lineValues_h{'ATTRIBUTE_NAME'} = genAttributeName($device, $lineValues_h{'ATTRIBUTE_NAME'});
536 push @smartValues, \%lineValues_h;
537 }
538 }
539 elsif(@transport && $transport[0] =~ /SAS/ && $line =~ /([A-Za-z\s]+)\:\s+(.+)$/) {
540 if(exists $hdrmap_sas{$1}){
541 my $idoffset = 1;
542 if (ref $hdrmap_sas{$1} eq 'ARRAY') {
543 my $op = $1;
544 my $values = $2;
545 my $n = 0;
546 while ($values =~ /([\d,\.]+)/g) {
547 my %lineValues_h;
548 $lineValues_h{'ATTRIBUTE_NAME'} = $hdrmap_sas{$op}->[$n];
549 $lineValues_h{'ID#'} = $n + $idoffset;
550 $lineValues_h{'RAW_VALUE'} = $1;
551 $lineValues_h{'ATTRIBUTE_NAME'} = genAttributeName($device, $lineValues_h{'ATTRIBUTE_NAME'});
552 push @smartValues, \%lineValues_h;
553 $n++;
554 }
555 $idoffset += 7;
556 }
557 else {
558 my %lineValues_h;
559 $lineValues_h{'ATTRIBUTE_NAME'} = $1;
560 $lineValues_h{'ID#'} = $hdrmap_sas{$1};
561 $lineValues_h{'RAW_VALUE'} = $2;
562 $lineValues_h{'ATTRIBUTE_NAME'} = genAttributeName($device, $lineValues_h{'ATTRIBUTE_NAME'});
563 push @smartValues, \%lineValues_h;
564 }
565 }
566 }
567 if($line =~ /(ATA Error Count)\:\s+(\d+)/){
568 my %lineValues_h;
569 $lineValues_h{'ATTRIBUTE_NAME'} = $1;
570 $lineValues_h{'VALUE'} = $2;
571 $lineValues_h{'ID#'} = 1024;
572 $lineValues_h{'ATTRIBUTE_NAME'} = genAttributeName($device, $lineValues_h{'ATTRIBUTE_NAME'});
573 push @smartValues, \%lineValues_h;
574 }
575 if($line =~ /(SMART overall-health self-assessment test result)\:\s(\w+)/){
576 my %lineValues_h;
577 $lineValues_h{'ATTRIBUTE_NAME'} = 'Overall_Health_Test_Result';
578 $lineValues_h{'ID#'} = 1025;
579 if($2 eq 'PASSED'){
580 $lineValues_h{'VALUE'} = 0;
581 }
582 else{
583 $lineValues_h{'VALUE'} = 1;
584 }
585 $lineValues_h{'ATTRIBUTE_NAME'} = genAttributeName($device, $lineValues_h{'ATTRIBUTE_NAME'});
586 push @smartValues, \%lineValues_h;
587 }
588 }
589 $smartValues_h{$device} = \@smartValues;
590 }
591 return \%smartValues_h;
592 }
593
594 sub checkThreshs{
595 my $value = shift;
596 my $pattern = shift;
597
598 if($pattern =~ /(^[0-9]*$)/){
599 if($value < 0 || $value > $1){
600 return 0;
601 }
602 }
603 if($pattern =~ /(^[0-9]*)\:$/){
604 if($value < $1){
605 return 0;
606 }
607 }
608 if($pattern =~ /^\~\:([0-9]*)$/){
609 if($value > $1){
610 return 0;
611 }
612 }
613 return 1;
614 }
615
616 sub checkSmartctl{
617 my %smartValues_h = %{(shift)};
618 my @devices_a = @{(shift)};
619 # Resulting status level variables
620 my @warnings_a;
621 my @criticals_a;
622 my @statusLevel_a = ("OK");
623
624 foreach my $device (@devices_a){
625 # Fetch the configured variables for a device
626 my %IDs_h = %{$device->{'ID#'}};
627 my %threshs_h = %{$device->{'Threshs'}};
628 my @smartValues_a = @{$smartValues_h{$device->{'Path'}}};
629 # Check the corresponding smart values
630 foreach my $row (@smartValues_a){
631 my $ID = $row->{'ID#'};
632 if(exists $IDs_h{$ID}{'value'} && exists $threshs_h{$ID}){
633 if(defined($threshs_h{$ID}->[2])){
634 # Check if a bit pattern exits, then shift it
635 $threshs_h{$ID}->[2] =~ /^([l,r])([0-9]+)$/;
636 my $shift_dir = $1;
637 my $shift_ct = $2;
638 if($shift_dir eq 'l'){
639 $row->{$IDs_h{$ID}{'value'}} = $row->{$IDs_h{$ID}{'value'}} << $2;
640 }
641 if($shift_dir eq 'r'){
642 $row->{$IDs_h{$ID}{'value'}} = $row->{$IDs_h{$ID}{'value'}} >> $2;
643 }
644 }
645 if(!(checkThreshs($row->{$IDs_h{$ID}{'value'}},$threshs_h{$ID}->[0]))){
646 # Don't loose the critical state
647 $statusLevel_a[0] = 'Warning' unless $statusLevel_a[0] eq 'Critical';
648 push @warnings_a, $row->{'ATTRIBUTE_NAME'};
649 }
650 if(!(checkThreshs($row->{$IDs_h{$ID}{'value'}},$threshs_h{$ID}->[1]))){
651 $statusLevel_a[0] = 'Critical';
652 pop @warnings_a;
653 push @criticals_a, $row->{'ATTRIBUTE_NAME'};
654 }
655 }
656 }
657 }
658
659 push @statusLevel_a, \@warnings_a;
660 push @statusLevel_a, \@criticals_a;
661 return \@statusLevel_a;
662 }
663
664 sub printMissingDevicesDB{
665 my @devices_a = @{(shift)};
666 my $missingDevs_str;
667 my $found;
668 foreach my $device (@devices_a){
669 $missingDevs_str .= ', ' if defined($missingDevs_str);
670 $missingDevs_str .= $device;
671 }
672 return $missingDevs_str;
673 }
674
675
676 sub getStatusString{
677 my $level = shift;
678 my @statusLevel_a = @{(shift)};
679 my %smartValues_h = %{(shift)};
680 my @devices_a = @{(shift)};
681 # Sensors to check, warn or crit
682 my @sensors_a;
683 my $status_str = "";
684
685 if($level eq "Warning"){
686 @sensors_a = @{$statusLevel_a[1]};
687 }
688 if($level eq "Critical"){
689 @sensors_a = @{$statusLevel_a[2]};
690 }
691
692 if($level eq "Warning" || $level eq "Critical"){
693 if(@sensors_a){
694 # Print which sensors are Warn or Crit
695 foreach my $sensor (@sensors_a){
696 $status_str .= "[".$sensor." = ".$level;
697 if($VERBOSITY){
698 # Parse out the used device, use numbers for megaraid devs
699 $sensor =~ /^([a-zA-Z0-9]+)/;
700 my $devicePath = '/dev/'.$1;
701 my %IDs_h;
702 my @smartValues_a;
703 foreach my $device (@devices_a){
704 # Search for the device the sensor belongs to
705 if($devicePath eq $device->{'Path'}){
706 %IDs_h = %{$device->{'ID#'}};
707 @smartValues_a = @{$smartValues_h{$device->{'Path'}}};
708 }
709 }
710 # Append the value for the given sensor
711 foreach my $row (@smartValues_a){
712 if($row->{'ATTRIBUTE_NAME'} eq $sensor){
713 my $ID = $row->{'ID#'};
714 if(exists $IDs_h{$ID}{'value'}){
715 $status_str .= " (".$row->{$IDs_h{$ID}{'value'}}.")";
716 }
717 }
718 }
719 }
720 $status_str .= "]";
721 }
722 }
723 }
724 return $status_str;
725 }
726 sub getPerfString{
727 my %smartValues_h = %{(shift)};
728 my @devices_a = @{(shift)};
729 my $allPerfs = shift;
730 my $perf_str;
731
732 foreach my $device (@devices_a){
733 # Fetch the configured variables for a device
734 my %IDs_h = %{$device->{'ID#'}};
735 my %threshs_h = %{$device->{'Threshs'}};
736 my @smartValues_a = @{$smartValues_h{$device->{'Path'}}};
737 my @perfmap_a = ();
738 if(!defined($allPerfs)){
739 @perfmap_a = @{$device->{'Perfs'}};
740 }
741 else{
742 @perfmap_a = keys %IDs_h;
743 }
744
745 foreach my $perf (@perfmap_a){
746 # Search for the sensor and print its value
747 foreach my $row (@smartValues_a){
748 if($perf eq $row->{'ID#'}){
749 my $ID = $row->{'ID#'};
750 my $attr_str;
751 if(exists $IDs_h{$ID}{'value'}){
752 $attr_str = "'".$row->{'ATTRIBUTE_NAME'}."'=".$row->{$IDs_h{$ID}{'value'}};
753 if($perf_str){
754 $attr_str = " ".$attr_str;
755 }
756 }
757 $perf_str .= $attr_str;
758 # If available also print its thresholds
759 if(exists $IDs_h{$ID}{'value'} && exists $threshs_h{$ID}){
760 $threshs_h{$ID}->[0] =~ /(\d+)/;
761 $perf_str .= ';'.$1.';';
762 $threshs_h{$ID}->[1] =~ /(\d+)/;
763 $perf_str .= $1;
764 }
765 }
766 }
767 }
768 }
769 return $perf_str;
770 }
771
772 sub getVerboseString{
773 my %smartValues_h = %{(shift)};
774 my @devices_a = @{(shift)};
775 my %smartctlOut_h = %{(shift)};
776 my %command_h = %{(shift)};
777 my $verb_str;
778
779 foreach my $device (@devices_a){
780 # Fetch the configured variables for a device
781 my %IDs_h = %{$device->{'ID#'}};
782 my %threshs_h = %{$device->{'Threshs'}};
783 my @perfmap_a = @{$device->{'Perfs'}};
784 my @smartValues_a = @{$smartValues_h{$device->{'Path'}}};
785
786 foreach my $row (@smartValues_a){
787 my $ID = $row->{'ID#'};
788 if(exists $IDs_h{$ID}{'value'}){
789 $verb_str .= "\n".$row->{'ATTRIBUTE_NAME'}." = ".$row->{$IDs_h{$ID}{'value'}};
790 $verb_str .= " (".$IDs_h{$ID}{'value'}.")";
791 }
792 }
793 $verb_str .= "\n";
794 if($VERBOSITY == 3){
795 my @smartctlOut = @{$smartctlOut_h{$device->{'Path'}}};
796 $verb_str .= "\n========================================";
797 $verb_str .= "\nBegin of verbosity level 3 (-vvv) output for device: ".$device->{'Path'}."\n";
798 $verb_str .= "\n================= \n";
799 $verb_str .= "Used smartctl command:\n";
800 $verb_str .= $command_h{$device->{'Path'}};
801 $verb_str .= "\n================= \n";
802 $verb_str .= "Thresholds:\n";
803 foreach my $ID (keys %threshs_h){
804 if(defined($threshs_h{$ID}->[2])){
805 $verb_str .= $ID.": [".$threshs_h{$ID}->[0].",".$threshs_h{$ID}->[1].",".$threshs_h{$ID}->[2]."]\n";
806 }
807 else{
808 $verb_str .= $ID.": [".$threshs_h{$ID}->[0].",".$threshs_h{$ID}->[1]."]\n";
809 }
810 }
811 $verb_str .= "================= \n";
812 $verb_str .= "Performance Value IDs:\n";
813 $verb_str .= "[@perfmap_a]\n";
814 $verb_str .= "================= \n";
815 $verb_str .= "Begin of smartctl output:\n";
816 foreach my $line (@smartctlOut){
817 $verb_str .= $line;
818 }
819 $verb_str .= "\nEnd of verbosity level 3 (-vvv) output for device: ".$device->{'Path'}."\n";
820 $verb_str .= "======================================== \n";
821 }
822 }
823
824 return $verb_str;
825 }
826
827 MAIN: {
828 my ($smartctl, $dbJSON, $uCfgJSON, $exitCode, $noSudo, $allPerfs, $extraOpts, $criticalOnUnknown, $ssdonly, $findregex);
829 my @devicesToCheck_a;
830 if ( !(GetOptions(
831 'v|verbose' => sub { $VERBOSITY = 1 },
832 'vv' => sub { $VERBOSITY = 2 },
833 'vvv' => sub { $VERBOSITY = 3 },
834 'h|help' => sub {
835 print getVersionString();
836 print getUsageString();
837 print getHelpString();
838 exit(STATE_OK);
839 ;},
840 'p|path=s' => \$smartctl,
841 'dbj|dbjson=s' => \$dbJSON,
842 'd|device=s' => \@devicesToCheck_a,
843 'ucfgj|ucfgjson=s' => \$uCfgJSON,
844 'cu|critical_on_unknown' => \$criticalOnUnknown,
845 'nosudo' => \$noSudo,
846 'ap|allperfs' => \$allPerfs,
847 'O|options=s' => \$extraOpts,
848 's|ssdonly' => \$ssdonly,
849 'r|regex=s' => \$findregex,
850 'V|version' => sub{
851 print getVersionString()."\n";
852 exit(STATE_OK);
853 },
854 ))) {
855 print getUsageString();
856 exit(STATE_UNKNOWN);
857 }
858 # Check smartclt tool
859 if(!defined($smartctl)){
860 $smartctl = "/usr/sbin/smartctl";
861 }
862 if(! -x $smartctl){
863 print "Error: cannot find smartctl executable.\n";
864 exit(STATE_UNKNOWN);
865 }
866 # Check for sudo unless disabled
867 if(!defined($noSudo)){
868 my $sudo;
869 chomp($sudo = `which sudo`);
870 if(! -x $sudo){
871 print "Error: cannot find sudo executable.\n";
872 exit(STATE_UNKNOWN);
873 }
874 $smartctl = $sudo.' '.$smartctl;
875 }
876 # The smartdb must be present
877 if(!defined($dbJSON)){
878 print "Error: smartctl requires a valid smartdb JSON file.\n";
879 print getUsageString();
880 exit(STATE_UNKNOWN);
881 }
882 # Devices to check are required
883 if(!(@devicesToCheck_a)){
884 # If no devices are given check if a regex should be used
885 if($findregex){
886 @devicesToCheck_a = findDevicesByRegex($findregex);
887 if(!(@devicesToCheck_a)){
888 print "Error: the find command with the given regex did not return any device(s).\n";
889 }
890 }
891 if(!(@devicesToCheck_a)){
892 print "Error: check_smart_values requires a device to check.\n";
893 print getUsageString();
894 exit(STATE_UNKNOWN);
895 }
896 }
897 # Check if a user config is given
898 my $uCfg;
899 if(defined($uCfgJSON)){
900 $uCfg = readUCfgJSON($uCfgJSON);
901 }
902 my ( $output_h, $command_h ) = getSmartctl($smartctl,\@devicesToCheck_a,$extraOpts);
903 my $dbConfig = readDbJSON($dbJSON);
904 my ( $devices_a, $devices_missing_a ) = checkWhichDevice($dbConfig,$uCfg,$ssdonly,$output_h);
905 if(@$devices_missing_a){
906 print "Error: the following device(s) were not found in the smartdb JSON file: ";
907 print printMissingDevicesDB($devices_missing_a)."\n";
908 print "Smartctl was called with the following commands:\n";
909 foreach my $device (keys %$command_h){
910 print $device.': '.$command_h->{$device}."\n";
911 }
912 if(!defined($criticalOnUnknown)){
913 exit(STATE_UNKNOWN);
914 }
915 else {
916 exit(STATE_CRITICAL);
917 }
918 }
919
920 my $smartValues_h = parseSmartctlOut($output_h);
921 my $statusLevel_a = checkSmartctl($smartValues_h,$devices_a);
922
923 $exitCode = STATE_OK;
924 if($statusLevel_a->[0] eq "Critical"){
925 $exitCode = STATE_CRITICAL;
926 }
927 if($statusLevel_a->[0] eq "Warning"){
928 $exitCode = STATE_WARNING;
929 }
930
931 print $statusLevel_a->[0];
932 print' (';
933 my $dev_str;
934 foreach my $devChecked (@$devices_a){
935 $dev_str .= ', ' if defined($dev_str);
936 $devChecked->{'Path'} =~ m/^\/dev\/(?:disk\/by-(?:id|label)\/)?([A-Za-z0-9_\-,\.\:]+)$/;
937 $dev_str .= $1;
938 }
939 $dev_str .= ') ';
940 # If the status string exceeds 36 chars, just use the number of checked devices
941 if(length($dev_str) > 36){
942 $dev_str = scalar(@$devices_a).' devices) ';
943 }
944 print $dev_str;
945 print getStatusString("Critical",$statusLevel_a,$smartValues_h,$devices_a);
946 print getStatusString("Warning",$statusLevel_a,$smartValues_h,$devices_a);
947 my $perf_str = getPerfString($smartValues_h,$devices_a,$allPerfs);
948 if($perf_str){
949 print "|".$perf_str;
950 }
951 if($VERBOSITY == 2 || $VERBOSITY == 3){
952 print getVerboseString($smartValues_h,$devices_a,$output_h,$command_h);
953 }
954 else{
955 print "\n";
956 }
957 exit ($exitCode);
958 }