]> git.proxmox.com Git - pve-storage.git/blob - PVE/Diskmanage.pm
Diskmanage: correctly add wearout value of 0
[pve-storage.git] / PVE / Diskmanage.pm
1 package PVE::Diskmanage;
2
3 use strict;
4 use warnings;
5 use PVE::ProcFSTools;
6 use Data::Dumper;
7 use Cwd qw(abs_path);
8 use Fcntl ':mode';
9
10 use PVE::Tools qw(extract_param run_command file_get_contents file_read_firstline dir_glob_regex dir_glob_foreach trim);
11
12 my $SMARTCTL = "/usr/sbin/smartctl";
13 my $ZPOOL = "/sbin/zpool";
14 my $SGDISK = "/sbin/sgdisk";
15 my $PVS = "/sbin/pvs";
16 my $LVS = "/sbin/lvs";
17 my $UDEVADM = "/bin/udevadm";
18
19 sub verify_blockdev_path {
20 my ($rel_path) = @_;
21
22 die "missing path" if !$rel_path;
23 my $path = abs_path($rel_path);
24 die "failed to get absolute path to $rel_path\n" if !$path;
25
26 die "got unusual device path '$path'\n" if $path !~ m|^/dev/(.*)$|;
27
28 $path = "/dev/$1"; # untaint
29
30 assert_blockdev($path);
31
32 return $path;
33 }
34
35 sub assert_blockdev {
36 my ($dev, $noerr) = @_;
37
38 if ($dev !~ m|^/dev/| || !(-b $dev)) {
39 return undef if $noerr;
40 die "not a valid block device\n";
41 }
42
43 return 1;
44 }
45
46 sub init_disk {
47 my ($disk, $uuid) = @_;
48
49 assert_blockdev($disk);
50
51 # we should already have checked if it is in use in the api call
52 # but we check again for safety
53 die "disk $disk is already in use\n" if disk_is_used($disk);
54
55 my $id = $uuid || 'R';
56 run_command([$SGDISK, $disk, '-U', $id]);
57 return 1;
58 }
59
60 sub disk_is_used {
61 my ($disk) = @_;
62
63 my $dev = $disk;
64 $dev =~ s|^/dev/||;
65
66 my $disklist = get_disks($dev, 1);
67
68 die "'$disk' is not a valid local disk\n" if !defined($disklist->{$dev});
69 return 1 if $disklist->{$dev}->{used};
70
71 return 0;
72 }
73
74 sub get_smart_data {
75 my ($disk, $healthonly) = @_;
76
77 assert_blockdev($disk);
78 my $smartdata = {};
79 my $type;
80
81 my $returncode = 0;
82
83 if ($disk =~ m!^/dev/(nvme\d+n\d+)$!) {
84 my $info = get_sysdir_info("/sys/block/$1");
85 $disk = "/dev/".($info->{device}
86 or die "failed to get nvme controller device for $disk\n");
87 }
88
89 my $cmd = [$SMARTCTL, '-H'];
90 push @$cmd, '-A', '-f', 'brief' if !$healthonly;
91 push @$cmd, $disk;
92
93 eval {
94 $returncode = run_command($cmd, noerr => 1, outfunc => sub{
95 my ($line) = @_;
96
97 # ATA SMART attributes, e.g.:
98 # ID# ATTRIBUTE_NAME FLAGS VALUE WORST THRESH FAIL RAW_VALUE
99 # 1 Raw_Read_Error_Rate POSR-K 100 100 000 - 0
100 #
101 # SAS and NVME disks, e.g.:
102 # Data Units Written: 5,584,952 [2.85 TB]
103 # Accumulated start-stop cycles: 34
104
105 if (defined($type) && $type eq 'ata' && $line =~ m/^([ \d]{2}\d)\s+(\S+)\s+(\S{6})\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+)\s+(.*)$/) {
106 my $entry = {};
107
108
109 $entry->{name} = $2 if defined $2;
110 $entry->{flags} = $3 if defined $3;
111 # the +0 makes a number out of the strings
112 $entry->{value} = $4+0 if defined $4;
113 $entry->{worst} = $5+0 if defined $5;
114 # some disks report the default threshold as --- instead of 000
115 if (defined($6) && $6 eq '---') {
116 $entry->{threshold} = 0;
117 } else {
118 $entry->{threshold} = $6+0 if defined $6;
119 }
120 $entry->{fail} = $7 if defined $7;
121 $entry->{raw} = $8 if defined $8;
122 $entry->{id} = $1 if defined $1;
123 push @{$smartdata->{attributes}}, $entry;
124 } elsif ($line =~ m/(?:Health Status|self\-assessment test result): (.*)$/ ) {
125 $smartdata->{health} = $1;
126 } elsif ($line =~ m/Vendor Specific SMART Attributes with Thresholds:/) {
127 $type = 'ata';
128 delete $smartdata->{text};
129 } elsif ($line =~ m/=== START OF (READ )?SMART DATA SECTION ===/) {
130 $type = 'text';
131 } elsif (defined($type) && $type eq 'text') {
132 $smartdata->{text} = '' if !defined $smartdata->{text};
133 $smartdata->{text} .= "$line\n";
134 # extract wearout from nvme text, allow for decimal values
135 if ($line =~ m/Percentage Used:.*(\d+(?:\.\d+)?)\%/i) {
136 $smartdata->{wearout} = 100 - $1;
137 }
138 } elsif ($line =~ m/SMART Disabled/) {
139 $smartdata->{health} = "SMART Disabled";
140 }
141 });
142 };
143 my $err = $@;
144
145 # bit 0 and 1 mark an severe smartctl error
146 # all others are for disk status, so ignore them
147 # see smartctl(8)
148 if ((defined($returncode) && ($returncode & 0b00000011)) || $err) {
149 die "Error getting S.M.A.R.T. data: Exit code: $returncode\n";
150 }
151
152 $smartdata->{type} = $type;
153
154 return $smartdata;
155 }
156
157 sub get_zfs_devices {
158 my $list = {};
159
160 return {} if ! -x $ZPOOL;
161
162 # use zpool and parttype uuid,
163 # because log and cache do not have
164 # zfs type uuid
165 eval {
166 run_command([$ZPOOL, 'list', '-HPLv'], outfunc => sub {
167 my ($line) = @_;
168
169 if ($line =~ m|^\t([^\t]+)\t|) {
170 $list->{$1} = 1;
171 }
172 });
173 };
174
175 # only warn here,
176 # because maybe zfs tools are not installed
177 warn "$@\n" if $@;
178
179 my $applezfsuuid = "6a898cc3-1dd2-11b2-99a6-080020736631";
180 my $bsdzfsuuid = "516e7cba-6ecf-11d6-8ff8-00022d09712b";
181
182 dir_glob_foreach('/dev/disk/by-parttypeuuid', "($applezfsuuid|$bsdzfsuuid)\..+", sub {
183 my ($entry) = @_;
184 my $real_dev = abs_path("/dev/disk/by-parttypeuuid/$entry");
185 $list->{$real_dev} = 1;
186 });
187
188 return $list;
189 }
190
191 sub get_lvm_devices {
192 my $list = {};
193 eval {
194 run_command([$PVS, '--noheadings', '--readonly', '-o', 'pv_name'], outfunc => sub{
195 my ($line) = @_;
196 $line = trim($line);
197 if ($line =~ m|^/dev/|) {
198 $list->{$line} = 1;
199 }
200 });
201 };
202
203 # if something goes wrong, we do not want
204 # to give up, but indicate an error has occured
205 warn "$@\n" if $@;
206
207 my $lvmuuid = "e6d6d379-f507-44c2-a23c-238f2a3df928";
208
209 dir_glob_foreach('/dev/disk/by-parttypeuuid', "$lvmuuid\..+", sub {
210 my ($entry) = @_;
211 my $real_dev = abs_path("/dev/disk/by-parttypeuuid/$entry");
212 $list->{$real_dev} = 1;
213 });
214
215 return $list;
216 }
217
218 sub get_ceph_journals {
219 my $journalhash = {};
220
221 my $journal_uuid = '45b0969e-9b03-4f30-b4c6-b4b80ceff106';
222 my $db_uuid = '30cd0809-c2b2-499c-8879-2d6b78529876';
223 my $wal_uuid = '5ce17fce-4087-4169-b7ff-056cc58473f9';
224 my $block_uuid = 'cafecafe-9b03-4f30-b4c6-b4b80ceff106';
225
226 dir_glob_foreach('/dev/disk/by-parttypeuuid', "($journal_uuid|$db_uuid|$wal_uuid|$block_uuid)\..+", sub {
227 my ($entry, $type) = @_;
228 my $real_dev = abs_path("/dev/disk/by-parttypeuuid/$entry");
229 if ($type eq $journal_uuid) {
230 $journalhash->{$real_dev} = 1;
231 } elsif ($type eq $db_uuid) {
232 $journalhash->{$real_dev} = 2;
233 } elsif ($type eq $wal_uuid) {
234 $journalhash->{$real_dev} = 3;
235 } elsif ($type eq $block_uuid) {
236 $journalhash->{$real_dev} = 4;
237 }
238 });
239
240 return $journalhash;
241 }
242
243 # reads the lv_tags and matches them with the devices
244 sub get_ceph_volume_infos {
245 my $result = {};
246
247 my $cmd = [ $LVS, '-S', 'lv_name=~^osd-', '-o', 'devices,lv_name,lv_tags',
248 '--noheadings', '--readonly', '--separator', ';' ];
249
250 run_command($cmd, outfunc => sub {
251 my $line = shift;
252 $line =~ s/(?:^\s+)|(?:\s+$)//g; # trim whitespaces
253
254 my $fields = [ split(';', $line) ];
255
256 # lvs syntax is /dev/sdX(Y) where Y is the start (which we do not need)
257 my ($dev) = $fields->[0] =~ m|^(/dev/[a-z]+)|;
258 if ($fields->[1] =~ m|^osd-([^-]+)-|) {
259 my $type = $1;
260 # $result autovivification is wanted, to not creating empty hashes
261 if (($type eq 'block' || $type eq 'data') && $fields->[2] =~ m/ceph.osd_id=([^,])/) {
262 $result->{$dev}->{osdid} = $1;
263 $result->{$dev}->{bluestore} = ($type eq 'block');
264 } else {
265 # undef++ becomes '1' (see `perldoc perlop`: Auto-increment)
266 $result->{$dev}->{$type}++;
267 }
268 }
269 });
270
271 return $result;
272 }
273
274 sub get_udev_info {
275 my ($dev) = @_;
276
277 my $info = "";
278 my $data = {};
279 eval {
280 run_command([$UDEVADM, 'info', '-p', $dev, '--query', 'all'], outfunc => sub {
281 my ($line) = @_;
282 $info .= "$line\n";
283 });
284 };
285 warn $@ if $@;
286 return undef if !$info;
287
288 return undef if $info !~ m/^E: DEVTYPE=disk$/m;
289 return undef if $info =~ m/^E: ID_CDROM/m;
290
291 # we use this, because some disks are not simply in /dev
292 # e.g. /dev/cciss/c0d0
293 if ($info =~ m/^E: DEVNAME=(\S+)$/m) {
294 $data->{devpath} = $1;
295 }
296 return if !defined($data->{devpath});
297
298 $data->{serial} = 'unknown';
299 if ($info =~ m/^E: ID_SERIAL_SHORT=(\S+)$/m) {
300 $data->{serial} = $1;
301 }
302
303 $data->{gpt} = 0;
304 if ($info =~ m/^E: ID_PART_TABLE_TYPE=gpt$/m) {
305 $data->{gpt} = 1;
306 }
307
308 # detect SSD
309 $data->{rpm} = -1;
310 if ($info =~ m/^E: ID_ATA_ROTATION_RATE_RPM=(\d+)$/m) {
311 $data->{rpm} = $1;
312 }
313
314 if ($info =~ m/^E: ID_BUS=usb$/m) {
315 $data->{usb} = 1;
316 }
317
318 if ($info =~ m/^E: ID_MODEL=(.+)$/m) {
319 $data->{model} = $1;
320 }
321
322 $data->{wwn} = 'unknown';
323 if ($info =~ m/^E: ID_WWN=(.*)$/m) {
324 $data->{wwn} = $1;
325 }
326
327 return $data;
328 }
329
330 sub get_sysdir_info {
331 my ($sysdir) = @_;
332
333 return undef if ! -d "$sysdir/device";
334
335 my $data = {};
336
337 my $size = file_read_firstline("$sysdir/size");
338 return undef if !$size;
339
340 # linux always considers sectors to be 512 bytes,
341 # independently of real block size
342 $data->{size} = $size * 512;
343
344 # dir/queue/rotational should be 1 for hdd, 0 for ssd
345 $data->{rotational} = file_read_firstline("$sysdir/queue/rotational") // -1;
346
347 $data->{vendor} = file_read_firstline("$sysdir/device/vendor") || 'unknown';
348 $data->{model} = file_read_firstline("$sysdir/device/model") || 'unknown';
349
350 if (defined(my $device = readlink("$sysdir/device"))) {
351 # strip directory and untaint:
352 ($data->{device}) = $device =~ m!([^/]+)$!;
353 }
354
355 return $data;
356 }
357
358 sub get_wear_leveling_info {
359 my ($smartdata, $model) = @_;
360 my $attributes = $smartdata->{attributes};
361
362 if (defined($smartdata->{wearout})) {
363 return $smartdata->{wearout};
364 }
365
366 my $wearout;
367
368 my $vendormap = {
369 'kingston' => 231,
370 'samsung' => 177,
371 'intel' => 233,
372 'sandisk' => 233,
373 'crucial' => 202,
374 'default' => 233,
375 };
376
377 # find target attr id
378
379 my $attrid;
380
381 foreach my $vendor (keys %$vendormap) {
382 if ($model =~ m/$vendor/i) {
383 $attrid = $vendormap->{$vendor};
384 # found the attribute
385 last;
386 }
387 }
388
389 if (!$attrid) {
390 $attrid = $vendormap->{default};
391 }
392
393 foreach my $attr (@$attributes) {
394 next if $attr->{id} != $attrid;
395 $wearout = $attr->{value};
396 last;
397 }
398
399 return $wearout;
400 }
401
402 sub dir_is_empty {
403 my ($dir) = @_;
404
405 my $dh = IO::Dir->new ($dir);
406 return 1 if !$dh;
407
408 while (defined(my $tmp = $dh->read)) {
409 next if $tmp eq '.' || $tmp eq '..';
410 $dh->close;
411 return 0;
412 }
413 $dh->close;
414 return 1;
415 }
416
417 sub is_iscsi {
418 my ($sysdir) = @_;
419
420 if (-l $sysdir && readlink($sysdir) =~ m|host[^/]*/session[^/]*|) {
421 return 1;
422 }
423
424 return 0;
425 }
426
427 sub get_disks {
428 my ($disks, $nosmart) = @_;
429 my $disklist = {};
430
431 my $mounted = {};
432
433 my $mounts = PVE::ProcFSTools::parse_proc_mounts();
434
435 foreach my $mount (@$mounts) {
436 next if $mount->[0] !~ m|^/dev/|;
437 $mounted->{abs_path($mount->[0])} = $mount->[1];
438 };
439
440 my $dev_is_mounted = sub {
441 my ($dev) = @_;
442 return $mounted->{$dev};
443 };
444
445 my $journalhash = get_ceph_journals();
446 my $ceph_volume_infos = get_ceph_volume_infos();
447
448 my $zfslist = get_zfs_devices();
449
450 my $lvmlist = get_lvm_devices();
451
452 my $disk_regex = ".*";
453 if (defined($disks)) {
454 if (!ref($disks)) {
455 $disks = [ $disks ];
456 } elsif (ref($disks) ne 'ARRAY') {
457 die "disks is not a string or array reference\n";
458 }
459 # we get cciss/c0d0 but need cciss!c0d0
460 map { s|cciss/|cciss!| } @$disks;
461
462 $disk_regex = "(?:" . join('|', @$disks) . ")";
463 }
464
465 dir_glob_foreach('/sys/block', $disk_regex, sub {
466 my ($dev) = @_;
467 # whitelisting following devices
468 # hdX: ide block device
469 # sdX: sd block device
470 # vdX: virtual block device
471 # xvdX: xen virtual block device
472 # nvmeXnY: nvme devices
473 # cciss!cXnY: cciss devices
474 return if $dev !~ m/^(h|s|x?v)d[a-z]+$/ &&
475 $dev !~ m/^nvme\d+n\d+$/ &&
476 $dev !~ m/^cciss\!c\d+d\d+$/;
477
478 my $data = get_udev_info("/sys/block/$dev");
479 return if !defined($data);
480 my $devpath = $data->{devpath};
481
482 my $sysdir = "/sys/block/$dev";
483
484 # we do not want iscsi devices
485 return if is_iscsi($sysdir);
486
487 my $sysdata = get_sysdir_info($sysdir);
488 return if !defined($sysdata);
489
490 my $type = 'unknown';
491
492 if ($sysdata->{rotational} == 0) {
493 $type = 'ssd';
494 $data->{rpm} = 0;
495 } elsif ($sysdata->{rotational} == 1) {
496 if ($data->{rpm} != -1) {
497 $type = 'hdd';
498 } elsif ($data->{usb}) {
499 $type = 'usb';
500 $data->{rpm} = 0;
501 }
502 }
503
504 my $health = 'UNKNOWN';
505 my $wearout = 'N/A';
506
507 if (!$nosmart) {
508 eval {
509 my $smartdata = get_smart_data($devpath, ($type ne 'ssd'));
510 $health = $smartdata->{health} if $smartdata->{health};
511
512 if ($type eq 'ssd') {
513 # if we have an ssd we try to get the wearout indicator
514 my $wearval = get_wear_leveling_info($smartdata, $data->{model} || $sysdata->{model});
515 $wearout = $wearval if defined($wearval);
516 }
517 };
518 }
519
520 my $used;
521
522 $used = 'LVM' if $lvmlist->{$devpath};
523
524 $used = 'mounted' if &$dev_is_mounted($devpath);
525
526 $used = 'ZFS' if $zfslist->{$devpath};
527
528 # we replaced cciss/ with cciss! above
529 # but in the result we need cciss/ again
530 # because the caller might want to check the
531 # result again with the original parameter
532 if ($dev =~ m|^cciss!|) {
533 $dev =~ s|^cciss!|cciss/|;
534 }
535
536 $disklist->{$dev} = {
537 vendor => $sysdata->{vendor},
538 model => $data->{model} || $sysdata->{model},
539 size => $sysdata->{size},
540 serial => $data->{serial},
541 gpt => $data->{gpt},
542 rpm => $data->{rpm},
543 type => $type,
544 wwn => $data->{wwn},
545 health => $health,
546 devpath => $devpath,
547 wearout => $wearout,
548 };
549
550 my $osdid = -1;
551 my $bluestore = 0;
552
553 my $journal_count = 0;
554 my $db_count = 0;
555 my $wal_count = 0;
556
557 my $found_partitions;
558 my $found_lvm;
559 my $found_mountpoints;
560 my $found_zfs;
561 my $found_dm;
562 my $partpath = $devpath;
563
564 # remove part after last / to
565 # get the base path for the partitions
566 # e.g. from /dev/cciss/c0d0 get /dev/cciss
567 $partpath =~ s/\/[^\/]+$//;
568
569 dir_glob_foreach("$sysdir", "$dev.+", sub {
570 my ($part) = @_;
571
572 $found_partitions = 1;
573
574 if (my $mp = &$dev_is_mounted("$partpath/$part")) {
575 $found_mountpoints = 1;
576 if ($mp =~ m|^/var/lib/ceph/osd/ceph-(\d+)$|) {
577 $osdid = $1;
578 }
579 }
580
581 if ($lvmlist->{"$partpath/$part"}) {
582 $found_lvm = 1;
583 }
584
585 if ($zfslist->{"$partpath/$part"}) {
586 $found_zfs = 1;
587 }
588
589 if (my $journal_part = $journalhash->{"$partpath/$part"}) {
590 $journal_count++ if $journal_part == 1;
591 $db_count++ if $journal_part == 2;
592 $wal_count++ if $journal_part == 3;
593 $bluestore = 1 if $journal_part == 4;
594 }
595
596 if (!dir_is_empty("$sysdir/$part/holders") && !$found_lvm) {
597 $found_dm = 1;
598 }
599 });
600
601 if (my $ceph_volume = $ceph_volume_infos->{$devpath}) {
602 $journal_count += $ceph_volume->{journal} // 0;
603 $db_count += $ceph_volume->{db} // 0;
604 $wal_count += $ceph_volume->{wal} // 0;
605 if ($ceph_volume->{osdid}) {
606 $osdid = $ceph_volume->{osdid};
607 $bluestore = 1 if $ceph_volume->{bluestore};
608 }
609 }
610
611 $used = 'mounted' if $found_mountpoints && !$used;
612 $used = 'LVM' if $found_lvm && !$used;
613 $used = 'ZFS' if $found_zfs && !$used;
614 $used = 'Device Mapper' if $found_dm && !$used;
615 $used = 'partitions' if $found_partitions && !$used;
616
617 # multipath, software raid, etc.
618 # this check comes in last, to show more specific info
619 # if we have it
620 $used = 'Device Mapper' if !$used && !dir_is_empty("$sysdir/holders");
621
622 $disklist->{$dev}->{used} = $used if $used;
623 $disklist->{$dev}->{osdid} = $osdid;
624 $disklist->{$dev}->{journals} = $journal_count if $journal_count;
625 $disklist->{$dev}->{bluestore} = $bluestore if $osdid != -1;
626 $disklist->{$dev}->{db} = $db_count if $db_count;
627 $disklist->{$dev}->{wal} = $wal_count if $wal_count;
628 });
629
630 return $disklist;
631
632 }
633
634 sub get_partnum {
635 my ($part_path) = @_;
636
637 my ($mode, $rdev) = (stat($part_path))[2,6];
638
639 next if !$mode || !S_ISBLK($mode) || !$rdev;
640 my $major = PVE::Tools::dev_t_major($rdev);
641 my $minor = PVE::Tools::dev_t_minor($rdev);
642 my $partnum_path = "/sys/dev/block/$major:$minor/";
643
644 my $partnum;
645
646 $partnum = file_read_firstline("${partnum_path}partition");
647
648 die "Partition does not exists\n" if !defined($partnum);
649
650 #untaint and ensure it is a int
651 if ($partnum =~ m/(\d+)/) {
652 $partnum = $1;
653 die "Partition number $partnum is invalid\n" if $partnum > 128;
654 } else {
655 die "Failed to get partition number\n";
656 }
657
658 return $partnum;
659 }
660
661 sub get_blockdev {
662 my ($part_path) = @_;
663
664 my $dev = $1 if $part_path =~ m|^/dev/(.*)$|;
665 my $link = readlink "/sys/class/block/$dev";
666 my $block_dev = $1 if $link =~ m|([^/]*)/$dev$|;
667
668 die "Can't parse parent device\n" if !defined($block_dev);
669 die "No valid block device\n" if index($dev, $block_dev) == -1;
670
671 $block_dev = "/dev/$block_dev";
672 die "Block device does not exsists\n" if !(-b $block_dev);
673
674 return $block_dev;
675 }
676
677 sub locked_disk_action {
678 my ($sub) = @_;
679 my $res = PVE::Tools::lock_file('/run/lock/pve-diskmanage.lck', undef, $sub);
680 die $@ if $@;
681 return $res;
682 }
683
684 sub assert_disk_unused {
685 my ($dev) = @_;
686
687 die "device '$dev' is already in use\n" if disk_is_used($dev);
688
689 return undef;
690 }
691
692 sub append_partition {
693 my ($dev, $size) = @_;
694
695 my $devname = $dev;
696 $devname =~ s|^/dev/||;
697
698 my $newpartid = 1;
699 dir_glob_foreach("/sys/block/$devname", qr/\Q$devname\E.*?(\d+)/, sub {
700 my ($part, $partid) = @_;
701
702 if ($partid >= $newpartid) {
703 $newpartid = $partid + 1;
704 }
705 });
706
707 $size = PVE::Tools::convert_size($size, 'b' => 'mb');
708
709 run_command([ $SGDISK, '-n', "$newpartid:0:+${size}M", $dev ],
710 errmsg => "error creating partition '$newpartid' on '$dev'");
711
712 my $partition;
713
714 # loop again to detect the real partiton device which does not always follow
715 # a strict $devname$partition scheme like /dev/nvme0n1 -> /dev/nvme0n1p1
716 dir_glob_foreach("/sys/block/$devname", qr/\Q$devname\E.*$newpartid/, sub {
717 my ($part) = @_;
718
719 $partition = "/dev/$part";
720 });
721
722 return $partition;
723 }
724
725 1;