]>
git.proxmox.com Git - pve-storage.git/blob - PVE/Diskmanage.pm
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';
485 my ($disks, $nosmart, $include_partitions) = @_;
490 my $mounts = PVE
::ProcFSTools
::parse_proc_mounts
();
492 foreach my $mount (@$mounts) {
493 next if $mount->[0] !~ m
|^/dev/|;
494 $mounted->{abs_path
($mount->[0])} = $mount->[1];
497 my $lsblk_info = get_lsblk_info
();
499 my $journalhash = get_ceph_journals
($lsblk_info);
500 my $ceph_volume_infos = get_ceph_volume_infos
();
502 my $zfshash = get_zfs_devices
($lsblk_info);
504 my $lvmhash = get_lvm_devices
($lsblk_info);
506 my $disk_regex = ".*";
507 if (defined($disks)) {
510 } elsif (ref($disks) ne 'ARRAY') {
511 die "disks is not a string or array reference\n";
513 # we get cciss/c0d0 but need cciss!c0d0
514 $_ =~ s
|cciss
/|cciss
!| for @$disks;
516 $disk_regex = "(?:" . join('|', @$disks) . ")";
519 dir_glob_foreach
('/sys/block', $disk_regex, sub {
521 # whitelisting following devices
522 # hdX: ide block device
523 # sdX: sd block device
524 # vdX: virtual block device
525 # xvdX: xen virtual block device
526 # nvmeXnY: nvme devices
527 # cciss!cXnY: cciss devices
528 return if $dev !~ m/^(h|s|x?v)d[a-z]+$/ &&
529 $dev !~ m/^nvme\d+n\d+$/ &&
530 $dev !~ m/^cciss\!c\d+d\d+$/;
532 my $data = get_udev_info
("/sys/block/$dev");
533 return if !defined($data);
534 my $devpath = $data->{devpath
};
536 my $sysdir = "/sys/block/$dev";
538 # we do not want iscsi devices
539 return if is_iscsi
($sysdir);
541 my $sysdata = get_sysdir_info
($sysdir);
542 return if !defined($sysdata);
544 my $type = 'unknown';
546 if ($sysdata->{rotational
} == 0) {
548 $type = 'nvme' if $dev =~ m/^nvme\d+n\d+$/;
550 } elsif ($sysdata->{rotational
} == 1) {
551 if ($data->{rpm
} != -1) {
553 } elsif ($data->{usb
}) {
559 my $health = 'UNKNOWN';
564 my $smartdata = get_smart_data
($devpath, !is_ssdlike
($type));
565 $health = $smartdata->{health
} if $smartdata->{health
};
567 if (is_ssdlike
($type)) {
568 # if we have an ssd we try to get the wearout indicator
569 my $wearval = get_wear_leveling_info
($smartdata);
570 $wearout = $wearval if defined($wearval);
575 # we replaced cciss/ with cciss! above
576 # but in the result we need cciss/ again
577 # because the caller might want to check the
578 # result again with the original parameter
579 if ($dev =~ m
|^cciss
!|) {
580 $dev =~ s
|^cciss
!|cciss
/|;
583 $disklist->{$dev} = {
584 vendor
=> $sysdata->{vendor
},
585 model
=> $data->{model
} || $sysdata->{model
},
586 size
=> $sysdata->{size
},
587 serial
=> $data->{serial
},
597 my $by_id_link = $data->{by_id_link
};
598 $disklist->{$dev}->{by_id_link
} = $by_id_link if defined($by_id_link);
602 my $osdencrypted = 0;
604 my $journal_count = 0;
608 my $partpath = $devpath;
610 # remove part after last / to
611 # get the base path for the partitions
612 # e.g. from /dev/cciss/c0d0 get /dev/cciss
613 $partpath =~ s/\/[^\/]+$//;
615 my $determine_usage = sub {
616 my ($devpath, $sysdir, $is_partition) = @_;
618 return 'LVM' if $lvmhash->{$devpath};
619 return 'ZFS' if $zfshash->{$devpath};
621 my $info = $lsblk_info->{$devpath} // {};
623 my $parttype = $info->{parttype
};
624 if (defined($parttype)) {
626 if $parttype eq '21686148-6449-6e6f-744e-656564454649';
628 if $parttype eq 'c12a7328-f81f-11d2-ba4b-00a0c93ec93b';
629 return 'ZFS reserved'
630 if $parttype eq '6a945a3b-1dd2-11b2-99a6-080020736631';
633 my $fstype = $info->{fstype
};
634 if (defined($fstype)) {
635 return "${fstype} (mounted)" if $mounted->{$devpath};
638 return 'mounted' if $mounted->{$devpath};
640 return if !$is_partition;
642 # for devices, this check is done explicitly later
643 return 'Device Mapper' if !dir_is_empty
("$sysdir/holders");
648 my $collect_ceph_info = sub {
651 my $ceph_volume = $ceph_volume_infos->{$devpath} or return;
652 $journal_count += $ceph_volume->{journal
} // 0;
653 $db_count += $ceph_volume->{db
} // 0;
654 $wal_count += $ceph_volume->{wal
} // 0;
655 if (defined($ceph_volume->{osdid
})) {
656 $osdid = $ceph_volume->{osdid
};
657 $bluestore = 1 if $ceph_volume->{bluestore
};
658 $osdencrypted = 1 if $ceph_volume->{encrypted
};
661 my $result = { %{$ceph_volume} };
662 $result->{journals
} = delete $result->{journal
}
663 if $result->{journal
};
669 dir_glob_foreach
("$sysdir", "$dev.+", sub {
672 $partitions->{$part} = $collect_ceph_info->("$partpath/$part");
673 my $lvm_based_osd = defined($partitions->{$part});
675 $partitions->{$part}->{devpath
} = "$partpath/$part";
676 $partitions->{$part}->{parent
} = "$devpath";
677 $partitions->{$part}->{gpt
} = $data->{gpt
};
678 $partitions->{$part}->{type
} = 'partition';
679 $partitions->{$part}->{size
} =
680 get_sysdir_size
("$sysdir/$part") // 0;
681 $partitions->{$part}->{used
} =
682 $determine_usage->("$partpath/$part", "$sysdir/$part", 1);
683 $partitions->{$part}->{osdid
} //= -1;
685 # Avoid counting twice (e.g. partition on which the LVM for the
686 # DB OSD resides is present in the $journalhash)
687 return if $lvm_based_osd;
689 # Legacy handling for non-LVM based OSDs
691 if (my $mp = $mounted->{"$partpath/$part"}) {
692 if ($mp =~ m
|^/var/lib
/ceph/osd/ceph-
(\d
+)$|) {
694 $partitions->{$part}->{osdid
} = $osdid;
698 if (my $journal_part = $journalhash->{"$partpath/$part"}) {
699 $journal_count++ if $journal_part == 1;
700 $db_count++ if $journal_part == 2;
701 $wal_count++ if $journal_part == 3;
702 $bluestore = 1 if $journal_part == 4;
704 $partitions->{$part}->{journals
} = 1 if $journal_part == 1;
705 $partitions->{$part}->{db
} = 1 if $journal_part == 2;
706 $partitions->{$part}->{wal
} = 1 if $journal_part == 3;
707 $partitions->{$part}->{bluestore
} = 1 if $journal_part == 4;
711 my $used = $determine_usage->($devpath, $sysdir, 0);
712 if (!$include_partitions) {
713 foreach my $part (sort keys %{$partitions}) {
714 next if $partitions->{$part}->{used
} eq 'partition';
715 $used //= $partitions->{$part}->{used
};
718 # fstype might be set even if there are partitions, but showing that is confusing
719 $used = 'partitions' if scalar(keys %{$partitions});
721 $used //= 'partitions' if scalar(keys %{$partitions});
722 # multipath, software raid, etc.
723 # this check comes in last, to show more specific info
725 $used //= 'Device Mapper' if !dir_is_empty
("$sysdir/holders");
727 $disklist->{$dev}->{used
} = $used if $used;
729 $collect_ceph_info->($devpath);
731 $disklist->{$dev}->{osdid
} = $osdid;
732 $disklist->{$dev}->{journals
} = $journal_count if $journal_count;
733 $disklist->{$dev}->{bluestore
} = $bluestore if $osdid != -1;
734 $disklist->{$dev}->{osdencrypted
} = $osdencrypted if $osdid != -1;
735 $disklist->{$dev}->{db
} = $db_count if $db_count;
736 $disklist->{$dev}->{wal
} = $wal_count if $wal_count;
738 if ($include_partitions) {
739 foreach my $part (keys %{$partitions}) {
740 $disklist->{$part} = $partitions->{$part};
750 my ($part_path) = @_;
752 my $st = stat($part_path);
754 die "error detecting block device '$part_path'\n"
755 if !$st || !$st->mode || !S_ISBLK
($st->mode) || !$st->rdev;
757 my $major = PVE
::Tools
::dev_t_major
($st->rdev);
758 my $minor = PVE
::Tools
::dev_t_minor
($st->rdev);
759 my $partnum_path = "/sys/dev/block/$major:$minor/";
763 $partnum = file_read_firstline
("${partnum_path}partition");
765 die "Partition does not exist\n" if !defined($partnum);
767 #untaint and ensure it is a int
768 if ($partnum =~ m/(\d+)/) {
770 die "Partition number $partnum is invalid\n" if $partnum > 128;
772 die "Failed to get partition number\n";
779 my ($part_path) = @_;
781 my ($dev, $block_dev);
782 if ($part_path =~ m
|^/dev/(.*)$|) {
784 my $link = readlink "/sys/class/block/$dev";
785 $block_dev = $1 if $link =~ m
|([^/]*)/$dev$|;
788 die "Can't parse parent device\n" if !defined($block_dev);
789 die "No valid block device\n" if index($dev, $block_dev) == -1;
791 $block_dev = "/dev/$block_dev";
792 die "Block device does not exsists\n" if !(-b
$block_dev);
797 sub locked_disk_action
{
799 my $res = PVE
::Tools
::lock_file
('/run/lock/pve-diskmanage.lck', undef, $sub);
804 sub assert_disk_unused
{
807 die "device '$dev' is already in use\n" if disk_is_used
($dev);
812 sub append_partition
{
813 my ($dev, $size) = @_;
816 $devname =~ s
|^/dev/||;
819 dir_glob_foreach
("/sys/block/$devname", qr
/\Q
$devname\E.*?
(\d
+)/, sub {
820 my ($part, $partid) = @_;
822 if ($partid >= $newpartid) {
823 $newpartid = $partid + 1;
827 $size = PVE
::Tools
::convert_size
($size, 'b' => 'mb');
829 run_command
([ $SGDISK, '-n', "$newpartid:0:+${size}M", $dev ],
830 errmsg
=> "error creating partition '$newpartid' on '$dev'");
834 # loop again to detect the real partiton device which does not always follow
835 # a strict $devname$partition scheme like /dev/nvme0n1 -> /dev/nvme0n1p1
836 dir_glob_foreach
("/sys/block/$devname", qr
/\Q
$devname\E.*$newpartid/, sub {
839 $partition = "/dev/$part";
845 # Wipes all labels and the first 200 MiB of a disk/partition (or the whole if it is smaller).
846 # Expected to be called with a result of verify_blockdev_path().
850 my $wipefs_cmd = ['wipefs', '--all', $devpath];
852 my $dd_cmd = ['dd', 'if=/dev/zero', "of=${devpath}", 'bs=1M', 'conv=fdatasync'];
854 my $devname = basename
($devpath);
855 my $dev_size = PVE
::Tools
::file_get_contents
("/sys/class/block/$devname/size");
857 ($dev_size) = $dev_size =~ m
|(\d
+)|; # untaint $dev_size
858 die "Couldn't get the size of the device $devname\n" if !defined($dev_size);
860 my $size = ($dev_size * 512 / 1024 / 1024);
861 my $count = ($size < 200) ?
$size : 200;
863 push @{$dd_cmd}, "count=${count}";
865 print "wiping disk/partition: ${devpath}\n";
867 run_command
($wipefs_cmd, errmsg
=> "error wiping labels for '${devpath}'");
868 run_command
($dd_cmd, errmsg
=> "error wiping '${devpath}'");