1 package PVE
::Diskmanage
;
14 use PVE
::Tools
qw(extract_param run_command file_get_contents file_read_firstline dir_glob_regex dir_glob_foreach trim);
16 my $SMARTCTL = "/usr/sbin/smartctl";
17 my $ZPOOL = "/sbin/zpool";
18 my $SGDISK = "/sbin/sgdisk";
19 my $PVS = "/sbin/pvs";
20 my $LVS = "/sbin/lvs";
21 my $LSBLK = "/bin/lsblk";
29 sub verify_blockdev_path
{
32 die "missing path" if !$rel_path;
33 my $path = abs_path
($rel_path);
34 die "failed to get absolute path to $rel_path\n" if !$path;
36 die "got unusual device path '$path'\n" if $path !~ m
|^/dev/(.*)$|;
38 $path = "/dev/$1"; # untaint
40 assert_blockdev
($path);
46 my ($dev, $noerr) = @_;
48 if ($dev !~ m
|^/dev/| || !(-b
$dev)) {
49 return undef if $noerr;
50 die "not a valid block device\n";
57 my ($disk, $uuid) = @_;
59 assert_blockdev
($disk);
61 # we should already have checked if it is in use in the api call
62 # but we check again for safety
63 die "disk $disk is already in use\n" if disk_is_used
($disk);
65 my $id = $uuid || 'R';
66 run_command
([$SGDISK, $disk, '-U', $id]);
76 my $disklist = get_disks
($dev, 1);
78 die "'$disk' is not a valid local disk\n" if !defined($disklist->{$dev});
79 return 1 if $disklist->{$dev}->{used
};
85 my ($disk, $healthonly) = @_;
87 assert_blockdev
($disk);
93 if ($disk =~ m!^/dev/(nvme\d+n\d+)$!) {
94 my $info = get_sysdir_info
("/sys/block/$1");
95 $disk = "/dev/".($info->{device
}
96 or die "failed to get nvme controller device for $disk\n");
99 my $cmd = [$SMARTCTL, '-H'];
100 push @$cmd, '-A', '-f', 'brief' if !$healthonly;
104 $returncode = run_command
($cmd, noerr
=> 1, outfunc
=> sub{
107 # ATA SMART attributes, e.g.:
108 # ID# ATTRIBUTE_NAME FLAGS VALUE WORST THRESH FAIL RAW_VALUE
109 # 1 Raw_Read_Error_Rate POSR-K 100 100 000 - 0
111 # SAS and NVME disks, e.g.:
112 # Data Units Written: 5,584,952 [2.85 TB]
113 # Accumulated start-stop cycles: 34
115 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+(.*)$/) {
118 $entry->{name
} = $2 if defined $2;
119 $entry->{flags
} = $3 if defined $3;
120 # the +0 makes a number out of the strings
121 $entry->{value
} = $4+0 if defined $4;
122 $entry->{worst
} = $5+0 if defined $5;
123 # some disks report the default threshold as --- instead of 000
124 if (defined($6) && $6 eq '---') {
125 $entry->{threshold
} = 0;
127 $entry->{threshold
} = $6+0 if defined $6;
129 $entry->{fail
} = $7 if defined $7;
130 $entry->{raw
} = $8 if defined $8;
131 $entry->{id
} = $1 if defined $1;
132 push @{$smartdata->{attributes
}}, $entry;
133 } elsif ($line =~ m/(?:Health Status|self\-assessment test result): (.*)$/ ) {
134 $smartdata->{health
} = $1;
135 } elsif ($line =~ m/Vendor Specific SMART Attributes with Thresholds:/) {
137 delete $smartdata->{text
};
138 } elsif ($line =~ m/=== START OF (READ )?SMART DATA SECTION ===/) {
140 } elsif (defined($type) && $type eq 'text') {
141 $smartdata->{text
} = '' if !defined $smartdata->{text
};
142 $smartdata->{text
} .= "$line\n";
143 # extract wearout from nvme/sas text, allow for decimal values
144 if ($line =~ m/Percentage Used(?: endurance indicator)?:\s*(\d+(?:\.\d+)?)\%/i) {
145 $smartdata->{wearout
} = 100 - $1;
147 } elsif ($line =~ m/SMART Disabled/) {
148 $smartdata->{health
} = "SMART Disabled";
154 # bit 0 and 1 mark an severe smartctl error
155 # all others are for disk status, so ignore them
157 if ((defined($returncode) && ($returncode & 0b00000011)) || $err) {
158 die "Error getting S.M.A.R.T. data: Exit code: $returncode\n";
161 $smartdata->{type
} = $type;
166 sub get_lsblk_info
() {
167 my $cmd = [$LSBLK, '--json', '-o', 'path,parttype,fstype'];
171 run_command
($cmd, outfunc
=> sub {
173 $output .= "$line\n";
177 return $res if $output eq '';
179 my $parsed = eval { decode_json
($output) };
181 my $list = $parsed->{blockdevices
} // [];
185 parttype
=> $_->{parttype
},
186 fstype
=> $_->{fstype
}
193 my $get_devices_by_partuuid = sub {
194 my ($lsblk_info, $uuids, $res) = @_;
196 $res = {} if !defined($res);
198 foreach my $dev (sort keys %{$lsblk_info}) {
199 my $uuid = $lsblk_info->{$dev}->{parttype
};
200 next if !defined($uuid) || !defined($uuids->{$uuid});
201 $res->{$dev} = $uuids->{$uuid};
207 sub get_zfs_devices
{
208 my ($lsblk_info) = @_;
211 return {} if !check_bin
($ZPOOL);
213 # use zpool and parttype uuid,
214 # because log and cache do not have
217 run_command
([$ZPOOL, 'list', '-HPLv'], outfunc
=> sub {
220 if ($line =~ m
|^\t([^\t]+)\t|) {
227 # because maybe zfs tools are not installed
231 "6a898cc3-1dd2-11b2-99a6-080020736631" => 1, # apple
232 "516e7cba-6ecf-11d6-8ff8-00022d09712b" => 1, # bsd
236 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
241 sub get_lvm_devices
{
242 my ($lsblk_info) = @_;
245 run_command
([$PVS, '--noheadings', '--readonly', '-o', 'pv_name'], outfunc
=> sub{
248 if ($line =~ m
|^/dev/|) {
254 # if something goes wrong, we do not want
255 # to give up, but indicate an error has occured
259 "e6d6d379-f507-44c2-a23c-238f2a3df928" => 1,
262 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
267 sub get_ceph_journals
{
268 my ($lsblk_info) = @_;
272 '45b0969e-9b03-4f30-b4c6-b4b80ceff106' => 1, # journal
273 '30cd0809-c2b2-499c-8879-2d6b78529876' => 2, # db
274 '5ce17fce-4087-4169-b7ff-056cc58473f9' => 3, # wal
275 'cafecafe-9b03-4f30-b4c6-b4b80ceff106' => 4, # block
278 $res = $get_devices_by_partuuid->($lsblk_info, $uuids, $res);
283 # reads the lv_tags and matches them with the devices
284 sub get_ceph_volume_infos
{
287 my $cmd = [ $LVS, '-S', 'lv_name=~^osd-', '-o', 'devices,lv_name,lv_tags',
288 '--noheadings', '--readonly', '--separator', ';' ];
290 run_command
($cmd, outfunc
=> sub {
292 $line =~ s/(?:^\s+)|(?:\s+$)//g; # trim whitespaces
294 my $fields = [ split(';', $line) ];
296 # lvs syntax is /dev/sdX(Y) where Y is the start (which we do not need)
297 my ($dev) = $fields->[0] =~ m
|^(/dev/[a-z
]+[^(]*)|;
298 if ($fields->[1] =~ m
|^osd-
([^-]+)-|) {
300 # $result autovivification is wanted, to not creating empty hashes
301 if (($type eq 'block' || $type eq 'data') && $fields->[2] =~ m/ceph.osd_id=([^,]+)/) {
302 $result->{$dev}->{osdid
} = $1;
303 $result->{$dev}->{bluestore
} = ($type eq 'block');
304 if ($fields->[2] =~ m/ceph\.encrypted=1/) {
305 $result->{$dev}->{encrypted
} = 1;
308 # undef++ becomes '1' (see `perldoc perlop`: Auto-increment)
309 $result->{$dev}->{$type}++;
323 run_command
(['udevadm', 'info', '-p', $dev, '--query', 'all'], outfunc
=> sub {
329 return undef if !$info;
331 return undef if $info !~ m/^E: DEVTYPE=disk$/m;
332 return undef if $info =~ m/^E: ID_CDROM/m;
334 # we use this, because some disks are not simply in /dev
335 # e.g. /dev/cciss/c0d0
336 if ($info =~ m/^E: DEVNAME=(\S+)$/m) {
337 $data->{devpath
} = $1;
339 return if !defined($data->{devpath
});
341 $data->{serial
} = 'unknown';
342 if ($info =~ m/^E: ID_SERIAL_SHORT=(\S+)$/m) {
343 $data->{serial
} = $1;
347 if ($info =~ m/^E: ID_PART_TABLE_TYPE=gpt$/m) {
353 if ($info =~ m/^E: ID_ATA_ROTATION_RATE_RPM=(\d+)$/m) {
357 if ($info =~ m/^E: ID_BUS=usb$/m) {
361 if ($info =~ m/^E: ID_MODEL=(.+)$/m) {
365 $data->{wwn
} = 'unknown';
366 if ($info =~ m/^E: ID_WWN=(.*)$/m) {
370 if ($info =~ m/^E: DEVLINKS=(.+)$/m) {
371 my @devlinks = grep(m
#^/dev/disk/by-id/(ata|scsi|nvme(?!-eui))#, split (/ /, $1));
372 $data->{by_id_link
} = $devlinks[0] if defined($devlinks[0]);
378 sub get_sysdir_size
{
381 my $size = file_read_firstline
("$sysdir/size");
384 # linux always considers sectors to be 512 bytes,
385 # independently of real block size
389 sub get_sysdir_info
{
392 return undef if ! -d
"$sysdir/device";
396 $data->{size
} = get_sysdir_size
($sysdir) or return;
398 # dir/queue/rotational should be 1 for hdd, 0 for ssd
399 $data->{rotational
} = file_read_firstline
("$sysdir/queue/rotational") // -1;
401 $data->{vendor
} = file_read_firstline
("$sysdir/device/vendor") || 'unknown';
402 $data->{model
} = file_read_firstline
("$sysdir/device/model") || 'unknown';
404 if (defined(my $device = readlink("$sysdir/device"))) {
405 # strip directory and untaint:
406 ($data->{device
}) = $device =~ m!([^/]+)$!;
412 sub get_wear_leveling_info
{
413 my ($smartdata) = @_;
414 my $attributes = $smartdata->{attributes
};
416 if (defined($smartdata->{wearout
})) {
417 return $smartdata->{wearout
};
422 # Common register names that represent percentage values of potential
423 # failure indicators used in drivedb.h of smartmontool's. Order matters,
424 # as some drives may have multiple definitions
425 my @wearoutregisters = (
426 "Media_Wearout_Indicator",
428 "Wear_Leveling_Count",
429 "Perc_Write\/Erase_Ct_BC",
430 "Perc_Rated_Life_Remain",
431 "Remaining_Lifetime_Perc",
432 "Percent_Lifetime_Remain",
434 "PCT_Life_Remaining",
435 "Lifetime_Remaining",
436 "Percent_Life_Remaining",
437 "Percent_Lifetime_Used",
438 "Perc_Rated_Life_Used"
441 # Search for S.M.A.R.T. attributes for known register
442 foreach my $register (@wearoutregisters) {
443 last if defined $wearout;
444 foreach my $attr (@$attributes) {
445 next if $attr->{name
} !~ m/$register/;
446 $wearout = $attr->{value
};
457 my $dh = IO
::Dir-
>new ($dir);
460 while (defined(my $tmp = $dh->read)) {
461 next if $tmp eq '.' || $tmp eq '..';
472 if (-l
$sysdir && readlink($sysdir) =~ m
|host
[^/]*/session
[^/]*|) {
481 return $type eq 'ssd' || $type eq 'nvme';
484 sub mounted_blockdevs
{
487 my $mounts = PVE
::ProcFSTools
::parse_proc_mounts
();
489 foreach my $mount (@$mounts) {
490 next if $mount->[0] !~ m
|^/dev/|;
491 $mounted->{abs_path
($mount->[0])} = $mount->[1];
498 my ($disks, $nosmart, $include_partitions) = @_;
501 my $mounted = mounted_blockdevs
();
503 my $lsblk_info = get_lsblk_info
();
505 my $journalhash = get_ceph_journals
($lsblk_info);
506 my $ceph_volume_infos = get_ceph_volume_infos
();
508 my $zfshash = get_zfs_devices
($lsblk_info);
510 my $lvmhash = get_lvm_devices
($lsblk_info);
512 my $disk_regex = ".*";
513 if (defined($disks)) {
516 } elsif (ref($disks) ne 'ARRAY') {
517 die "disks is not a string or array reference\n";
519 # we get cciss/c0d0 but need cciss!c0d0
520 $_ =~ s
|cciss
/|cciss
!| for @$disks;
522 $disk_regex = "(?:" . join('|', @$disks) . ")";
525 dir_glob_foreach
('/sys/block', $disk_regex, sub {
527 # whitelisting following devices
528 # hdX: ide block device
529 # sdX: sd block device
530 # vdX: virtual block device
531 # xvdX: xen virtual block device
532 # nvmeXnY: nvme devices
533 # cciss!cXnY: cciss devices
534 return if $dev !~ m/^(h|s|x?v)d[a-z]+$/ &&
535 $dev !~ m/^nvme\d+n\d+$/ &&
536 $dev !~ m/^cciss\!c\d+d\d+$/;
538 my $data = get_udev_info
("/sys/block/$dev");
539 return if !defined($data);
540 my $devpath = $data->{devpath
};
542 my $sysdir = "/sys/block/$dev";
544 # we do not want iscsi devices
545 return if is_iscsi
($sysdir);
547 my $sysdata = get_sysdir_info
($sysdir);
548 return if !defined($sysdata);
550 my $type = 'unknown';
552 if ($sysdata->{rotational
} == 0) {
554 $type = 'nvme' if $dev =~ m/^nvme\d+n\d+$/;
556 } elsif ($sysdata->{rotational
} == 1) {
557 if ($data->{rpm
} != -1) {
559 } elsif ($data->{usb
}) {
565 my $health = 'UNKNOWN';
570 my $smartdata = get_smart_data
($devpath, !is_ssdlike
($type));
571 $health = $smartdata->{health
} if $smartdata->{health
};
573 if (is_ssdlike
($type)) {
574 # if we have an ssd we try to get the wearout indicator
575 my $wearval = get_wear_leveling_info
($smartdata);
576 $wearout = $wearval if defined($wearval);
581 # we replaced cciss/ with cciss! above
582 # but in the result we need cciss/ again
583 # because the caller might want to check the
584 # result again with the original parameter
585 if ($dev =~ m
|^cciss
!|) {
586 $dev =~ s
|^cciss
!|cciss
/|;
589 $disklist->{$dev} = {
590 vendor
=> $sysdata->{vendor
},
591 model
=> $data->{model
} || $sysdata->{model
},
592 size
=> $sysdata->{size
},
593 serial
=> $data->{serial
},
603 my $by_id_link = $data->{by_id_link
};
604 $disklist->{$dev}->{by_id_link
} = $by_id_link if defined($by_id_link);
608 my $osdencrypted = 0;
610 my $journal_count = 0;
614 my $partpath = $devpath;
616 # remove part after last / to
617 # get the base path for the partitions
618 # e.g. from /dev/cciss/c0d0 get /dev/cciss
619 $partpath =~ s/\/[^\/]+$//;
621 my $determine_usage = sub {
622 my ($devpath, $sysdir, $is_partition) = @_;
624 return 'LVM' if $lvmhash->{$devpath};
625 return 'ZFS' if $zfshash->{$devpath};
627 my $info = $lsblk_info->{$devpath} // {};
629 my $parttype = $info->{parttype
};
630 if (defined($parttype)) {
632 if $parttype eq '21686148-6449-6e6f-744e-656564454649';
634 if $parttype eq 'c12a7328-f81f-11d2-ba4b-00a0c93ec93b';
635 return 'ZFS reserved'
636 if $parttype eq '6a945a3b-1dd2-11b2-99a6-080020736631';
639 my $fstype = $info->{fstype
};
640 if (defined($fstype)) {
641 return "${fstype} (mounted)" if $mounted->{$devpath};
644 return 'mounted' if $mounted->{$devpath};
646 return if !$is_partition;
648 # for devices, this check is done explicitly later
649 return 'Device Mapper' if !dir_is_empty
("$sysdir/holders");
654 my $collect_ceph_info = sub {
657 my $ceph_volume = $ceph_volume_infos->{$devpath} or return;
658 $journal_count += $ceph_volume->{journal
} // 0;
659 $db_count += $ceph_volume->{db
} // 0;
660 $wal_count += $ceph_volume->{wal
} // 0;
661 if (defined($ceph_volume->{osdid
})) {
662 $osdid = $ceph_volume->{osdid
};
663 $bluestore = 1 if $ceph_volume->{bluestore
};
664 $osdencrypted = 1 if $ceph_volume->{encrypted
};
667 my $result = { %{$ceph_volume} };
668 $result->{journals
} = delete $result->{journal
}
669 if $result->{journal
};
675 dir_glob_foreach
("$sysdir", "$dev.+", sub {
678 $partitions->{$part} = $collect_ceph_info->("$partpath/$part");
679 my $lvm_based_osd = defined($partitions->{$part});
681 $partitions->{$part}->{devpath
} = "$partpath/$part";
682 $partitions->{$part}->{parent
} = "$devpath";
683 $partitions->{$part}->{gpt
} = $data->{gpt
};
684 $partitions->{$part}->{type
} = 'partition';
685 $partitions->{$part}->{size
} =
686 get_sysdir_size
("$sysdir/$part") // 0;
687 $partitions->{$part}->{used
} =
688 $determine_usage->("$partpath/$part", "$sysdir/$part", 1);
689 $partitions->{$part}->{osdid
} //= -1;
691 # Avoid counting twice (e.g. partition on which the LVM for the
692 # DB OSD resides is present in the $journalhash)
693 return if $lvm_based_osd;
695 # Legacy handling for non-LVM based OSDs
697 if (my $mp = $mounted->{"$partpath/$part"}) {
698 if ($mp =~ m
|^/var/lib
/ceph/osd/ceph-
(\d
+)$|) {
700 $partitions->{$part}->{osdid
} = $osdid;
704 if (my $journal_part = $journalhash->{"$partpath/$part"}) {
705 $journal_count++ if $journal_part == 1;
706 $db_count++ if $journal_part == 2;
707 $wal_count++ if $journal_part == 3;
708 $bluestore = 1 if $journal_part == 4;
710 $partitions->{$part}->{journals
} = 1 if $journal_part == 1;
711 $partitions->{$part}->{db
} = 1 if $journal_part == 2;
712 $partitions->{$part}->{wal
} = 1 if $journal_part == 3;
713 $partitions->{$part}->{bluestore
} = 1 if $journal_part == 4;
717 my $used = $determine_usage->($devpath, $sysdir, 0);
718 if (!$include_partitions) {
719 foreach my $part (sort keys %{$partitions}) {
720 next if $partitions->{$part}->{used
} eq 'partition';
721 $used //= $partitions->{$part}->{used
};
724 # fstype might be set even if there are partitions, but showing that is confusing
725 $used = 'partitions' if scalar(keys %{$partitions});
727 $used //= 'partitions' if scalar(keys %{$partitions});
728 # multipath, software raid, etc.
729 # this check comes in last, to show more specific info
731 $used //= 'Device Mapper' if !dir_is_empty
("$sysdir/holders");
733 $disklist->{$dev}->{used
} = $used if $used;
735 $collect_ceph_info->($devpath);
737 $disklist->{$dev}->{osdid
} = $osdid;
738 $disklist->{$dev}->{journals
} = $journal_count if $journal_count;
739 $disklist->{$dev}->{bluestore
} = $bluestore if $osdid != -1;
740 $disklist->{$dev}->{osdencrypted
} = $osdencrypted if $osdid != -1;
741 $disklist->{$dev}->{db
} = $db_count if $db_count;
742 $disklist->{$dev}->{wal
} = $wal_count if $wal_count;
744 if ($include_partitions) {
745 foreach my $part (keys %{$partitions}) {
746 $disklist->{$part} = $partitions->{$part};
756 my ($part_path) = @_;
758 my $st = stat($part_path);
760 die "error detecting block device '$part_path'\n"
761 if !$st || !$st->mode || !S_ISBLK
($st->mode) || !$st->rdev;
763 my $major = PVE
::Tools
::dev_t_major
($st->rdev);
764 my $minor = PVE
::Tools
::dev_t_minor
($st->rdev);
765 my $partnum_path = "/sys/dev/block/$major:$minor/";
769 $partnum = file_read_firstline
("${partnum_path}partition");
771 die "Partition does not exist\n" if !defined($partnum);
773 #untaint and ensure it is a int
774 if ($partnum =~ m/(\d+)/) {
776 die "Partition number $partnum is invalid\n" if $partnum > 128;
778 die "Failed to get partition number\n";
785 my ($part_path) = @_;
787 my ($dev, $block_dev);
788 if ($part_path =~ m
|^/dev/(.*)$|) {
790 my $link = readlink "/sys/class/block/$dev";
791 $block_dev = $1 if $link =~ m
|([^/]*)/$dev$|;
794 die "Can't parse parent device\n" if !defined($block_dev);
795 die "No valid block device\n" if index($dev, $block_dev) == -1;
797 $block_dev = "/dev/$block_dev";
798 die "Block device does not exsists\n" if !(-b
$block_dev);
803 sub locked_disk_action
{
805 my $res = PVE
::Tools
::lock_file
('/run/lock/pve-diskmanage.lck', undef, $sub);
810 sub assert_disk_unused
{
813 die "device '$dev' is already in use\n" if disk_is_used
($dev);
818 sub append_partition
{
819 my ($dev, $size) = @_;
822 $devname =~ s
|^/dev/||;
825 dir_glob_foreach
("/sys/block/$devname", qr
/\Q
$devname\E.*?
(\d
+)/, sub {
826 my ($part, $partid) = @_;
828 if ($partid >= $newpartid) {
829 $newpartid = $partid + 1;
833 $size = PVE
::Tools
::convert_size
($size, 'b' => 'mb');
835 run_command
([ $SGDISK, '-n', "$newpartid:0:+${size}M", $dev ],
836 errmsg
=> "error creating partition '$newpartid' on '$dev'");
840 # loop again to detect the real partiton device which does not always follow
841 # a strict $devname$partition scheme like /dev/nvme0n1 -> /dev/nvme0n1p1
842 dir_glob_foreach
("/sys/block/$devname", qr
/\Q
$devname\E.*$newpartid/, sub {
845 $partition = "/dev/$part";
851 # Basic check if a disk or any of its partitions is mounted.
852 # Can also be called with a partition.
853 # Expected to be called with a result of verify_blockdev_path().
857 my $mounted = mounted_blockdevs
();
859 return $devpath if $mounted->{$devpath};
866 dir_glob_foreach
("/sys/block/${dev}", "${dev}.+", sub {
869 my $partpath = "/dev/${part}";
871 $found = $partpath if $mounted->{$partpath};
877 # Wipes all labels and the first 200 MiB of a disk/partition (or the whole if it is smaller).
878 # Expected to be called with a result of verify_blockdev_path().
882 my $wipefs_cmd = ['wipefs', '--all', $devpath];
884 my $dd_cmd = ['dd', 'if=/dev/zero', "of=${devpath}", 'bs=1M', 'conv=fdatasync'];
886 my $devname = basename
($devpath);
887 my $dev_size = PVE
::Tools
::file_get_contents
("/sys/class/block/$devname/size");
889 ($dev_size) = $dev_size =~ m
|(\d
+)|; # untaint $dev_size
890 die "Couldn't get the size of the device $devname\n" if !defined($dev_size);
892 my $size = ($dev_size * 512 / 1024 / 1024);
893 my $count = ($size < 200) ?
$size : 200;
895 push @{$dd_cmd}, "count=${count}";
897 print "wiping disk/partition: ${devpath}\n";
899 run_command
($wipefs_cmd, errmsg
=> "error wiping labels for '${devpath}'");
900 run_command
($dd_cmd, errmsg
=> "error wiping '${devpath}'");